summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/pkg/matcher/expr_test.go
blob: 93a1832266a72155941f683bd7838c5928cb7a05 (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
98
99
100
// SPDX-License-Identifier: GPL-3.0-or-later

package matcher

import (
	"testing"

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

func TestSimpleExpr_none(t *testing.T) {
	expr := &SimpleExpr{}

	m, err := expr.Parse()
	assert.EqualError(t, err, ErrEmptyExpr.Error())
	assert.Nil(t, m)
}

func TestSimpleExpr_include(t *testing.T) {
	expr := &SimpleExpr{
		Includes: []string{
			"~ /api/",
			"~ .php$",
		},
	}

	m, err := expr.Parse()
	assert.NoError(t, err)

	assert.True(t, m.MatchString("/api/a.php"))
	assert.True(t, m.MatchString("/api/a.php2"))
	assert.True(t, m.MatchString("/api2/a.php"))
	assert.True(t, m.MatchString("/api/img.php"))
	assert.False(t, m.MatchString("/api2/img.php2"))
}

func TestSimpleExpr_exclude(t *testing.T) {
	expr := &SimpleExpr{
		Excludes: []string{
			"~ /api/img",
		},
	}

	m, err := expr.Parse()
	assert.NoError(t, err)

	assert.True(t, m.MatchString("/api/a.php"))
	assert.True(t, m.MatchString("/api/a.php2"))
	assert.True(t, m.MatchString("/api2/a.php"))
	assert.False(t, m.MatchString("/api/img.php"))
	assert.True(t, m.MatchString("/api2/img.php2"))
}

func TestSimpleExpr_both(t *testing.T) {
	expr := &SimpleExpr{
		Includes: []string{
			"~ /api/",
			"~ .php$",
		},
		Excludes: []string{
			"~ /api/img",
		},
	}

	m, err := expr.Parse()
	assert.NoError(t, err)

	assert.True(t, m.MatchString("/api/a.php"))
	assert.True(t, m.MatchString("/api/a.php2"))
	assert.True(t, m.MatchString("/api2/a.php"))
	assert.False(t, m.MatchString("/api/img.php"))
	assert.False(t, m.MatchString("/api2/img.php2"))
}

func TestSimpleExpr_Parse_NG(t *testing.T) {
	{
		expr := &SimpleExpr{
			Includes: []string{
				"~ (ab",
				"~ .php$",
			},
		}

		m, err := expr.Parse()
		assert.Error(t, err)
		assert.Nil(t, m)
	}
	{
		expr := &SimpleExpr{
			Excludes: []string{
				"~ (ab",
				"~ .php$",
			},
		}

		m, err := expr.Parse()
		assert.Error(t, err)
		assert.Nil(t, m)
	}
}