Debian Codegraph @

debian/missing-sources/github.com/google/cel-go/ext/formatting_v2_test.go

raw symbols SCIP
1 // Copyright 2020 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 "math"
20 "reflect"
21 "strings"
22 "testing"
23 "time"
24
25 "google.golang.org/protobuf/proto"
26
27 "github.com/google/cel-go/cel"
28 "github.com/google/cel-go/checker"
29 "github.com/google/cel-go/common/types"
30 "github.com/google/cel-go/common/types/ref"
31
32 proto3pb "github.com/google/cel-go/test/proto3pb"
33 )
34
35 func TestStringsWithExtensionV2(t *testing.T) {
36 env, err := cel.NewEnv(Strings())
37 if err != nil {
38 t.Fatalf("cel.NewEnv(Strings()) failed: %v", err)
39 }
40 _, err = env.Extend(Strings())
41 if err != nil {
42 t.Fatalf("env.Extend(Strings()) failed: %v", err)
43 }
44 }
45
46 func TestStringFormatV2(t *testing.T) {
47 tests := []struct {
48 name string
49 format string
50 dynArgs map[string]any
51 formatArgs string
52 err string
53 expectedOutput string
54 expectedRuntimeCost uint64
55 expectedEstimatedCost checker.CostEstimate
56 skipCompileCheck bool
57 }{
58 {
59 name: "no-op",
60 format: "no substitution",
61 expectedOutput: "no substitution",
62 expectedRuntimeCost: 12,
63 expectedEstimatedCost: checker.CostEstimate{Min: 12, Max: 12},
64 },
65
66 {
67 name: "mid-string substitution",
68 format: "str is %s and some more",
69 formatArgs: `"filler"`,
70 expectedOutput: "str is filler and some more",
71 expectedRuntimeCost: 13,
72 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
73 },
74 {
75 name: "percent escaping",
76 format: "%% and also %%",
77 expectedOutput: "% and also %",
78 expectedRuntimeCost: 12,
79 expectedEstimatedCost: checker.CostEstimate{Min: 12, Max: 12},
80 },
81 {
82 name: "substution inside escaped percent signs",
83 format: "%%%s%%",
84 formatArgs: `"text"`,
85 expectedOutput: "%text%",
86 expectedRuntimeCost: 11,
87 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
88 },
89 {
90 name: "substitution with one escaped percent sign on the right",
91 format: "%s%%",
92 formatArgs: `"percent on the right"`,
93 expectedOutput: "percent on the right%",
94 expectedRuntimeCost: 11,
95 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
96 },
97 {
98 name: "substitution with one escaped percent sign on the left",
99 format: "%%%s",
100 formatArgs: `"percent on the left"`,
101 expectedOutput: "%percent on the left",
102 expectedRuntimeCost: 11,
103 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
104 },
105 {
106 name: "multiple substitutions",
107 format: "%d %d %d, %s %s %s, %d %d %d, %s %s %s",
108 formatArgs: `1, 2, 3, "A", "B", "C", 4, 5, 6, "D", "E", "F"`,
109 expectedOutput: "1 2 3, A B C, 4 5 6, D E F",
110 expectedRuntimeCost: 14,
111 expectedEstimatedCost: checker.CostEstimate{Min: 14, Max: 14},
112 },
113 {
114 name: "percent sign escape sequence support",
115 format: "\u0025\u0025escaped \u0025s\u0025\u0025",
116 formatArgs: `"percent"`,
117 expectedOutput: "%escaped percent%",
118 expectedRuntimeCost: 12,
119 expectedEstimatedCost: checker.FixedCostEstimate(12),
120 },
121 {
122 name: "fixed point formatting clause",
123 format: "%.3f",
124 formatArgs: "1.2345",
125 expectedOutput: "1.234",
126 expectedRuntimeCost: 11,
127 expectedEstimatedCost: checker.FixedCostEstimate(11),
128 },
129 {
130 name: "fixed point formatting clause with int",
131 format: "%.3f + %.2f",
132 formatArgs: "1, 1u",
133 expectedOutput: "1.000 + 1.00",
134 expectedRuntimeCost: 12,
135 expectedEstimatedCost: checker.FixedCostEstimate(12),
136 },
137 {
138 name: "binary formatting clause",
139 format: "this is 5 in binary: %b",
140 formatArgs: "5",
141 expectedOutput: "this is 5 in binary: 101",
142 expectedRuntimeCost: 13,
143 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
144 },
145 {
146 name: "negative binary formatting clause",
147 format: "this is -5 in binary: %b",
148 formatArgs: "-5",
149 expectedOutput: "this is -5 in binary: -101",
150 expectedRuntimeCost: 13,
151 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
152 },
153 {
154 name: "uint support for binary formatting",
155 format: "unsigned 64 in binary: %b",
156 formatArgs: "uint(64)",
157 expectedOutput: "unsigned 64 in binary: 1000000",
158 expectedRuntimeCost: 14,
159 expectedEstimatedCost: checker.CostEstimate{Min: 14, Max: 14},
160 },
161 {
162 name: "bool support for binary formatting",
163 format: "bit set from bool: %b",
164 formatArgs: "true",
165 expectedOutput: "bit set from bool: 1",
166 expectedRuntimeCost: 13,
167 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
168 },
169 {
170 name: "octal formatting clause",
171 format: "%o",
172 formatArgs: "11",
173 expectedOutput: "13",
174 expectedRuntimeCost: 11,
175 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
176 },
177 {
178 name: "negative octal formatting clause",
179 format: "%o",
180 formatArgs: "-11",
181 expectedOutput: "-13",
182 expectedRuntimeCost: 11,
183 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
184 },
185 {
186 name: "uint support for octal formatting clause",
187 format: "this is an unsigned octal: %o",
188 formatArgs: "uint(65535)",
189 expectedOutput: "this is an unsigned octal: 177777",
190 expectedRuntimeCost: 14,
191 expectedEstimatedCost: checker.CostEstimate{Min: 14, Max: 14},
192 },
193 {
194 name: "lowercase hexadecimal formatting clause",
195 format: "%x is 30 in hexadecimal",
196 formatArgs: "30",
197 expectedOutput: "1e is 30 in hexadecimal",
198 expectedRuntimeCost: 13,
199 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
200 },
201 {
202 name: "uppercase hexadecimal formatting clause",
203 format: "%X is 20 in hexadecimal",
204 formatArgs: "30",
205 expectedOutput: "1E is 20 in hexadecimal",
206 expectedRuntimeCost: 13,
207 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
208 },
209 {
210 name: "negative hexadecimal formatting clause",
211 format: "%x is -30 in hexadecimal",
212 formatArgs: "-30",
213 expectedOutput: "-1e is -30 in hexadecimal",
214 expectedRuntimeCost: 13,
215 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
216 },
217 {
218 name: "unsigned support for hexadecimal formatting clause",
219 format: "%X is 6000 in hexadecimal",
220 formatArgs: "uint(6000)",
221 expectedOutput: "1770 is 6000 in hexadecimal",
222 expectedRuntimeCost: 14,
223 expectedEstimatedCost: checker.CostEstimate{Min: 14, Max: 14},
224 },
225 {
226 name: "string support with hexadecimal formatting clause",
227 format: "%x",
228 formatArgs: `"Hello world!"`,
229 expectedOutput: "48656c6c6f20776f726c6421",
230 expectedRuntimeCost: 11,
231 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
232 },
233 {
234 name: "string support with uppercase hexadecimal formatting clause",
235 format: "%X",
236 formatArgs: `"Hello world!"`,
237 expectedOutput: "48656C6C6F20776F726C6421",
238 expectedRuntimeCost: 11,
239 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
240 },
241 {
242 name: "byte support with hexadecimal formatting clause",
243 format: "%x",
244 formatArgs: `b"byte string"`,
245 expectedOutput: "6279746520737472696e67",
246 expectedRuntimeCost: 11,
247 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
248 },
249 {
250 name: "byte support with hexadecimal formatting clause leading zero",
251 format: "%x",
252 formatArgs: `b"\x00\x00byte string\x00"`,
253 expectedOutput: "00006279746520737472696e6700",
254 expectedRuntimeCost: 11,
255 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
256 },
257 {
258 name: "byte support with uppercase hexadecimal formatting clause",
259 format: "%X",
260 formatArgs: `b"byte string"`,
261 expectedOutput: "6279746520737472696E67",
262 expectedRuntimeCost: 11,
263 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
264 },
265 {
266 name: "scientific notation formatting clause",
267 format: "%.6e",
268 formatArgs: "1052.032911275",
269 expectedOutput: "1.052033e+03",
270 expectedRuntimeCost: 11,
271 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
272 },
273 {
274 name: "scientific notation formatting clause with uint",
275 format: "%.4e",
276 formatArgs: "1052u",
277 expectedOutput: "1.0520e+03",
278 expectedRuntimeCost: 11,
279 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
280 },
281 {
282 name: "scientific notation formatting clause with int",
283 format: "%.5e",
284 formatArgs: "1052",
285 expectedOutput: "1.05200e+03",
286 expectedRuntimeCost: 11,
287 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
288 },
289 {
290 name: "default precision for fixed-point clause",
291 format: "%f",
292 formatArgs: "2.71828",
293 expectedOutput: "2.718280",
294 expectedRuntimeCost: 11,
295 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
296 },
297 {
298 name: "default precision for scientific notation",
299 format: "%e",
300 formatArgs: "2.71828",
301 expectedOutput: "2.718280e+00",
302 expectedRuntimeCost: 11,
303 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
304 },
305 {
306 name: "default precision for string",
307 format: "%s",
308 formatArgs: "2.71",
309 expectedOutput: "2.71",
310 expectedRuntimeCost: 11,
311 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
312 },
313 {
314 name: "default list precision for string",
315 format: "%s",
316 formatArgs: "[2.71]",
317 expectedOutput: "[2.71]",
318 expectedRuntimeCost: 21,
319 expectedEstimatedCost: checker.CostEstimate{Min: 21, Max: 21},
320 },
321 {
322 name: "default format for string",
323 format: "%s",
324 formatArgs: "0.000000002",
325 expectedOutput: "0.000000002",
326 expectedRuntimeCost: 11,
327 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
328 },
329 {
330 name: "default list scientific notation for string",
331 format: "%s",
332 formatArgs: "[0.000000002]",
333 expectedOutput: "[0.000000002]",
334 expectedRuntimeCost: 21,
335 expectedEstimatedCost: checker.CostEstimate{Min: 21, Max: 21},
336 },
337 {
338 name: "NaN support for fixed-point",
339 format: "%f",
340 formatArgs: `double("NaN")`,
341 expectedOutput: "NaN",
342 expectedRuntimeCost: 12,
343 expectedEstimatedCost: checker.CostEstimate{Min: 12, Max: 12},
344 },
345 {
346 name: "positive infinity support for fixed-point",
347 format: "%f",
348 formatArgs: `double("Infinity")`,
349 expectedOutput: "Infinity",
350 expectedRuntimeCost: 12,
351 expectedEstimatedCost: checker.CostEstimate{Min: 12, Max: 12},
352 },
353 {
354 name: "negative infinity support for fixed-point",
355 format: "%f",
356 formatArgs: `double("-Infinity")`,
357 expectedOutput: "-Infinity",
358 expectedRuntimeCost: 12,
359 expectedEstimatedCost: checker.CostEstimate{Min: 12, Max: 12},
360 },
361 {
362 name: "NaN support for string",
363 format: "%s",
364 formatArgs: `double("NaN")`,
365 expectedOutput: "NaN",
366 },
367 {
368 name: "positive infinity support for string",
369 format: "%s",
370 formatArgs: `double("Infinity")`,
371 expectedOutput: "Infinity",
372 },
373 {
374 name: "negative infinity support for string",
375 format: "%s",
376 formatArgs: `double("-Infinity")`,
377 expectedOutput: "-Infinity",
378 },
379 {
380 name: "infinity list support for string",
381 format: "%s",
382 formatArgs: `[double("NaN"),double("+Infinity"), double("-Infinity")]`,
383 expectedOutput: `[NaN, Infinity, -Infinity]`,
384 },
385 {
386 name: "uint support for decimal clause",
387 format: "%d",
388 formatArgs: "uint(64)",
389 expectedOutput: "64",
390 expectedRuntimeCost: 12,
391 expectedEstimatedCost: checker.CostEstimate{Min: 12, Max: 12},
392 },
393 {
394 name: "null support for string",
395 format: "null: %s",
396 formatArgs: "null",
397 expectedOutput: "null: null",
398 expectedRuntimeCost: 11,
399 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
400 },
401 {
402 name: "int support for string",
403 format: "%s",
404 formatArgs: `999999999999`,
405 expectedOutput: "999999999999",
406 expectedRuntimeCost: 11,
407 expectedEstimatedCost: checker.CostEstimate{Min: 11, Max: 11},
408 },
409 {
410 name: "bytes support for string",
411 format: "some bytes: %s",
412 formatArgs: `b"xyz"`,
413 expectedOutput: "some bytes: xyz",
414 expectedRuntimeCost: 12,
415 expectedEstimatedCost: checker.CostEstimate{Min: 12, Max: 12},
416 },
417 {
418 name: "type() support for string",
419 format: "type is %s",
420 formatArgs: `type("test string")`,
421 expectedOutput: "type is string",
422 expectedRuntimeCost: 12,
423 expectedEstimatedCost: checker.CostEstimate{Min: 12, Max: 12},
424 },
425 {
426 name: "timestamp support for string",
427 format: "%s",
428 formatArgs: `timestamp("2023-02-03T23:31:20+00:00")`,
429 expectedOutput: "2023-02-03T23:31:20Z",
430 expectedRuntimeCost: 12,
431 expectedEstimatedCost: checker.CostEstimate{Min: 12, Max: 12},
432 },
433 {
434 name: "duration support for string",
435 format: "%s",
436 formatArgs: `duration("1h45m47s")`,
437 expectedOutput: "6347s",
438 expectedRuntimeCost: 12,
439 expectedEstimatedCost: checker.CostEstimate{Min: 12, Max: 12},
440 },
441 {
442 name: "small duration support for string",
443 format: "%s",
444 formatArgs: `duration("2ns")`,
445 expectedOutput: "0.000000002s",
446 expectedRuntimeCost: 12,
447 expectedEstimatedCost: checker.CostEstimate{Min: 12, Max: 12},
448 },
449 {
450 name: "list support for string",
451 format: "%s",
452 formatArgs: `["abc", 3.14, null, [9, 8, 7, 6], timestamp("2023-02-03T23:31:20Z")]`,
453 expectedOutput: `[abc, 3.14, null, [9, 8, 7, 6], 2023-02-03T23:31:20Z]`,
454 expectedRuntimeCost: 32,
455 expectedEstimatedCost: checker.CostEstimate{Min: 32, Max: 32},
456 },
457 {
458 name: "map support for string",
459 format: "%s",
460 formatArgs: `{"key1": b"xyz", "key5": null, "key2": duration("2h"), "key4": true, "key3": 2.71828}`,
461 expectedOutput: `{key1: xyz, key2: 7200s, key3: 2.71828, key4: true, key5: null}`,
462 expectedRuntimeCost: 42,
463 expectedEstimatedCost: checker.CostEstimate{Min: 42, Max: 42},
464 },
465 {
466 name: "map support (all key types)",
467 format: "map with multiple key types: %s",
468 formatArgs: `{1: "value1", uint(2): "value2", true: double("NaN")}`,
469 expectedOutput: `map with multiple key types: {1: value1, 2: value2, true: NaN}`,
470 expectedRuntimeCost: 46,
471 expectedEstimatedCost: checker.CostEstimate{Min: 46, Max: 46},
472 },
473 {
474 name: "boolean support for %s",
475 format: "true bool: %s, false bool: %s",
476 formatArgs: `true, false`,
477 expectedOutput: "true bool: true, false bool: false",
478 expectedRuntimeCost: 13,
479 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
480 },
481 {
482 name: "dyntype support for string formatting clause",
483 format: "dynamic string: %s",
484 formatArgs: `dynStr`,
485 dynArgs: map[string]any{
486 "dynStr": "a string",
487 },
488 expectedOutput: "dynamic string: a string",
489 expectedRuntimeCost: 13,
490 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
491 },
492 {
493 name: "dyntype support for numbers with string formatting clause",
494 format: "dynIntStr: %s dynDoubleStr: %s",
495 formatArgs: `dynIntStr, dynDoubleStr`,
496 dynArgs: map[string]any{
497 "dynIntStr": 32,
498 "dynDoubleStr": 56.8,
499 },
500 expectedOutput: "dynIntStr: 32 dynDoubleStr: 56.8",
501 expectedRuntimeCost: 15,
502 expectedEstimatedCost: checker.CostEstimate{Min: 15, Max: 15},
503 },
504 {
505 name: "dyntype support for integer formatting clause",
506 format: "dynamic int: %d",
507 formatArgs: `dynInt`,
508 dynArgs: map[string]any{
509 "dynInt": 128,
510 },
511 expectedOutput: "dynamic int: 128",
512 expectedRuntimeCost: 13,
513 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
514 },
515 {
516 name: "dyntype support for integer formatting clause (unsigned)",
517 format: "dynamic unsigned int: %d",
518 formatArgs: `dynUnsignedInt`,
519 dynArgs: map[string]any{
520 "dynUnsignedInt": uint64(256),
521 },
522 expectedOutput: "dynamic unsigned int: 256",
523 expectedRuntimeCost: 14,
524 expectedEstimatedCost: checker.CostEstimate{Min: 14, Max: 14},
525 },
526 {
527 name: "dyntype support for hex formatting clause",
528 format: "dynamic hex int: %x",
529 formatArgs: `dynHexInt`,
530 dynArgs: map[string]any{
531 "dynHexInt": 22,
532 },
533 expectedOutput: "dynamic hex int: 16",
534 expectedRuntimeCost: 13,
535 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
536 },
537 {
538 name: "dyntype support for hex formatting clause (uppercase)",
539 format: "dynamic hex int: %X (uppercase)",
540 formatArgs: `dynHexInt`,
541 dynArgs: map[string]any{
542 "dynHexInt": 26,
543 },
544 expectedOutput: "dynamic hex int: 1A (uppercase)",
545 expectedRuntimeCost: 15,
546 expectedEstimatedCost: checker.CostEstimate{Min: 15, Max: 15},
547 },
548 {
549 name: "dyntype support for unsigned hex formatting clause",
550 format: "dynamic hex int: %x (unsigned)",
551 formatArgs: `dynUnsignedHexInt`,
552 dynArgs: map[string]any{
553 "dynUnsignedHexInt": uint(500),
554 },
555 expectedOutput: "dynamic hex int: 1f4 (unsigned)",
556 expectedRuntimeCost: 14,
557 expectedEstimatedCost: checker.CostEstimate{Min: 14, Max: 14},
558 },
559 {
560 name: "dyntype support for fixed-point formatting clause",
561 format: "dynamic double: %.3f",
562 formatArgs: `dynDouble`,
563 dynArgs: map[string]any{
564 "dynDouble": 4.5,
565 },
566 expectedOutput: "dynamic double: 4.500",
567 expectedRuntimeCost: 13,
568 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
569 },
570 {
571 name: "dyntype support for scientific notation",
572 format: "(dyntype) e: %e",
573 formatArgs: "dynE",
574 dynArgs: map[string]any{
575 "dynE": 2.71828,
576 },
577 expectedOutput: "(dyntype) e: 2.718280e+00",
578 expectedRuntimeCost: 13,
579 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
580 },
581 {
582 name: "dyntype NaN/infinity support for decimal",
583 format: "NaN: %d, infinity: %d, -infinity: %d",
584 formatArgs: `dynNaN, dynInf, dynNegInf`,
585 dynArgs: map[string]any{
586 "dynNaN": math.NaN(),
587 "dynInf": math.Inf(1),
588 "dynNegInf": math.Inf(-1),
589 },
590 expectedOutput: "NaN: NaN, infinity: Infinity, -infinity: -Infinity",
591 expectedRuntimeCost: 17,
592 expectedEstimatedCost: checker.FixedCostEstimate(17),
593 },
594 {
595 name: "dyntype NaN/infinity support for fixed-point",
596 format: "NaN: %f, infinity: %f",
597 formatArgs: `dynNaN, dynInf`,
598 dynArgs: map[string]any{
599 "dynNaN": math.NaN(),
600 "dynInf": math.Inf(1),
601 },
602 expectedOutput: "NaN: NaN, infinity: Infinity",
603 expectedRuntimeCost: 15,
604 expectedEstimatedCost: checker.CostEstimate{Min: 15, Max: 15},
605 },
606 {
607 name: "dyntype NaN/infinity support for scientific",
608 format: "NaN: %e, infinity: %e, -infinity: %e",
609 formatArgs: `dynNaN, dynInf, dynNegInf`,
610 dynArgs: map[string]any{
611 "dynNaN": math.NaN(),
612 "dynInf": math.Inf(1),
613 "dynNegInf": math.Inf(-1),
614 },
615 expectedOutput: "NaN: NaN, infinity: Infinity, -infinity: -Infinity",
616 expectedRuntimeCost: 17,
617 expectedEstimatedCost: checker.FixedCostEstimate(17),
618 },
619 {
620 name: "dyntype support for timestamp",
621 format: "dyntype timestamp: %s",
622 formatArgs: `dynTime`,
623 dynArgs: map[string]any{
624 "dynTime": time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC),
625 },
626 expectedOutput: "dyntype timestamp: 2009-11-10T23:00:00Z",
627 expectedRuntimeCost: 14,
628 expectedEstimatedCost: checker.CostEstimate{Min: 14, Max: 14},
629 },
630 {
631 name: "dyntype support for duration",
632 format: "dyntype duration: %s",
633 formatArgs: `dynDuration`,
634 dynArgs: map[string]any{
635 "dynDuration": mustParseDuration("2h25m47s"),
636 },
637 expectedOutput: "dyntype duration: 8747s",
638 expectedRuntimeCost: 13,
639 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
640 },
641 {
642 name: "dyntype support for lists",
643 format: "dyntype list: %s",
644 formatArgs: `dynList`,
645 dynArgs: map[string]any{
646 "dynList": []any{6, 4.2, "a string"},
647 },
648 expectedOutput: `dyntype list: [6, 4.2, a string]`,
649 expectedRuntimeCost: 13,
650 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
651 },
652 {
653 name: "dyntype support for maps",
654 format: "dyntype map: %s",
655 formatArgs: `dynMap`,
656 dynArgs: map[string]any{
657 "dynMap": map[any]any{
658 "strKey": "x",
659 true: 42,
660 int64(6): mustParseDuration("7m2s"),
661 },
662 },
663 expectedOutput: `dyntype map: {6: 422s, strKey: x, true: 42}`,
664 expectedRuntimeCost: 13,
665 expectedEstimatedCost: checker.CostEstimate{Min: 13, Max: 13},
666 },
667 {
668 name: "message field support",
669 format: "message field msg.single_int32: %d, msg.single_double: %.1f",
670 formatArgs: `msg.single_int32, msg.single_double`,
671 dynArgs: map[string]any{
672 "msg": &proto3pb.TestAllTypes{
673 SingleInt32: 2,
674 SingleDouble: 1.0,
675 },
676 },
677 expectedOutput: `message field msg.single_int32: 2, msg.single_double: 1.0`,
678 },
679 {
680 name: "unrecognized formatting clause",
681 format: "%a",
682 formatArgs: "1",
683 skipCompileCheck: true,
684 err: "could not parse formatting clause: unrecognized formatting clause \"a\"",
685 },
686 {
687 name: "out of bounds arg index",
688 format: "%d %d %d",
689 formatArgs: "0, 1",
690 skipCompileCheck: true,
691 err: "index 2 out of range",
692 },
693 {
694 name: "string substitution is not allowed with binary clause",
695 format: "string is %b",
696 formatArgs: `"abc"`,
697 skipCompileCheck: true,
698 err: "error during formatting: only ints, uints, and bools can be formatted as binary, was given string",
699 },
700 {
701 name: "duration substitution not allowed with decimal clause",
702 format: "%d",
703 formatArgs: `duration("30m2s")`,
704 skipCompileCheck: true,
705 err: "error during formatting: decimal clause can only be used on ints, uints, and doubles, was given google.protobuf.Duration",
706 },
707 {
708 name: "string substitution not allowed with octal clause",
709 format: "octal: %o",
710 formatArgs: `"a string"`,
711 skipCompileCheck: true,
712 err: "error during formatting: octal clause can only be used on ints and uints, was given string",
713 },
714 {
715 name: "double substitution not allowed with hex clause",
716 format: "double is %x",
717 formatArgs: "0.5",
718 skipCompileCheck: true,
719 err: "error during formatting: only ints, uints, bytes, and strings can be formatted as hex, was given double",
720 },
721 {
722 name: "uppercase not allowed for scientific clause",
723 format: "double is %E",
724 formatArgs: "0.5",
725 skipCompileCheck: true,
726 err: `could not parse formatting clause: unrecognized formatting clause "E"`,
727 },
728 {
729 name: "object not allowed",
730 format: "object is %s",
731 formatArgs: `ext.TestAllTypes{PbVal: test.TestAllTypes{}}`,
732 skipCompileCheck: true,
733 err: "error during formatting: string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps, was given ext.TestAllTypes",
734 },
735 {
736 name: "object inside list",
737 format: "%s",
738 formatArgs: "[1, 2, ext.TestAllTypes{PbVal: test.TestAllTypes{}}]",
739 skipCompileCheck: true,
740 err: "error during formatting: string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps, was given ext.TestAllTypes",
741 },
742 {
743 name: "object inside map",
744 format: "%s",
745 formatArgs: `{1: "a", 2: ext.TestAllTypes{}}`,
746 skipCompileCheck: true,
747 err: "error during formatting: string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps, was given ext.TestAllTypes",
748 },
749 {
750 name: "null not allowed for %d",
751 format: "null: %d",
752 formatArgs: "null",
753 skipCompileCheck: true,
754 err: "error during formatting: decimal clause can only be used on ints, uints, and doubles, was given null_type",
755 },
756 {
757 name: "null not allowed for %e",
758 format: "null: %e",
759 formatArgs: "null",
760 skipCompileCheck: true,
761 err: "error during formatting: scientific clause can only be used on ints, uints, and doubles, was given null_type",
762 },
763 {
764 name: "null not allowed for %f",
765 format: "null: %f",
766 formatArgs: "null",
767 skipCompileCheck: true,
768 err: "error during formatting: fixed-point clause can only be used on ints, uints, and doubles, was given null_type",
769 },
770 {
771 name: "null not allowed for %x",
772 format: "null: %x",
773 formatArgs: "null",
774 skipCompileCheck: true,
775 err: "error during formatting: only ints, uints, bytes, and strings can be formatted as hex, was given null_type",
776 },
777 {
778 name: "null not allowed for %X",
779 format: "null: %X",
780 formatArgs: "null",
781 skipCompileCheck: true,
782 err: "error during formatting: only ints, uints, bytes, and strings can be formatted as hex, was given null_type",
783 },
784 {
785 name: "null not allowed for %b",
786 format: "null: %b",
787 formatArgs: "null",
788 skipCompileCheck: true,
789 err: "error during formatting: only ints, uints, and bools can be formatted as binary, was given null_type",
790 },
791 {
792 name: "null not allowed for %o",
793 format: "null: %o",
794 formatArgs: "null",
795 skipCompileCheck: true,
796 err: "error during formatting: octal clause can only be used on ints and uints, was given null_type",
797 },
798 {
799 name: "compile-time cardinality check (too few for string)",
800 format: "%s %s",
801 formatArgs: `"abc"`,
802 err: "index 1 out of range",
803 },
804 {
805 name: "compile-time cardinality check (too many for string)",
806 format: "%s %s",
807 formatArgs: `"abc", "def", "ghi"`,
808 err: "too many arguments supplied to string.format (expected 2, got 3)",
809 },
810 {
811 name: "compile-time syntax check (unexpected end of string)",
812 format: "filler %",
813 formatArgs: "",
814 err: "unexpected end of string",
815 },
816 {
817 name: "compile-time syntax check (unrecognized formatting clause)",
818 format: "%j",
819 // pass args here, otherwise the cardinality check will fail first
820 formatArgs: "123",
821 err: `could not parse formatting clause: unrecognized formatting clause "j"`,
822 },
823 {
824 name: "compile-time %s check",
825 format: "object is %s",
826 formatArgs: `ext.TestAllTypes{PbVal: test.TestAllTypes{}}`,
827 err: "error during formatting: string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps",
828 },
829 {
830 name: "compile-time check for objects inside list literal",
831 format: "list is %s",
832 formatArgs: `[1, 2, ext.TestAllTypes{PbVal: test.TestAllTypes{}}]`,
833 err: "error during formatting: string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps",
834 },
835 {
836 name: "compile-time %d check",
837 format: "int is %d",
838 formatArgs: "null",
839 err: "error during formatting: decimal clause can only be used on ints, uints, and doubles, was given null_type",
840 },
841 {
842 name: "compile-time %f check",
843 format: "double is %f",
844 formatArgs: "true",
845 err: "error during formatting: fixed-point clause can only be used on ints, uints, and doubles, was given bool",
846 },
847 {
848 name: "compile-time precision syntax check",
849 format: "double is %.34",
850 formatArgs: "5.0",
851 err: "could not parse formatting clause: error while parsing precision: could not find end of precision specifier",
852 },
853 {
854 name: "compile-time %e check",
855 format: "double is %e",
856 formatArgs: "true",
857 err: "error during formatting: scientific clause can only be used on ints, uints, and doubles, was given bool",
858 },
859 {
860 name: "compile-time %b check",
861 format: "string is %b",
862 formatArgs: `"a string"`,
863 err: "error during formatting: only ints, uints, and bools can be formatted as binary, was given string",
864 },
865 {
866 name: "compile-time %x check",
867 format: "%x is a double",
868 formatArgs: "2.5",
869 err: "error during formatting: only ints, uints, bytes, and strings can be formatted as hex, was given double",
870 },
871 {
872 name: "compile-time %X check",
873 format: "%X is a double",
874 formatArgs: "2.5",
875 err: "error during formatting: only ints, uints, bytes, and strings can be formatted as hex, was given double",
876 },
877 {
878 name: "compile-time %o check",
879 format: "an octal: %o",
880 formatArgs: "3.14",
881 err: "octal clause can only be used on ints and uints, was given double",
882 },
883 }
884 evalExpr := func(env *cel.Env, expr string, evalArgs any, expectedRuntimeCost uint64, expectedEstimatedCost checker.CostEstimate, t *testing.T) (ref.Val, error) {
885 t.Logf("evaluating expr: %s", expr)
886 parsedAst, issues := env.Parse(expr)
887 if issues.Err() != nil {
888 t.Fatalf("env.Parse(%v) failed: %v", expr, issues.Err())
889 }
890 checkedAst, issues := env.Check(parsedAst)
891 if issues.Err() != nil {
892 return nil, issues.Err()
893 }
894 evalOpts := make([]cel.ProgramOption, 0)
895 costTracker := &noopCostEstimator{}
896 if expectedRuntimeCost != 0 {
897 evalOpts = append(evalOpts, cel.CostTracking(costTracker))
898 }
899 program, err := env.Program(checkedAst, evalOpts...)
900 if err != nil {
901 return nil, err
902 }
903
904 actualEstimatedCost, err := env.EstimateCost(checkedAst, costTracker)
905 if err != nil {
906 t.Fatal(err)
907 }
908 if expectedEstimatedCost.Min != 0 && expectedEstimatedCost.Max != 0 {
909 if actualEstimatedCost.Min != expectedEstimatedCost.Min && actualEstimatedCost.Max != expectedEstimatedCost.Max {
910 t.Fatalf("expected estimated cost range to be %v, was %v", expectedEstimatedCost, actualEstimatedCost)
911 }
912 }
913
914 var out ref.Val
915 var details *cel.EvalDetails
916 if evalArgs != nil {
917 out, details, err = program.Eval(evalArgs)
918 } else {
919 out, details, err = program.Eval(cel.NoVars())
920 }
921
922 if expectedRuntimeCost != 0 {
923 if details == nil {
924 t.Fatal("no EvalDetails available when runtime cost was expected")
925 }
926 if *details.ActualCost() != expectedRuntimeCost {
927 t.Fatalf("expected runtime cost to be %d, was %d", expectedRuntimeCost, *details.ActualCost())
928 }
929 if expectedEstimatedCost.Min != 0 && expectedEstimatedCost.Max != 0 {
930 if *details.ActualCost() < expectedEstimatedCost.Min || *details.ActualCost() > expectedEstimatedCost.Max {
931 t.Fatalf("runtime cost %d outside of expected estimated cost range %v", *details.ActualCost(), expectedEstimatedCost)
932 }
933 }
934 }
935 return out, err
936 }
937 buildVariables := func(vars map[string]any) []cel.EnvOption {
938 opts := make([]cel.EnvOption, len(vars))
939 i := 0
940 for name, value := range vars {
941 t := cel.DynType
942 switch v := value.(type) {
943 case proto.Message:
944 t = cel.ObjectType(string(v.ProtoReflect().Descriptor().FullName()))
945 case types.Bool:
946 t = cel.BoolType
947 case types.Bytes:
948 t = cel.BytesType
949 case types.Double:
950 t = cel.DoubleType
951 case types.Duration:
952 t = cel.DurationType
953 case types.Int:
954 t = cel.IntType
955 case types.Null:
956 t = cel.NullType
957 case types.String:
958 t = cel.StringType
959 case types.Timestamp:
960 t = cel.TimestampType
961 case types.Uint:
962 t = cel.UintType
963 }
964 opts[i] = cel.Variable(name, t)
965 i++
966 }
967 return opts
968 }
969 buildOpts := func(skipCompileCheck bool, variables []cel.EnvOption) []cel.EnvOption {
970 opts := []cel.EnvOption{
971 Strings(StringsValidateFormatCalls(!skipCompileCheck)),
972 cel.Container("ext"),
973 cel.Abbrevs("google.expr.proto3.test"),
974 cel.Types(&proto3pb.TestAllTypes{}),
975 NativeTypes(
976 reflect.TypeOf(&TestNestedType{}),
977 reflect.ValueOf(&TestAllTypes{}),
978 ),
979 }
980 opts = append(opts, cel.ASTValidators(cel.ValidateHomogeneousAggregateLiterals()))
981 opts = append(opts, variables...)
982 return opts
983 }
984 runCase := func(format, formatArgs string, dynArgs map[string]any, skipCompileCheck bool, expectedRuntimeCost uint64, expectedEstimatedCost checker.CostEstimate, t *testing.T) (ref.Val, error) {
985 env, err := cel.NewEnv(buildOpts(skipCompileCheck, buildVariables(dynArgs))...)
986 if err != nil {
987 t.Fatalf("cel.NewEnv() failed: %v", err)
988 }
989 expr := fmt.Sprintf("%q.format([%s])", format, formatArgs)
990 if len(dynArgs) == 0 {
991 return evalExpr(env, expr, cel.NoVars(), expectedRuntimeCost, expectedEstimatedCost, t)
992 }
993 return evalExpr(env, expr, dynArgs, expectedRuntimeCost, expectedEstimatedCost, t)
994 }
995 checkCase := func(output ref.Val, expectedOutput string, err error, expectedErr string, t *testing.T) {
996 if err != nil {
997 if expectedErr != "" {
998 if !strings.Contains(err.Error(), expectedErr) {
999 t.Fatalf("expected %q as error message, got %q", expectedErr, err.Error())
1000 }
1001 } else {
1002 t.Fatalf("unexpected error: %s", err)
1003 }
1004 } else {
1005 if output.Type() != types.StringType {
1006 t.Fatalf("expected test expr to eval to string (got %s instead)", output.Type().TypeName())
1007 } else {
1008 outputStr := output.Value().(string)
1009 if outputStr != expectedOutput {
1010 t.Errorf("expected %q as output, got %q", expectedOutput, outputStr)
1011 }
1012 }
1013 }
1014 }
1015 for _, tt := range tests {
1016 t.Run(tt.name, func(t *testing.T) {
1017 out, err := runCase(tt.format, tt.formatArgs, tt.dynArgs, tt.skipCompileCheck, tt.expectedRuntimeCost, tt.expectedEstimatedCost, t)
1018 checkCase(out, tt.expectedOutput, err, tt.err, t)
1019 })
1020 }
1021 }
1022
1023 func TestStringFormatHeterogeneousLiteralsV2(t *testing.T) {
1024 tests := []struct {
1025 expr string
1026 out string
1027 }{
1028 {
1029 expr: `"list: %s".format([[[1, 2, [3.0, 4]]]])`,
1030 out: `list: [[1, 2, [3, 4]]]`,
1031 },
1032 {
1033 expr: `"list size: %d".format([[[1, 2, [3.0, 4]]].size()])`,
1034 out: `list size: 1`,
1035 },
1036 {
1037 expr: `"list element: %s".format([[[1, 2, [3.0, 4]]][0]])`,
1038 out: `list element: [1, 2, [3, 4]]`,
1039 },
1040 }
1041 env, err := cel.NewEnv(Strings(), cel.ASTValidators(cel.ValidateHomogeneousAggregateLiterals()))
1042 if err != nil {
1043 t.Fatalf("cel.NewEnv() failed: %v", err)
1044 }
1045 for _, tst := range tests {
1046 tc := tst
1047 t.Run(tc.expr, func(t *testing.T) {
1048 ast, iss := env.Compile(tc.expr)
1049 if iss.Err() != nil {
1050 t.Fatalf("env.Compile(%q) failed: %v", tc.expr, iss.Err())
1051 }
1052 prg, err := env.Program(ast)
1053 if err != nil {
1054 t.Fatalf("env.Program() failed: %v", err)
1055 }
1056 out, _, err := prg.Eval(cel.NoVars())
1057 if err != nil {
1058 t.Fatalf("Eval() failed: %v", err)
1059 }
1060 if out.Value() != tc.out {
1061 t.Errorf("Eval() got %v, wanted %v", out, tc.out)
1062 }
1063 })
1064 }
1065 }