Debian Codegraph @

ext/formatting_test.go

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