github.com/cilki/sh@v2.6.4+incompatible/syntax/pattern_test.go (about) 1 // Copyright (c) 2017, Daniel Martà <mvdan@mvdan.cc> 2 // See LICENSE for licensing information 3 4 package syntax 5 6 import ( 7 "fmt" 8 rsyntax "regexp/syntax" 9 "testing" 10 ) 11 12 var translateTests = []struct { 13 pattern string 14 greedy bool 15 want string 16 wantErr bool 17 }{ 18 {``, false, ``, false}, 19 {`foo`, false, `foo`, false}, 20 {`.`, false, `\.`, false}, 21 {`foo*`, false, `foo.*?`, false}, 22 {`foo*`, true, `foo.*`, false}, 23 {`\*`, false, `\*`, false}, 24 {`\`, false, "", true}, 25 {`?`, false, `.`, false}, 26 {`\a`, false, `a`, false}, 27 {`(`, false, `\(`, false}, 28 {`a|b`, false, `a\|b`, false}, 29 {`x{3}`, false, `x\{3\}`, false}, 30 {`[a]`, false, `[a]`, false}, 31 {`[abc]`, false, `[abc]`, false}, 32 {`[^bc]`, false, `[^bc]`, false}, 33 {`[!bc]`, false, `[^bc]`, false}, 34 {`[[]`, false, `[[]`, false}, 35 {`[]]`, false, `[]]`, false}, 36 {`[^]]`, false, `[^]]`, false}, 37 {`[`, false, "", true}, 38 {`[]`, false, "", true}, 39 {`[^]`, false, "", true}, 40 {`[ab`, false, "", true}, 41 {`[a-]`, false, `[a-]`, false}, 42 {`[z-a]`, false, "", true}, 43 {`[a-a]`, false, "[a-a]", false}, 44 {`[aa]`, false, `[aa]`, false}, 45 {`[0-4A-Z]`, false, `[0-4A-Z]`, false}, 46 {`[-a]`, false, "[-a]", false}, 47 {`[^-a]`, false, "[^-a]", false}, 48 {`[a-]`, false, "[a-]", false}, 49 {`[[:digit:]]`, false, `[[:digit:]]`, false}, 50 {`[[:`, false, "", true}, 51 {`[[:digit`, false, "", true}, 52 {`[[:wrong:]]`, false, "", true}, 53 {`[[=x=]]`, false, "", true}, 54 {`[[.x.]]`, false, "", true}, 55 } 56 57 func TestTranslatePattern(t *testing.T) { 58 t.Parallel() 59 for i, tc := range translateTests { 60 t.Run(fmt.Sprintf("%02d", i), func(t *testing.T) { 61 got, gotErr := TranslatePattern(tc.pattern, tc.greedy) 62 if tc.wantErr && gotErr == nil { 63 t.Fatalf("(%q, %v) did not error", 64 tc.pattern, tc.greedy) 65 } 66 if !tc.wantErr && gotErr != nil { 67 t.Fatalf("(%q, %v) errored with %q", 68 tc.pattern, tc.greedy, gotErr) 69 } 70 if got != tc.want { 71 t.Fatalf("(%q, %v) got %q, wanted %q", 72 tc.pattern, tc.greedy, got, tc.want) 73 } 74 _, rxErr := rsyntax.Parse(got, rsyntax.Perl) 75 if gotErr == nil && rxErr != nil { 76 t.Fatalf("regexp/syntax.Parse(%q) failed with %q", 77 got, rxErr) 78 } 79 }) 80 } 81 } 82 83 var quoteTests = []struct { 84 pattern string 85 want string 86 }{ 87 {``, ``}, 88 {`foo`, `foo`}, 89 {`.`, `.`}, 90 {`*`, `\*`}, 91 {`foo?`, `foo\?`}, 92 {`\[`, `\\\[`}, 93 } 94 95 func TestQuotePattern(t *testing.T) { 96 t.Parallel() 97 for _, tc := range quoteTests { 98 got := QuotePattern(tc.pattern) 99 if got != tc.want { 100 t.Errorf("QuotePattern(%q) got %q, wanted %q", 101 tc.pattern, got, tc.want) 102 } 103 } 104 }