cloudflare/pint
Publicmirrored from https://github.com/cloudflare/pintAvailable
internal/discovery/glob_test.go
100lines · modecode
| 1 | package discovery_test |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "io/ioutil" |
| 6 | "os" |
| 7 | "path" |
| 8 | "path/filepath" |
| 9 | "strconv" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | |
| 13 | "github.com/stretchr/testify/require" |
| 14 | |
| 15 | "github.com/cloudflare/pint/internal/discovery" |
| 16 | "github.com/cloudflare/pint/internal/parser" |
| 17 | ) |
| 18 | |
| 19 | func TestGlobPathFinder(t *testing.T) { |
| 20 | type testCaseT struct { |
| 21 | files map[string]string |
| 22 | finder discovery.GlobFinder |
| 23 | entries []discovery.Entry |
| 24 | err error |
| 25 | } |
| 26 | |
| 27 | p := parser.NewParser() |
| 28 | testRuleBody := "- record: foo\n expr: sum(foo)\n" |
| 29 | testRules, err := p.Parse([]byte(testRuleBody)) |
| 30 | require.NoError(t, err) |
| 31 | |
| 32 | testCases := []testCaseT{ |
| 33 | { |
| 34 | files: map[string]string{}, |
| 35 | finder: discovery.NewGlobFinder("[]"), |
| 36 | err: filepath.ErrBadPattern, |
| 37 | }, |
| 38 | { |
| 39 | files: map[string]string{}, |
| 40 | finder: discovery.NewGlobFinder("*"), |
| 41 | err: fmt.Errorf("no matching files"), |
| 42 | }, |
| 43 | { |
| 44 | files: map[string]string{}, |
| 45 | finder: discovery.NewGlobFinder("*"), |
| 46 | err: fmt.Errorf("no matching files"), |
| 47 | }, |
| 48 | { |
| 49 | files: map[string]string{}, |
| 50 | finder: discovery.NewGlobFinder("foo/*"), |
| 51 | err: fmt.Errorf("no matching files"), |
| 52 | }, |
| 53 | { |
| 54 | files: map[string]string{"bar.yml": testRuleBody}, |
| 55 | finder: discovery.NewGlobFinder("foo/*"), |
| 56 | err: fmt.Errorf("no matching files"), |
| 57 | }, |
| 58 | { |
| 59 | files: map[string]string{"bar.yml": testRuleBody}, |
| 60 | finder: discovery.NewGlobFinder("*"), |
| 61 | entries: []discovery.Entry{ |
| 62 | { |
| 63 | Path: "bar.yml", |
| 64 | Rule: testRules[0], |
| 65 | }, |
| 66 | }, |
| 67 | }, |
| 68 | { |
| 69 | files: map[string]string{"foo/bar.yml": testRuleBody}, |
| 70 | finder: discovery.NewGlobFinder("*"), |
| 71 | entries: []discovery.Entry{ |
| 72 | { |
| 73 | Path: "foo/bar.yml", |
| 74 | Rule: testRules[0], |
| 75 | }, |
| 76 | }, |
| 77 | }, |
| 78 | } |
| 79 | |
| 80 | for i, tc := range testCases { |
| 81 | t.Run(strconv.Itoa(i), func(t *testing.T) { |
| 82 | workdir := t.TempDir() |
| 83 | err := os.Chdir(workdir) |
| 84 | require.NoError(t, err) |
| 85 | |
| 86 | for p, content := range tc.files { |
| 87 | if strings.Contains(p, "/") { |
| 88 | err = os.MkdirAll(path.Dir(p), 0o755) |
| 89 | require.NoError(t, err) |
| 90 | } |
| 91 | err = ioutil.WriteFile(p, []byte(content), 0o644) |
| 92 | require.NoError(t, err) |
| 93 | } |
| 94 | |
| 95 | entries, err := tc.finder.Find() |
| 96 | require.Equal(t, tc.err, err) |
| 97 | require.Equal(t, tc.entries, entries) |
| 98 | }) |
| 99 | } |
| 100 | } |
| 101 | |