glob_test.go (2559B)
1 // Copyright 2021 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package glob
15
16 import (
17 "path/filepath"
18 "testing"
19
20 qt "github.com/frankban/quicktest"
21 )
22
23 func TestResolveRootDir(t *testing.T) {
24 c := qt.New(t)
25
26 for _, test := range []struct {
27 input string
28 expected string
29 }{
30 {"data/foo.json", "data"},
31 {"a/b/**/foo.json", "a/b"},
32 {"dat?a/foo.json", ""},
33 {"a/b[a-c]/foo.json", "a"},
34 } {
35 c.Assert(ResolveRootDir(test.input), qt.Equals, test.expected)
36 }
37 }
38
39 func TestFilterGlobParts(t *testing.T) {
40 c := qt.New(t)
41
42 for _, test := range []struct {
43 input []string
44 expected []string
45 }{
46 {[]string{"a", "*", "c"}, []string{"a", "c"}},
47 } {
48 c.Assert(FilterGlobParts(test.input), qt.DeepEquals, test.expected)
49 }
50 }
51
52 func TestNormalizePath(t *testing.T) {
53 c := qt.New(t)
54
55 for _, test := range []struct {
56 input string
57 expected string
58 }{
59 {filepath.FromSlash("data/FOO.json"), "data/foo.json"},
60 {filepath.FromSlash("/data/FOO.json"), "data/foo.json"},
61 {filepath.FromSlash("./FOO.json"), "foo.json"},
62 {"//", ""},
63 } {
64 c.Assert(NormalizePath(test.input), qt.Equals, test.expected)
65 }
66 }
67
68 func TestGetGlob(t *testing.T) {
69 for _, cache := range []*globCache{defaultGlobCache, filenamesGlobCache} {
70 c := qt.New(t)
71 g, err := cache.GetGlob("**.JSON")
72 c.Assert(err, qt.IsNil)
73 c.Assert(g.Match("data/my.jSon"), qt.Equals, true)
74 }
75 }
76
77 func BenchmarkGetGlob(b *testing.B) {
78
79 runBench := func(name string, cache *globCache, search string) {
80 b.Run(name, func(b *testing.B) {
81 g, err := GetGlob("**/foo")
82 if err != nil {
83 b.Fatal(err)
84 }
85 for i := 0; i < b.N; i++ {
86 _ = g.Match(search)
87 }
88 })
89 }
90
91 runBench("Default cache", defaultGlobCache, "abcde")
92 runBench("Filenames cache, lowercase searchs", filenamesGlobCache, "abcde")
93 runBench("Filenames cache, mixed case searchs", filenamesGlobCache, "abCDe")
94
95 b.Run("GetGlob", func(b *testing.B) {
96 for i := 0; i < b.N; i++ {
97 _, err := GetGlob("**/foo")
98 if err != nil {
99 b.Fatal(err)
100 }
101 }
102 })
103 }