sigs.k8s.io/prow@v0.0.0-20240503223140-c5e374dc7eb1/pkg/gitattributes/pattern_test.go (about) 1 /* 2 Copyright 2019 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package gitattributes 18 19 import ( 20 "testing" 21 ) 22 23 func TestParsePattern(t *testing.T) { 24 var cases = []struct { 25 name string 26 pattern string 27 expectError bool 28 }{ 29 { 30 name: "file", 31 pattern: `abc.json`, 32 expectError: false, 33 }, 34 { 35 name: "negative file", 36 pattern: `!abc.json`, 37 expectError: true, 38 }, 39 { 40 name: "directory", 41 pattern: `abc/`, 42 expectError: true, 43 }, 44 { 45 name: "directory recursive", 46 pattern: `abc/**`, 47 expectError: false, 48 }, 49 { 50 name: "glob", 51 pattern: `a/*/c`, 52 expectError: false, 53 }, 54 { 55 name: "needs trim", 56 pattern: `abc.json `, 57 expectError: false, 58 }, 59 } 60 for _, c := range cases { 61 t.Run(c.name, func(t *testing.T) { 62 if _, err := parsePattern(c.pattern); err != nil && !c.expectError { 63 t.Fatalf("load error: %v", err) 64 } 65 }) 66 } 67 } 68 69 func TestMatch(t *testing.T) { 70 var cases = []struct { 71 name string 72 pattern string 73 path string 74 shouldMatch bool 75 }{ 76 { 77 name: "file", 78 pattern: `abc.json`, 79 path: "abc.json", 80 shouldMatch: true, 81 }, 82 { 83 name: "file in dir", 84 pattern: `abc.json`, 85 path: "a/abc.json", 86 shouldMatch: true, 87 }, 88 { 89 name: "file fail", 90 pattern: `abc.js`, 91 path: "abc.json", 92 shouldMatch: false, 93 }, 94 { 95 name: "glob", 96 pattern: `*.json`, 97 path: "abc.json", 98 shouldMatch: true, 99 }, 100 { 101 name: "glob in dir", 102 pattern: `a/*.json`, 103 path: "a/abc.json", 104 shouldMatch: true, 105 }, 106 { 107 name: "glob dir", 108 pattern: `*/abc.json`, 109 path: "a/abc.json", 110 shouldMatch: true, 111 }, 112 { 113 name: "glob dir fail", 114 pattern: `*/abc.json`, 115 path: "a/b/abc.json", 116 shouldMatch: false, 117 }, 118 { 119 name: "recursive file", 120 pattern: `**/abc.json`, 121 path: "a/b/abc.json", 122 shouldMatch: true, 123 }, 124 { 125 name: "recursive file fail", 126 pattern: `**/abc.js`, 127 path: "a/b/abc.json", 128 shouldMatch: false, 129 }, 130 { 131 name: "recursive dir", 132 pattern: `a/**`, 133 path: "a/b/abc.json", 134 shouldMatch: true, 135 }, 136 } 137 for _, c := range cases { 138 t.Run(c.name, func(t *testing.T) { 139 p, _ := parsePattern(c.pattern) 140 if p.Match(c.path) != c.shouldMatch { 141 t.Fatalf("mismatch") 142 } 143 }) 144 } 145 }