github.com/netdata/go.d.plugin@v0.58.1/pkg/matcher/glob_test.go (about) 1 // SPDX-License-Identifier: GPL-3.0-or-later 2 3 package matcher 4 5 import ( 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 func TestNewGlobMatcher(t *testing.T) { 12 cases := []struct { 13 expr string 14 matcher Matcher 15 }{ 16 {"", stringFullMatcher("")}, 17 {"a", stringFullMatcher("a")}, 18 {"a*b", globMatcher("a*b")}, 19 {`a*\b`, globMatcher(`a*\b`)}, 20 {`a\[`, stringFullMatcher(`a[`)}, 21 {`ab\`, nil}, 22 {`ab[`, nil}, 23 {`ab]`, stringFullMatcher("ab]")}, 24 } 25 for _, c := range cases { 26 t.Run(c.expr, func(t *testing.T) { 27 m, err := NewGlobMatcher(c.expr) 28 if c.matcher != nil { 29 assert.NoError(t, err) 30 assert.Equal(t, c.matcher, m) 31 } else { 32 assert.Error(t, err) 33 } 34 }) 35 } 36 } 37 38 func TestGlobMatcher_MatchString(t *testing.T) { 39 40 cases := []struct { 41 expected bool 42 expr string 43 line string 44 }{ 45 {true, "/a/*/d", "/a/b/c/d"}, 46 {true, "foo*", "foo123"}, 47 {true, "*foo*", "123foo123"}, 48 {true, "*foo", "123foo"}, 49 {true, "foo*bar", "foobar"}, 50 {true, "foo*bar", "foo baz bar"}, 51 {true, "a[bc]d", "abd"}, 52 {true, "a[^bc]d", "add"}, 53 {true, "a??d", "abcd"}, 54 {true, `a\??d`, "a?cd"}, 55 {true, "a[b-z]d", "abd"}, 56 {false, "/a/*/d", "a/b/c/d"}, 57 {false, "/a/*/d", "This will fail!"}, 58 } 59 60 for _, c := range cases { 61 t.Run(c.line, func(t *testing.T) { 62 m := globMatcher(c.expr) 63 assert.Equal(t, c.expected, m.Match([]byte(c.line))) 64 assert.Equal(t, c.expected, m.MatchString(c.line)) 65 }) 66 } 67 } 68 69 func BenchmarkGlob_MatchString(b *testing.B) { 70 benchmarks := []struct { 71 expr string 72 test string 73 }{ 74 {"", ""}, 75 {"abc", "abcd"}, 76 {"*abc", "abcd"}, 77 {"abc*", "abcd"}, 78 {"*abc*", "abcd"}, 79 {"[a-z]", "abcd"}, 80 } 81 for _, bm := range benchmarks { 82 b.Run(bm.expr+"_raw", func(b *testing.B) { 83 m := globMatcher(bm.expr) 84 b.ResetTimer() 85 for i := 0; i < b.N; i++ { 86 m.MatchString(bm.test) 87 } 88 }) 89 b.Run(bm.expr+"_optimized", func(b *testing.B) { 90 m, _ := NewGlobMatcher(bm.expr) 91 b.ResetTimer() 92 for i := 0; i < b.N; i++ { 93 m.MatchString(bm.test) 94 } 95 }) 96 } 97 }