Debian Codegraph @

ext/regex_test.go

raw
1 // Copyright 2025 Google LLC
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 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package ext
16
17 import (
18 "fmt"
19 "strings"
20 "testing"
21
22 "github.com/google/cel-go/cel"
23 "github.com/google/cel-go/checker"
24 )
25
26 func TestRegex(t *testing.T) {
27 regexTests := []struct {
28 expr string
29 }{
30 // Tests for replace Function
31 {expr: "regex.replace('abc', '^', 'start_') == 'start_abc'"},
32 {expr: "regex.replace('abc', '$', '_end') == 'abc_end'"},
33 {expr: `regex.replace('a-b', r'\b', '|') == '|a|-|b|'`},
34 {expr: `regex.replace('foo bar', '(fo)o (ba)r', r'\2 \1') == 'ba fo'`},
35 {expr: `regex.replace('foo bar', 'foo', r'\\') == '\\ bar'`},
36 {expr: "regex.replace('banana', 'ana', 'x') == 'bxna'"},
37 {expr: `regex.replace('abc', 'b(.)', r'x\1') == 'axc'`},
38 {expr: "regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'"},
39 {expr: `regex.replace('ac', 'a(b)?c', r'[\1]') == '[]'`},
40 {expr: "regex.replace('apple pie', 'p', 'X') == 'aXXle Xie'"},
41 {expr: `regex.replace('remove all spaces', r'\s', '') == 'removeallspaces'`},
42 {expr: `regex.replace('digit:99919291992', r'\d+', '3') == 'digit:3'`},
43 {expr: `regex.replace('foo bar baz', r'\w+', r'(\0)') == '(foo) (bar) (baz)'`},
44 {expr: "regex.replace('', 'a', 'b') == ''"},
45 {expr: `regex.replace('User: Alice, Age: 30', r'User: (?P<name>\w+), Age: (?P<age>\d+)', '${name} is ${age} years old') == '${name} is ${age} years old'`},
46 {expr: `regex.replace('User: Alice, Age: 30', r'User: (?P<name>\w+), Age: (?P<age>\d+)', r'\1 is \2 years old') == 'Alice is 30 years old'`},
47 {expr: "regex.replace('hello ☃', '☃', '❄') == 'hello ❄'"},
48 {expr: `regex.replace('id=123', r'id=(?P<value>\d+)', r'value: \1') == 'value: 123'`},
49 {expr: "regex.replace('banana', 'a', 'x') == 'bxnxnx'"},
50 {expr: `regex.replace(regex.replace('%(foo) %(bar) %2', r'%\((\w+)\)', r'${\1}'),r'%(\d+)', r'$\1') == '${foo} ${bar} $2'`},
51
52 // Tests for replace Function with count variable
53 {expr: "regex.replace('banana', 'a', 'x', 0) == 'banana'"},
54 {expr: "regex.replace('banana', 'a', 'x', 1) == 'bxnana'"},
55 {expr: "regex.replace('banana', 'a', 'x', 2) == 'bxnxna'"},
56 {expr: "regex.replace('banana', 'a', 'x', 100) == 'bxnxnx'"},
57 {expr: "regex.replace('banana', 'a', 'x', -1) == 'bxnxnx'"},
58 {expr: "regex.replace('banana', 'a', 'x', -100) == 'bxnxnx'"},
59 {expr: `regex.replace('cat-dog dog-cat cat-dog dog-cat', '(cat)-(dog)', r'\2-\1', 1) == 'dog-cat dog-cat cat-dog dog-cat'`},
60 {expr: `regex.replace('cat-dog dog-cat cat-dog dog-cat', '(cat)-(dog)', r'\2-\1', 2) == 'dog-cat dog-cat dog-cat dog-cat'`},
61 {expr: `regex.replace('a.b.c', r'\.', '-', 1) == 'a-b.c'`},
62 {expr: `regex.replace('a.b.c', r'\.', '-', -1) == 'a-b-c'`},
63 {expr: `regex.replace('abc def', r'(abc)', r'\\1') == r'\1 def'`},
64 {expr: `regex.replace('abc def', r'(abc)', r'\\2') == r'\2 def'`},
65 {expr: `regex.replace('abc def', r'(abc)', r'\\{word}') == '\\{word} def'`},
66 {expr: `regex.replace('abc def', r'(abc)', r'\\word') == '\\word def'`},
67
68 // Tests for extract Function
69 {expr: "regex.extract('hello world', 'hello(.*)') == optional.of(' world')"},
70 {expr: `regex.extract('item-A, item-B', r'item-(\w+)') == optional.of('A')`},
71 {expr: `regex.extract('The color is red', r'The color is (\w+)') == optional.of('red')`},
72 {expr: `regex.extract('The color is red', r'The color is \w+') == optional.of('The color is red')`},
73 {expr: "regex.extract('brand', 'brand') == optional.of('brand')"},
74 {expr: "regex.extract('hello world', 'goodbye (.*)') == optional.none()"},
75 {expr: "regex.extract('HELLO', 'hello') == optional.none()"},
76 {expr: `regex.extract('', r'\w+') == optional.none()`},
77 {expr: "regex.extract('4122345432', '22').or(optional.of('777')) == optional.of('22')"},
78 {expr: "regex.extract('4122345432', '22').orValue('777') == '22'"},
79
80 // Tests for extractAll Function
81 {expr: "regex.extractAll('id:123, id:456', 'assa') == []"},
82 {expr: `regex.extractAll('id:123, id:456', r'id:\d+') == ['id:123', 'id:456']`},
83 {expr: `regex.extractAll('Files: f_1.txt, f_2.csv', r'f_(\d+)') == ['1', '2']`},
84 {expr: "regex.extractAll('testuser@', '(?P<username>.*)@') == ['testuser']"},
85 {expr: "regex.extractAll('[email protected], [email protected], [email protected]', '(?P<username>.*)@') == ['[email protected], [email protected], 2312321wsamkldjq2w2']"},
86 {expr: `regex.extractAll('[email protected], [email protected], [email protected]', r'(?P<username>\w+)@') == ['testuser', 'a', '2312321wsamkldjq2w2']`},
87 {expr: "regex.extractAll('banananana', '(ana)') == ['ana', 'ana']"},
88 {expr: `regex.extractAll('item:a1, topic:b2', r'(?:item:|topic:)([a-z]\d)') == ['a1', 'b2']`},
89 {expr: "regex.extractAll('val=a, val=, val=c', 'val=([^,]*)') == ['a', 'c']"},
90 {expr: "regex.extractAll('key=, key=, key=', 'key=([^,]*)') == []"},
91 {expr: `regex.extractAll('a b c', r'(\S*)\s*') == ['a', 'b', 'c']`},
92 }
93
94 env := testRegexEnv(t)
95 for i, tst := range regexTests {
96 tr := tst // capture range variable
97 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
98 var asts []*cel.Ast
99 pAst, iss := env.Parse(tr.expr)
100 if iss.Err() != nil {
101 t.Fatalf("Parse(%s) failed: %v", tr.expr, iss.Err())
102 }
103 asts = append(asts, pAst)
104 cAst, iss := env.Check(pAst)
105 if iss.Err() != nil {
106 t.Fatalf("Check(%s) failed: %v", tr.expr, iss.Err())
107 }
108 asts = append(asts, cAst)
109
110 for _, ast := range asts {
111 prog, err := env.Program(ast)
112 if err != nil {
113 t.Fatalf("Program(%s) failed: %v", tr.expr, err)
114 }
115 out, _, err := prog.Eval(cel.NoVars())
116 if err != nil {
117 t.Fatalf("Eval(%s) failed: %v", tr.expr, err)
118 }
119 if out.Value() != true {
120 t.Errorf("Eval(%s) returned %v, want true", tr.expr, out.Value())
121 }
122 }
123 })
124 }
125 }
126
127 func TestRegexStaticErrors(t *testing.T) {
128 tests := []struct {
129 expr string
130 err string
131 }{
132 {
133 expr: "regex.replace('abc', '^', 1)",
134 err: "found no matching overload for 'regex.replace' applied to '(string, string, int)'",
135 },
136 {
137 expr: "regex.replace('abc', '^', '1','')",
138 err: "found no matching overload for 'regex.replace' applied to '(string, string, string, string)'",
139 },
140 {
141 expr: "regex.extract('foo bar', 1)",
142 err: "found no matching overload for 'regex.extract' applied to '(string, int)'",
143 },
144 {
145 expr: "regex.extract('foo bar', 1, 'bar')",
146 err: "found no matching overload for 'regex.extract' applied to '(string, int, string)'",
147 },
148 {
149 expr: "regex.extractAll()",
150 err: "found no matching overload for 'regex.extractAll' applied to '()'",
151 },
152 {
153 expr: "regex.replace('banana', 'a', 'x', 18446744073709551615)",
154 err: `ERROR: <input>:1:35: invalid int literal`,
155 },
156 }
157 env := testRegexEnv(t)
158 for i, tst := range tests {
159 tr := tst
160 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
161 _, iss := env.Compile(tr.expr)
162 if iss.Err() == nil || !strings.Contains(iss.Err().Error(), tr.err) {
163 t.Errorf("env.Compile(%q) got error %v, wanted %v", tr.expr, iss.Err(), tr.err)
164 }
165 })
166 }
167 }
168
169 func TestRegexRuntimeErrors(t *testing.T) {
170 tests := []struct {
171 expr string
172 err string
173 }{
174 {
175 expr: "regex.extract('foo bar', '(')",
176 err: "error parsing regexp: missing closing ): `(`",
177 },
178 {
179 expr: "regex.extractAll('foo bar', '[a-z')",
180 err: "error parsing regexp: missing closing ]: `[a-z`",
181 },
182 {
183 expr: `regex.replace('id=123', r'id=(?P<value>\d+)', r'value: \values')`,
184 err: `invalid replacement string: 'value: \values' \ must be followed by a digit`,
185 },
186 {
187 expr: `regex.replace('test', '(.)', r'\2')`,
188 err: "replacement string references group 2 but regex has only 1 group(s)",
189 },
190 {
191 expr: `regex.replace('id=123', r'id=(?P<value>\d+)', r'value: \')`,
192 err: `invalid replacement string: 'value: \' \ not allowed at end`,
193 },
194 {
195 expr: `regex.extract('phone: 415-5551212', r'phone: ((\d{3})-)?')`,
196 err: `regular expression has more than one capturing group: "phone: ((\\d{3})-)?"`,
197 },
198 {
199 expr: `regex.extractAll('Name: John Doe, Age:321', r'Name: (?P<Name>.*), Age:(?P<Age>\d+)')`,
200 err: `regular expression has more than one capturing group: "Name: (?P<Name>.*), Age:(?P<Age>\\d+)"`,
201 },
202 {
203 expr: `regex.extractAll('testuser@testdomain', '(.*)@([^.]*)')`,
204 err: `regular expression has more than one capturing group: "(.*)@([^.]*)"`,
205 },
206 {
207 expr: `regex.extractAll('The user testuser belongs to testdomain', 'The (user|domain) (?P<Username>.*) belongs (to) (?P<Domain>.*)')`,
208 err: `regular expression has more than one capturing group: "The (user|domain) (?P<Username>.*) belongs (to) (?P<Domain>.*)"`,
209 },
210 }
211
212 env := testRegexEnv(t)
213 for i, tst := range tests {
214 tr := tst
215 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
216 ast, iss := env.Compile(tr.expr)
217 if iss.Err() != nil {
218 t.Fatalf("env.Compile(%q) failed with error %v", tr.expr, iss.Err())
219 }
220 prg, err := env.Program(ast)
221 if err != nil {
222 t.Fatalf("env.Program(ast) failed: %v", err)
223 }
224 in := cel.NoVars()
225 _, _, err = prg.Eval(in)
226 if err == nil || !strings.Contains(err.Error(), tr.err) {
227 t.Errorf("prg.Eval() got %v, wanted %v", err, tr.err)
228 }
229 })
230 }
231 }
232
233 func TestRegexEnvCreationErrors(t *testing.T) {
234 tests := []struct {
235 name string
236 opts []cel.EnvOption
237 }{
238 {
239 name: "no optional types",
240 opts: []cel.EnvOption{Regex()},
241 },
242 {
243 name: "optional types after regex",
244 opts: []cel.EnvOption{Regex(), cel.OptionalTypes()},
245 },
246 }
247 for _, tc := range tests {
248 t.Run(tc.name, func(t *testing.T) {
249 _, err := cel.NewEnv(tc.opts...)
250 if err == nil || !strings.Contains(err.Error(), "regex library requires the optional library") {
251 t.Fatalf("prg.Eval() got %v, wanted regex library requires the optional library", err)
252 }
253 })
254 }
255 }
256
257 func TestRegexVersion(t *testing.T) {
258 _, err := cel.NewEnv(cel.OptionalTypes(), Regex(RegexVersion(0)))
259 if err != nil {
260 t.Fatalf("Regex(0) failed: %v", err)
261 }
262 }
263
264 func testRegexEnv(t *testing.T, opts ...cel.EnvOption) *cel.Env {
265 t.Helper()
266 baseOpts := []cel.EnvOption{
267 cel.OptionalTypes(),
268 Regex(),
269 }
270 env, err := cel.NewEnv(append(baseOpts, opts...)...)
271 if err != nil {
272 t.Fatalf("cel.NewEnv(Regex()) failed: %v", err)
273 }
274 return env
275 }
276
277 func TestRegexCosts(t *testing.T) {
278 tests := []struct {
279 expr string
280 vars []cel.EnvOption
281 in map[string]any
282 hints map[string]uint64
283 estimatedCost checker.CostEstimate
284 actualCost uint64
285 }{
286 {
287 expr: `regex.extract('hello world', 'hello (.*)') == optional.of('world')`,
288 estimatedCost: checker.CostEstimate{Min: 8, Max: 20},
289 actualCost: 8,
290 },
291 // - Estimated Cost (Min: 5): Derived from fixed costs of scanning 10-char
292 // target string and compiling 2-char regex. Since the inputs are constant,
293 // the Min estimate is very accurate.
294 // - Actual Cost (5): Observed cost is the sum of a base call cost (~1), the
295 // search cost, and the allocation cost for the 2-char result string '22'.
296 // It aligns perfectly with the minimum estimate.
297 {
298 expr: "regex.extract('4122345432', '22').orValue('777') == '22'",
299 estimatedCost: checker.CostEstimate{Min: 4, Max: 14},
300 actualCost: 4,
301 },
302 // .or() condition introduces runtime uncertainty, and since the cost estimator
303 // can't know which branch the code will take, it must prepare for the most
304 // expensive possible outcome resulting in an estimate.Max of ~ math.MaxUint64.
305 {
306 expr: "regex.extract('4122345432', '22').or(optional.of('777')) == optional.of('22')",
307 estimatedCost: checker.CostEstimate{Min: 6, Max: 1844674407370955279},
308 actualCost: 5,
309 },
310 {
311 expr: "regex.extract('hello world', 'goodbye (.*)') == optional.none()",
312 estimatedCost: checker.CostEstimate{Min: 10, Max: 22},
313 actualCost: 8,
314 },
315 {
316 expr: "regex.extractAll('id:123, id:456', 'assa') == []",
317 estimatedCost: checker.CostEstimate{Min: 24, Max: 38},
318 actualCost: 23,
319 },
320 // - Estimated Cost (Min: 25): Cost to scan the 14-char target and compile
321 // 5-char regex, plus a worst-case allocation cost for the result list's
322 // contents, which is estimated as the full 14-char size of the target.
323 // - Actual Cost (28): Observed cost includes the search cost plus the actual
324 // allocation cost, which is the base list creation cost plus the cost of
325 // allocating the two result strings, totaling 12 chars of content.
326 {
327 expr: `regex.extractAll('id:123, id:456', r'id:\d+') == ['id:123', 'id:456']`,
328 estimatedCost: checker.CostEstimate{Min: 25, Max: 39},
329 actualCost: 27,
330 },
331 {
332 expr: `regex.extractAll('a b c', r'(\S*)\s*') == ['a', 'b', 'c']`,
333 estimatedCost: checker.CostEstimate{Min: 24, Max: 29},
334 actualCost: 27,
335 },
336 {
337 expr: `regex.extractAll('[email protected], [email protected], [email protected]', r'(?P<username>\w+)@') == ['testuser', 'a', '2312321wsamkldjq2w2']`,
338 estimatedCost: checker.CostEstimate{Min: 51, Max: 108},
339 actualCost: 53,
340 },
341 {
342 expr: "regex.replace('hello world hello', 'hello', 'hi') == 'hi world hi'",
343 estimatedCost: checker.CostEstimate{Min: 22, Max: 40},
344 actualCost: 16,
345 },
346 {
347 expr: `regex.replace('ac', 'a(b)?c', r'[\1]') == '[]'`,
348 estimatedCost: checker.CostEstimate{Min: 5, Max: 11},
349 actualCost: 4,
350 },
351 {
352 expr: "regex.replace('apple pie', 'p', 'X') == 'aXXle Xie'",
353 estimatedCost: checker.CostEstimate{Min: 11, Max: 11},
354 actualCost: 11,
355 },
356 {
357 expr: "regex.replace('aaaaaa', 'a', '-what-') == '-what--what--what--what--what--what-'",
358 estimatedCost: checker.CostEstimate{Min: 8, Max: 41},
359 actualCost: 41,
360 },
361 // --- Constant Cost Cases ---
362 // These cases demonstrate that the cost is independent of the `count` arg.
363 // - Estimated Cost (9): Estimator does not evaluate the value of `count`.
364 // It assumes the worst case (all possible replacements) for any `count`.
365 // Since the other inputs are identical, the estimate is constant.
366 // - Actual Cost (9): The tracker's cost is also modeled on the worst case
367 // for consistency. The search phase of the operation scans the whole
368 // string for all matches, so the dominant cost is constant.
369 {
370 expr: "regex.replace('banana', 'a', 'x', 0) == 'banana'",
371 estimatedCost: checker.CostEstimate{Min: 8, Max: 8},
372 actualCost: 8,
373 },
374 {
375 expr: "regex.replace('banana', 'a', 'x', 1) == 'bxnana'",
376 estimatedCost: checker.CostEstimate{Min: 8, Max: 8},
377 actualCost: 8,
378 },
379 {
380 expr: "regex.replace('banana', 'a', 'x', 100) == 'bxnxnx'",
381 estimatedCost: checker.CostEstimate{Min: 8, Max: 8},
382 actualCost: 8,
383 },
384 {
385 expr: `regex.replace('foo bar', r'(foo bar)', r'\1\1\1\1\1' ) == 'foo barfoo barfoo barfoo barfoo bar'`,
386 estimatedCost: checker.CostEstimate{Min: 11, Max: 77},
387 actualCost: 42,
388 },
389 {
390 expr: `regex.replace('foo bar', r'(foo bar)', '') == ''`,
391 estimatedCost: checker.CostEstimate{Min: 3, Max: 10},
392 actualCost: 3,
393 },
394 }
395 for _, test := range tests {
396 tc := test
397 t.Run(tc.expr, func(t *testing.T) {
398 env := testRegexEnv(t, tc.vars...)
399 var asts []*cel.Ast
400 pAst, iss := env.Parse(tc.expr)
401 if iss.Err() != nil {
402 t.Fatalf("Parse(%s) failed: %v", tc.expr, iss.Err())
403 }
404 asts = append(asts, pAst)
405 cAst, iss := env.Check(pAst)
406 if iss.Err() != nil {
407 t.Fatalf("Check(%s) failed: %v", tc.expr, iss.Err())
408 }
409
410 testCheckCost(t, env, cAst, tc.hints, tc.estimatedCost)
411 asts = append(asts, cAst)
412 for _, ast := range asts {
413 testEvalWithCost(t, env, ast, tc.in, tc.actualCost)
414 }
415 })
416 }
417 }