summaryrefslogtreecommitdiffstats
path: root/src/go/pkg/matcher/glob_test.go
blob: 09d4561054848cec768a8adf6b95d51faa993597 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// SPDX-License-Identifier: GPL-3.0-or-later

package matcher

import (
	"testing"

	"github.com/stretchr/testify/assert"
)

func TestNewGlobMatcher(t *testing.T) {
	cases := []struct {
		expr    string
		matcher Matcher
	}{
		{"", stringFullMatcher("")},
		{"a", stringFullMatcher("a")},
		{"a*b", globMatcher("a*b")},
		{`a*\b`, globMatcher(`a*\b`)},
		{`a\[`, stringFullMatcher(`a[`)},
		{`ab\`, nil},
		{`ab[`, nil},
		{`ab]`, stringFullMatcher("ab]")},
	}
	for _, c := range cases {
		t.Run(c.expr, func(t *testing.T) {
			m, err := NewGlobMatcher(c.expr)
			if c.matcher != nil {
				assert.NoError(t, err)
				assert.Equal(t, c.matcher, m)
			} else {
				assert.Error(t, err)
			}
		})
	}
}

func TestGlobMatcher_MatchString(t *testing.T) {

	cases := []struct {
		expected bool
		expr     string
		line     string
	}{
		{true, "/a/*/d", "/a/b/c/d"},
		{true, "foo*", "foo123"},
		{true, "*foo*", "123foo123"},
		{true, "*foo", "123foo"},
		{true, "foo*bar", "foobar"},
		{true, "foo*bar", "foo baz bar"},
		{true, "a[bc]d", "abd"},
		{true, "a[^bc]d", "add"},
		{true, "a??d", "abcd"},
		{true, `a\??d`, "a?cd"},
		{true, "a[b-z]d", "abd"},
		{false, "/a/*/d", "a/b/c/d"},
		{false, "/a/*/d", "This will fail!"},
	}

	for _, c := range cases {
		t.Run(c.line, func(t *testing.T) {
			m := globMatcher(c.expr)
			assert.Equal(t, c.expected, m.Match([]byte(c.line)))
			assert.Equal(t, c.expected, m.MatchString(c.line))
		})
	}
}

func BenchmarkGlob_MatchString(b *testing.B) {
	benchmarks := []struct {
		expr string
		test string
	}{
		{"", ""},
		{"abc", "abcd"},
		{"*abc", "abcd"},
		{"abc*", "abcd"},
		{"*abc*", "abcd"},
		{"[a-z]", "abcd"},
	}
	for _, bm := range benchmarks {
		b.Run(bm.expr+"_raw", func(b *testing.B) {
			m := globMatcher(bm.expr)
			b.ResetTimer()
			for i := 0; i < b.N; i++ {
				m.MatchString(bm.test)
			}
		})
		b.Run(bm.expr+"_optimized", func(b *testing.B) {
			m, _ := NewGlobMatcher(bm.expr)
			b.ResetTimer()
			for i := 0; i < b.N; i++ {
				m.MatchString(bm.test)
			}
		})
	}
}