| 1 |
// Copyright 2024 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 |
"github.com/google/cel-go/common/types" |
| 25 |
"github.com/google/cel-go/interpreter" |
| 26 |
) |
| 27 |
|
| 28 |
func TestTwoVarComprehensions(t *testing.T) { |
| 29 |
compreTests := []struct { |
| 30 |
expr string |
| 31 |
}{ |
| 32 |
// list.all() |
| 33 |
{expr: "[1, 2, 3, 4].all(i, v, i < 5 && v > 0)"}, |
| 34 |
{expr: "[1, 2, 3, 4].all(i, v, i < v)"}, |
| 35 |
{expr: "[1, 2, 3, 4].all(i, v, i > v) == false"}, |
| 36 |
{expr: ` |
| 37 |
cel.bind(listA, [1, 2, 3, 4], |
| 38 |
cel.bind(listB, [1, 2, 3, 4, 5], |
| 39 |
listA.all(i, v, listB[?i].hasValue() && listB[i] == v) |
| 40 |
)) |
| 41 |
`}, |
| 42 |
{expr: ` |
| 43 |
cel.bind(listA, [1, 2, 3, 4, 5, 6], |
| 44 |
cel.bind(listB, [1, 2, 3, 4, 5], |
| 45 |
listA.all(i, v, listB[?i].hasValue() && listB[i] == v) |
| 46 |
)) == false |
| 47 |
`}, |
| 48 |
// list.exists() |
| 49 |
{expr: ` |
| 50 |
cel.bind(l, ['hello', 'world', 'hello!', 'worlds'], |
| 51 |
l.exists(i, v, |
| 52 |
v.startsWith('hello') && l[?(i+1)].optMap(next, next.endsWith('world')).orValue(false) |
| 53 |
) |
| 54 |
) |
| 55 |
`}, |
| 56 |
// list.existsOne() |
| 57 |
{expr: ` |
| 58 |
cel.bind(l, ['hello', 'world', 'hello!', 'worlds'], |
| 59 |
l.existsOne(i, v, |
| 60 |
v.startsWith('hello') && l[?(i+1)].optMap(next, next.endsWith('world')).orValue(false) |
| 61 |
) |
| 62 |
) |
| 63 |
`}, |
| 64 |
{expr: ` |
| 65 |
cel.bind(l, ['hello', 'goodbye', 'hello!', 'goodbye'], |
| 66 |
l.exists_one(i, v, |
| 67 |
v.startsWith('hello') && l[?(i+1)].optMap(next, next == "goodbye").orValue(false) |
| 68 |
) |
| 69 |
) == false |
| 70 |
`}, |
| 71 |
// list.transformList() |
| 72 |
{expr: ` |
| 73 |
['Hello', 'world'].transformList(i, v, "[%d]%s".format([i, v.lowerAscii()])) == ["[0]hello", "[1]world"] |
| 74 |
`}, |
| 75 |
{expr: ` |
| 76 |
['hello', 'world'].transformList(i, v, v.startsWith('greeting'), "[%d]%s".format([i, v])) == [] |
| 77 |
`}, |
| 78 |
{expr: ` |
| 79 |
[1, 2, 3].transformList(indexVar, valueVar, (indexVar * valueVar) + valueVar) == [1, 4, 9] |
| 80 |
`}, |
| 81 |
{expr: ` |
| 82 |
[1, 2, 3].transformList(indexVar, valueVar, indexVar % 2 == 0, (indexVar * valueVar) + valueVar) == [1, 9] |
| 83 |
`}, |
| 84 |
// list.transformMap() |
| 85 |
{expr: ` |
| 86 |
['Hello', 'world'].transformMap(i, v, [v.lowerAscii()]) == {0: ['hello'], 1: ['world']} |
| 87 |
`}, |
| 88 |
{expr: ` |
| 89 |
// round-tripping example |
| 90 |
['world', 'Hello'].transformMap(i, v, [v.lowerAscii()]) |
| 91 |
.transformList(k, v, v) // extract the list back form the map |
| 92 |
.flatten() |
| 93 |
.sort() == ['hello', 'world'] |
| 94 |
`}, |
| 95 |
{expr: ` |
| 96 |
[1, 2, 3].transformMap(indexVar, valueVar, |
| 97 |
(indexVar * valueVar) + valueVar) == {0: 1, 1: 4, 2: 9} |
| 98 |
`}, |
| 99 |
{expr: ` |
| 100 |
[1, 2, 3].transformMap(indexVar, valueVar, indexVar % 2 == 0, |
| 101 |
(indexVar * valueVar) + valueVar) == {0: 1, 2: 9} |
| 102 |
`}, |
| 103 |
// list.transformMapEntry() |
| 104 |
{expr: ` |
| 105 |
"key1:value1 key2:value2 key3:value3".split(" ") |
| 106 |
.transformMapEntry(i, v, |
| 107 |
cel.bind(entry, v.split(":"), |
| 108 |
entry.size() == 2 ? {entry[0]: entry[1]} : {} |
| 109 |
) |
| 110 |
) == {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} |
| 111 |
`}, |
| 112 |
{expr: ` |
| 113 |
"key1:value1:extra key2:value2 key3".split(" ") |
| 114 |
.transformMapEntry(i, v, |
| 115 |
cel.bind(entry, v.split(":"), {?entry[0]: entry[?1]}) |
| 116 |
) == {'key1': 'value1', 'key2': 'value2'} |
| 117 |
`}, |
| 118 |
// map.all() |
| 119 |
{expr: ` |
| 120 |
{'hello': 'world', 'hello!': 'world'}.all(k, v, k.startsWith('hello') && v == 'world') |
| 121 |
`}, |
| 122 |
{expr: ` |
| 123 |
{'hello': 'world', 'hello!': 'worlds'}.all(k, v, k.startsWith('hello') && v.endsWith('world')) == false |
| 124 |
`}, |
| 125 |
// map.exists() |
| 126 |
{expr: ` |
| 127 |
{'hello': 'world', 'hello!': 'worlds'}.exists(k, v, k.startsWith('hello') && v.endsWith('world')) |
| 128 |
`}, |
| 129 |
// map.existsOne() |
| 130 |
{expr: ` |
| 131 |
{'hello': 'world', 'hello!': 'worlds'}.existsOne(k, v, k.startsWith('hello') && v.endsWith('world')) |
| 132 |
`}, |
| 133 |
// map.exists_one() |
| 134 |
{expr: ` |
| 135 |
{'hello': 'world', 'hello!': 'worlds'}.exists_one(k, v, k.startsWith('hello') && v.endsWith('world')) |
| 136 |
`}, |
| 137 |
{expr: ` |
| 138 |
{'hello': 'world', 'hello!': 'wow, world'}.exists_one(k, v, k.startsWith('hello') && v.endsWith('world')) == false |
| 139 |
`}, |
| 140 |
// map.transformList() |
| 141 |
{expr: ` |
| 142 |
{'Hello': 'world'}.transformList(k, v, "%s=%s".format([k.lowerAscii(), v])) == ["hello=world"] |
| 143 |
`}, |
| 144 |
{expr: ` |
| 145 |
dyn({'Hello': 'world'}).transformList(k, v, "%s=%s".format([k.lowerAscii(), v])) == ["hello=world"] |
| 146 |
`}, |
| 147 |
{expr: ` |
| 148 |
{'hello': 'world'}.transformList(k, v, k.startsWith('greeting'), "%s=%s".format([k, v])) == [] |
| 149 |
`}, |
| 150 |
{expr: ` |
| 151 |
{'greeting': 'hello', 'farewell': 'goodbye'} |
| 152 |
.transformList(k, _, k).sort() == ['farewell', 'greeting'] |
| 153 |
`}, |
| 154 |
{expr: ` |
| 155 |
{'greeting': 'hello', 'farewell': 'goodbye'} |
| 156 |
.transformList(_, v, v).sort() == ['goodbye', 'hello'] |
| 157 |
`}, |
| 158 |
// map.transformMap() |
| 159 |
{expr: ` |
| 160 |
{'hello': 'world', 'goodbye': 'cruel world'}.transformMap(k, v, "%s, %s!".format([k, v])) |
| 161 |
== {'hello': 'hello, world!', 'goodbye': 'goodbye, cruel world!'} |
| 162 |
`}, |
| 163 |
{expr: ` |
| 164 |
dyn({'hello': 'world', 'goodbye': 'cruel world'}).transformMap(k, v, "%s, %s!".format([k, v])) |
| 165 |
== {'hello': 'hello, world!', 'goodbye': 'goodbye, cruel world!'} |
| 166 |
`}, |
| 167 |
{expr: ` |
| 168 |
{'hello': 'world', 'goodbye': 'cruel world'}.transformMap(k, v, v.startsWith('world'), "%s, %s!".format([k, v])) |
| 169 |
== {'hello': 'hello, world!'} |
| 170 |
`}, |
| 171 |
// map.transformMapEntry() |
| 172 |
{expr: ` |
| 173 |
{'hello': 'world', 'greetings': 'tacocat'}.transformMapEntry(k, v, {k.reverse(): v.reverse()}) |
| 174 |
== {'olleh': 'dlrow', 'sgniteerg': 'tacocat'} |
| 175 |
`}, |
| 176 |
{expr: ` |
| 177 |
{'hello': 'world', 'greetings': 'tacocat'}.transformMapEntry(k, v, v.reverse() == v, {k.reverse(): v.reverse()}) |
| 178 |
== {'sgniteerg': 'tacocat'} |
| 179 |
`}, |
| 180 |
{expr: ` |
| 181 |
{'hello': 'world', 'greetings': 'tacocat'}.transformMapEntry(k, v, {}) == {} |
| 182 |
`}, |
| 183 |
} |
| 184 |
|
| 185 |
env := testCompreEnv(t) |
| 186 |
for i, tst := range compreTests { |
| 187 |
tc := tst |
| 188 |
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { |
| 189 |
var asts []*cel.Ast |
| 190 |
pAst, iss := env.Parse(tc.expr) |
| 191 |
if iss.Err() != nil { |
| 192 |
t.Fatalf("env.Parse(%v) failed: %v", tc.expr, iss.Err()) |
| 193 |
} |
| 194 |
asts = append(asts, pAst) |
| 195 |
cAst, iss := env.Check(pAst) |
| 196 |
if iss.Err() != nil { |
| 197 |
t.Fatalf("env.Check(%v) failed: %v", tc.expr, iss.Err()) |
| 198 |
} |
| 199 |
asts = append(asts, cAst) |
| 200 |
|
| 201 |
for _, ast := range asts { |
| 202 |
prg, err := env.Program(ast) |
| 203 |
if err != nil { |
| 204 |
t.Fatalf("env.Program() failed: %v", err) |
| 205 |
} |
| 206 |
out, _, err := prg.Eval(cel.NoVars()) |
| 207 |
if err != nil { |
| 208 |
t.Fatalf("prg.Eval() failed: %v", err) |
| 209 |
} |
| 210 |
if out.Value() != true { |
| 211 |
t.Errorf("prg.Eval() got %v, wanted true for expr: %s", out.Value(), tc.expr) |
| 212 |
} |
| 213 |
} |
| 214 |
}) |
| 215 |
} |
| 216 |
} |
| 217 |
|
| 218 |
func TestTwoVarComprehensionsCost(t *testing.T) { |
| 219 |
tests := []struct { |
| 220 |
name string |
| 221 |
expr string |
| 222 |
vars []cel.EnvOption |
| 223 |
in map[string]any |
| 224 |
hints map[string]uint64 |
| 225 |
estimatedCost checker.CostEstimate |
| 226 |
actualCost uint64 |
| 227 |
}{ |
| 228 |
{ |
| 229 |
name: "all list literal", |
| 230 |
expr: `[1, 2, 3, 4].all(i, v, i < 5 && v > 0)`, |
| 231 |
estimatedCost: checker.CostEstimate{Min: 23, Max: 39}, |
| 232 |
actualCost: 39, |
| 233 |
}, |
| 234 |
{ |
| 235 |
name: "all map literal - true", |
| 236 |
expr: `{1: 1, 2: 2, 3: 3}.all(i, v, i < 5 && v > 0)`, |
| 237 |
estimatedCost: checker.CostEstimate{Min: 40, Max: 52}, |
| 238 |
actualCost: 52, |
| 239 |
}, |
| 240 |
{ |
| 241 |
name: "all map literal - false", |
| 242 |
expr: `!{0: 0}.all(i, v, i < 5 && v > 0)`, |
| 243 |
estimatedCost: checker.CostEstimate{Min: 35, Max: 39}, |
| 244 |
actualCost: 39, |
| 245 |
}, |
| 246 |
{ |
| 247 |
name: "all map(int,int) variable", |
| 248 |
expr: `m.all(i, v, i < 5 && v > 0)`, |
| 249 |
vars: []cel.EnvOption{cel.Variable("m", cel.MapType(cel.IntType, cel.IntType))}, |
| 250 |
hints: map[string]uint64{ |
| 251 |
"m": 3, |
| 252 |
}, |
| 253 |
in: map[string]any{ |
| 254 |
"m": map[int]int{1: 1, 2: 2}, |
| 255 |
}, |
| 256 |
estimatedCost: checker.CostEstimate{Min: 2, Max: 23}, |
| 257 |
actualCost: 16, |
| 258 |
}, |
| 259 |
{ |
| 260 |
name: "all map(string,string) variable", |
| 261 |
expr: `m.all(k, v, k < v)`, |
| 262 |
vars: []cel.EnvOption{cel.Variable("m", cel.MapType(cel.StringType, cel.StringType))}, |
| 263 |
hints: map[string]uint64{ |
| 264 |
"m": 3, |
| 265 |
"m.@keys": 16, |
| 266 |
"m.@values": 128, |
| 267 |
}, |
| 268 |
in: map[string]any{ |
| 269 |
"m": map[string]string{"he": "hello", "go": "goodbye"}, |
| 270 |
}, |
| 271 |
estimatedCost: checker.CostEstimate{Min: 2, Max: 23}, |
| 272 |
actualCost: 14, |
| 273 |
}, |
| 274 |
{ |
| 275 |
name: "transformList empty", |
| 276 |
expr: `[].transformList(i, v, v) == []`, |
| 277 |
estimatedCost: checker.FixedCostEstimate(31), |
| 278 |
actualCost: 31, |
| 279 |
}, |
| 280 |
{ |
| 281 |
name: "transformList single element", |
| 282 |
expr: `[1].transformList(i, v, i) == [0]`, |
| 283 |
estimatedCost: checker.FixedCostEstimate(45), |
| 284 |
actualCost: 45, |
| 285 |
}, |
| 286 |
{ |
| 287 |
name: "transformList with filter", |
| 288 |
expr: `[3, 2, 1].transformList(i, v, v > i, v) == [3, 2]`, |
| 289 |
estimatedCost: checker.CostEstimate{Min: 44, Max: 80}, |
| 290 |
actualCost: 67, |
| 291 |
}, |
| 292 |
{ |
| 293 |
name: "transformMap empty list", |
| 294 |
expr: `[].transformMap(k, v, v + 1) == {}`, |
| 295 |
estimatedCost: checker.FixedCostEstimate(71), |
| 296 |
actualCost: 71, |
| 297 |
}, |
| 298 |
{ |
| 299 |
name: "transformMap empty map", |
| 300 |
expr: `{}.transformMap(k, v, v + 1) == {}`, |
| 301 |
estimatedCost: checker.FixedCostEstimate(91), |
| 302 |
actualCost: 91, |
| 303 |
}, |
| 304 |
{ |
| 305 |
name: "transformMap literal scalar map", |
| 306 |
expr: `{1: 2}.transformMap(k, v, v + 1) == {1: 3}`, |
| 307 |
estimatedCost: checker.FixedCostEstimate(97), |
| 308 |
actualCost: 97, |
| 309 |
}, |
| 310 |
{ |
| 311 |
name: "transformMap local bind", |
| 312 |
expr: `cel.bind(m, {"hello": "hello"}, |
| 313 |
m.transformMap(k, v, v + "world")) == {"hello": "helloworld"}`, |
| 314 |
estimatedCost: checker.FixedCostEstimate(108), |
| 315 |
actualCost: 108, |
| 316 |
}, |
| 317 |
{ |
| 318 |
name: "transformMap filter map", |
| 319 |
expr: `{1: 2, 3: 4, 5: 6}.transformMap(k, v, k % 3 == 0, v + 1) == {3: 5}`, |
| 320 |
estimatedCost: checker.CostEstimate{Min: 104, Max: 116}, |
| 321 |
actualCost: 106, |
| 322 |
}, |
| 323 |
{ |
| 324 |
name: "transformMap variable input", |
| 325 |
expr: `m.transformMap(k, v, k.startsWith('legacy') && v.size() == 1, v + [2]) == {'legacy-solo': [1, 2]}`, |
| 326 |
vars: []cel.EnvOption{ |
| 327 |
cel.Variable("m", cel.MapType(cel.StringType, cel.ListType(cel.IntType))), |
| 328 |
}, |
| 329 |
in: map[string]any{ |
| 330 |
"m": map[string][]int{ |
| 331 |
"legacy-solo": {1}, |
| 332 |
"legacy-pair": {3, 2}, |
| 333 |
}, |
| 334 |
}, |
| 335 |
hints: map[string]uint64{ |
| 336 |
"m": 5, |
| 337 |
"m.@keys": 16, |
| 338 |
"m.@values": 10, |
| 339 |
"m.@values.@items": 2, |
| 340 |
}, |
| 341 |
estimatedCost: checker.CostEstimate{Min: 73, Max: 173}, |
| 342 |
actualCost: 100, |
| 343 |
}, |
| 344 |
{ |
| 345 |
name: "transformMapEntry literal input", |
| 346 |
expr: `{1: 2}.transformMapEntry(k, v, {v: k}) == {2: 1}`, |
| 347 |
estimatedCost: checker.FixedCostEstimate(126), |
| 348 |
actualCost: 126, |
| 349 |
}, |
| 350 |
{ |
| 351 |
name: "transformMapEntry variable input", |
| 352 |
expr: `m.transformMapEntry(k, v, {v: k}) == m.transformMapEntry(k, v, {v: k})`, |
| 353 |
vars: []cel.EnvOption{ |
| 354 |
cel.Variable("m", cel.MapType(cel.StringType, cel.IntType)), |
| 355 |
}, |
| 356 |
in: map[string]any{ |
| 357 |
"m": map[string]int{ |
| 358 |
"legacy-solo": 1, |
| 359 |
"legacy-pair": 2, |
| 360 |
}, |
| 361 |
}, |
| 362 |
hints: map[string]uint64{ |
| 363 |
"m": 5, |
| 364 |
"m.@keys": 16, |
| 365 |
"m.@values": 10, |
| 366 |
}, |
| 367 |
estimatedCost: checker.CostEstimate{Min: 65, Max: 405}, |
| 368 |
actualCost: 201, |
| 369 |
}, |
| 370 |
} |
| 371 |
|
| 372 |
for _, tst := range tests { |
| 373 |
tc := tst |
| 374 |
t.Run(tc.name, func(t *testing.T) { |
| 375 |
env := testCompreEnv(t, tc.vars...) |
| 376 |
var asts []*cel.Ast |
| 377 |
pAst, iss := env.Parse(tc.expr) |
| 378 |
if iss.Err() != nil { |
| 379 |
t.Fatalf("env.Parse(%v) failed: %v", tc.expr, iss.Err()) |
| 380 |
} |
| 381 |
asts = append(asts, pAst) |
| 382 |
cAst, iss := env.Check(pAst) |
| 383 |
if iss.Err() != nil { |
| 384 |
t.Fatalf("env.Check(%v) failed: %v", tc.expr, iss.Err()) |
| 385 |
} |
| 386 |
|
| 387 |
testCheckCost(t, env, cAst, tc.hints, tc.estimatedCost) |
| 388 |
asts = append(asts, cAst) |
| 389 |
for _, ast := range asts { |
| 390 |
testEvalWithCost(t, env, ast, tc.in, tc.actualCost) |
| 391 |
} |
| 392 |
}) |
| 393 |
} |
| 394 |
} |
| 395 |
|
| 396 |
func TestTwoVarComprehensionsStaticErrors(t *testing.T) { |
| 397 |
tests := []struct { |
| 398 |
expr string |
| 399 |
err string |
| 400 |
}{ |
| 401 |
{ |
| 402 |
expr: "[].all(i, i, i < i)", |
| 403 |
err: "duplicate variable name: i", |
| 404 |
}, |
| 405 |
{ |
| 406 |
expr: "[].all(__result__, i, __result__ < i)", |
| 407 |
err: "iteration variable overwrites accumulator variable", |
| 408 |
}, |
| 409 |
{ |
| 410 |
expr: "[].all(j, __result__, __result__ < j)", |
| 411 |
err: "iteration variable overwrites accumulator variable", |
| 412 |
}, |
| 413 |
{ |
| 414 |
expr: "[].all(i.j, k, i.j < k)", |
| 415 |
err: "argument must be a simple name", |
| 416 |
}, |
| 417 |
{ |
| 418 |
expr: "[].all(j, i.k, j < i.k)", |
| 419 |
err: "argument must be a simple name", |
| 420 |
}, |
| 421 |
{ |
| 422 |
expr: "1.all(j, k, j < k)", |
| 423 |
err: "cannot be range", |
| 424 |
}, |
| 425 |
{ |
| 426 |
expr: "[].exists(i.j, k, i.j < k)", |
| 427 |
err: "argument must be a simple name", |
| 428 |
}, |
| 429 |
{ |
| 430 |
expr: "[].exists(j, i.k, j < i.k)", |
| 431 |
err: "argument must be a simple name", |
| 432 |
}, |
| 433 |
{ |
| 434 |
expr: "''.exists(j, k, j < k)", |
| 435 |
err: "cannot be range", |
| 436 |
}, |
| 437 |
{ |
| 438 |
expr: "[].exists_one(i.j, k, i.j < k)", |
| 439 |
err: "argument must be a simple name", |
| 440 |
}, |
| 441 |
{ |
| 442 |
expr: "[].existsOne(j, i.k, j < i.k)", |
| 443 |
err: "argument must be a simple name", |
| 444 |
}, |
| 445 |
{ |
| 446 |
expr: "[].exists_one(i.j, k, i.j < k)", |
| 447 |
err: "argument must be a simple name", |
| 448 |
}, |
| 449 |
{ |
| 450 |
expr: "''.existsOne(j, k, j < k)", |
| 451 |
err: "cannot be range", |
| 452 |
}, |
| 453 |
{ |
| 454 |
expr: "[].transformList(i.j, k, i.j + k)", |
| 455 |
err: "argument must be a simple name", |
| 456 |
}, |
| 457 |
{ |
| 458 |
expr: "[].transformList(j, i.k, j + i.k)", |
| 459 |
err: "argument must be a simple name", |
| 460 |
}, |
| 461 |
{ |
| 462 |
expr: "{}.transformMap(i.j, k, i.j + k)", |
| 463 |
err: "argument must be a simple name", |
| 464 |
}, |
| 465 |
{ |
| 466 |
expr: "{}.transformMap(j, i.k, j + i.k)", |
| 467 |
err: "argument must be a simple name", |
| 468 |
}, |
| 469 |
{ |
| 470 |
expr: "{}.transformMapEntry(j, i.k, {j: i.k})", |
| 471 |
err: "argument must be a simple name", |
| 472 |
}, |
| 473 |
{ |
| 474 |
expr: "{}.transformMapEntry(i.j, k, {k: i.j})", |
| 475 |
err: "argument must be a simple name", |
| 476 |
}, |
| 477 |
{ |
| 478 |
expr: "{}.transformMapEntry(j, k, 'bad filter', {k: j})", |
| 479 |
err: "no matching overload", |
| 480 |
}, |
| 481 |
{ |
| 482 |
expr: "[1, 2].transformList(i, v, v % 2 == 0 ? [v] : v)", |
| 483 |
err: "no matching overload", |
| 484 |
}, |
| 485 |
{ |
| 486 |
expr: `{'hello': 'world', 'greetings': 'tacocat'}.transformMapEntry(k, v, []) == {}`, |
| 487 |
err: "no matching overload"}, |
| 488 |
} |
| 489 |
env := testCompreEnv(t) |
| 490 |
for i, tst := range tests { |
| 491 |
tc := tst |
| 492 |
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { |
| 493 |
_, iss := env.Compile(tc.expr) |
| 494 |
if iss.Err() == nil || !strings.Contains(iss.Err().Error(), tc.err) { |
| 495 |
t.Errorf("env.Compile(%q) got %v, wanted error %v", tc.expr, iss.Err(), tc.err) |
| 496 |
} |
| 497 |
}) |
| 498 |
} |
| 499 |
} |
| 500 |
|
| 501 |
func TestTwoVarComprehensionsRuntimeErrors(t *testing.T) { |
| 502 |
tests := []struct { |
| 503 |
expr string |
| 504 |
err string |
| 505 |
}{ |
| 506 |
{ |
| 507 |
expr: "[1, 1].transformMapEntry(i, v, {v: i})", |
| 508 |
err: "insert failed: key 1 already exists", |
| 509 |
}, |
| 510 |
{ |
| 511 |
expr: `[0, 0u].transformMapEntry(i, v, {v: i})`, |
| 512 |
err: "insert failed: key 0 already exists", |
| 513 |
}, |
| 514 |
} |
| 515 |
env := testCompreEnv(t) |
| 516 |
for i, tst := range tests { |
| 517 |
tc := tst |
| 518 |
t.Run(fmt.Sprintf("%d", i), func(t *testing.T) { |
| 519 |
ast, iss := env.Compile(tc.expr) |
| 520 |
if iss.Err() != nil { |
| 521 |
t.Fatalf("env.Compile(%q) failed with error %v", tc.expr, iss.Err()) |
| 522 |
} |
| 523 |
prg, err := env.Program(ast) |
| 524 |
if err != nil { |
| 525 |
t.Fatalf("env.Program(ast) failed: %v", err) |
| 526 |
} |
| 527 |
in := cel.NoVars() |
| 528 |
_, _, err = prg.Eval(in) |
| 529 |
if err == nil || !strings.Contains(err.Error(), tc.err) { |
| 530 |
t.Errorf("prg.Eval() got %v, wanted %v", err, tc.err) |
| 531 |
} |
| 532 |
}) |
| 533 |
} |
| 534 |
} |
| 535 |
|
| 536 |
func TestTwoVarComprehensionsVersion(t *testing.T) { |
| 537 |
_, err := cel.NewEnv(TwoVarComprehensions(TwoVarComprehensionsVersion(0))) |
| 538 |
if err != nil { |
| 539 |
t.Fatalf("TwoVarComprehensionVersion(0) failed: %v", err) |
| 540 |
} |
| 541 |
} |
| 542 |
|
| 543 |
func TestTwoVarComprehensionsUnparse(t *testing.T) { |
| 544 |
tests := []struct { |
| 545 |
name string |
| 546 |
expr string |
| 547 |
unparsed string |
| 548 |
}{ |
| 549 |
{ |
| 550 |
name: "transform map entry", |
| 551 |
expr: `[0, 0u].transformMapEntry(i, v, {v: i})`, |
| 552 |
unparsed: `[0, 0u].transformMapEntry(i, v, {v: i})`, |
| 553 |
}, |
| 554 |
{ |
| 555 |
name: "transform map", |
| 556 |
expr: `{'a': 'world', 'b': 'hello'}.transformMap(i, v, i == 'a' ? v.upperAscii() : v)`, |
| 557 |
unparsed: `{"a": "world", "b": "hello"}.transformMap(i, v, (i == "a") ? v.upperAscii() : v)`, |
| 558 |
}, |
| 559 |
{ |
| 560 |
name: "transform list", |
| 561 |
expr: `[1.0, 2.0, 2.0].transformList(i, v, i / 2.0 == 1.0)`, |
| 562 |
unparsed: `[1.0, 2.0, 2.0].transformList(i, v, i / 2.0 == 1.0)`, |
| 563 |
}, |
| 564 |
{ |
| 565 |
name: "existsOne", |
| 566 |
expr: `{'a': 'b', 'c': 'd'}.existsOne(k, v, k == 'b' || v == 'b')`, |
| 567 |
unparsed: `{"a": "b", "c": "d"}.existsOne(k, v, k == "b" || v == "b")`, |
| 568 |
}, |
| 569 |
{ |
| 570 |
name: "exists", |
| 571 |
expr: `{'a': 'b', 'c': 'd'}.exists(k, v, k == 'b' || v == 'b')`, |
| 572 |
unparsed: `{"a": "b", "c": "d"}.exists(k, v, k == "b" || v == "b")`, |
| 573 |
}, |
| 574 |
{ |
| 575 |
name: "all", |
| 576 |
expr: `[null, null, 'hello', string].all(i, v, i == 0 || type(v) != int)`, |
| 577 |
unparsed: `[null, null, "hello", string].all(i, v, i == 0 || type(v) != int)`, |
| 578 |
}, |
| 579 |
} |
| 580 |
env := testCompreEnv(t) |
| 581 |
for _, tst := range tests { |
| 582 |
tc := tst |
| 583 |
t.Run(tc.name, func(t *testing.T) { |
| 584 |
ast, iss := env.Parse(tc.expr) |
| 585 |
if iss.Err() != nil { |
| 586 |
t.Fatalf("env.Parse(%q) failed: %v", tc.expr, iss.Err()) |
| 587 |
} |
| 588 |
unparsed, err := cel.AstToString(ast) |
| 589 |
if err != nil { |
| 590 |
t.Fatalf("cel.AstToString() failed: %v", err) |
| 591 |
} |
| 592 |
if unparsed != tc.unparsed { |
| 593 |
t.Errorf("cel.AstToString() got %q, wanted %q", unparsed, tc.unparsed) |
| 594 |
} |
| 595 |
}) |
| 596 |
} |
| 597 |
} |
| 598 |
|
| 599 |
func TestTwoVarComprehensionsResidualAST(t *testing.T) { |
| 600 |
tests := []struct { |
| 601 |
name string |
| 602 |
in map[string]any |
| 603 |
varOpts []cel.EnvOption |
| 604 |
unks []*interpreter.AttributePattern |
| 605 |
expr string |
| 606 |
residual string |
| 607 |
}{ |
| 608 |
{ |
| 609 |
name: "transform map entry residual compare", |
| 610 |
varOpts: []cel.EnvOption{ |
| 611 |
cel.Variable("x", cel.ListType(cel.DynType)), |
| 612 |
cel.Variable("y", cel.IntType), |
| 613 |
}, |
| 614 |
in: map[string]any{ |
| 615 |
"x": []any{0, uint(1)}, |
| 616 |
}, |
| 617 |
unks: []*interpreter.AttributePattern{cel.AttributePattern("y")}, |
| 618 |
expr: `x.transformMapEntry(i, v, {v: i}).size() < y`, |
| 619 |
residual: `2 < y`, |
| 620 |
}, |
| 621 |
{ |
| 622 |
name: "transform map entry residual transform", |
| 623 |
varOpts: []cel.EnvOption{ |
| 624 |
cel.Variable("x", cel.ListType(cel.DynType)), |
| 625 |
cel.Variable("y", cel.IntType), |
| 626 |
}, |
| 627 |
in: map[string]any{ |
| 628 |
"x": []any{0, uint(1)}, |
| 629 |
}, |
| 630 |
unks: []*interpreter.AttributePattern{cel.AttributePattern("y")}, |
| 631 |
expr: `x.transformMapEntry(i, v, i < y, {v: i})`, |
| 632 |
residual: `[0, 1u].transformMapEntry(i, v, i < y, {v: i})`, |
| 633 |
}, |
| 634 |
{ |
| 635 |
name: "nested exists unknown inner range", |
| 636 |
varOpts: []cel.EnvOption{ |
| 637 |
cel.Variable("x", cel.ListType(cel.IntType)), |
| 638 |
cel.Variable("y", cel.MapType(cel.IntType, cel.DynType)), |
| 639 |
}, |
| 640 |
in: map[string]any{ |
| 641 |
"x": []any{1, 2, 3}, |
| 642 |
}, |
| 643 |
unks: []*interpreter.AttributePattern{cel.AttributePattern("y")}, |
| 644 |
expr: `x.exists(val, y.exists(key, _, key == val))`, |
| 645 |
residual: `[1, 2, 3].exists(val, y.exists(key, _, key == val))`, |
| 646 |
}, |
| 647 |
{ |
| 648 |
name: "nested exists unknown inner range", |
| 649 |
varOpts: []cel.EnvOption{ |
| 650 |
cel.Variable("x", cel.ListType(cel.IntType)), |
| 651 |
cel.Variable("y", cel.MapType(cel.IntType, cel.DynType)), |
| 652 |
}, |
| 653 |
in: map[string]any{ |
| 654 |
"y": map[int]string{1: "hi", 2: "hello", 3: "howdy"}, |
| 655 |
}, |
| 656 |
unks: []*interpreter.AttributePattern{cel.AttributePattern("x")}, |
| 657 |
expr: `x.exists(val, y.exists(key, _, key == val))`, |
| 658 |
residual: `x.exists(val, y.exists(key, _, key == val))`, |
| 659 |
}, |
| 660 |
{ |
| 661 |
name: "nested exists unknown outer range with extra predicate", |
| 662 |
varOpts: []cel.EnvOption{ |
| 663 |
cel.Variable("x", cel.ListType(cel.IntType)), |
| 664 |
cel.Variable("y", cel.MapType(cel.IntType, cel.DynType)), |
| 665 |
}, |
| 666 |
in: map[string]any{ |
| 667 |
"y": map[int]string{1: "hi", 2: "hello", 3: "howdy"}, |
| 668 |
}, |
| 669 |
unks: []*interpreter.AttributePattern{cel.AttributePattern("x")}, |
| 670 |
expr: `x.exists(val, y.exists(key, _, key == val)) && y.all(key, val, val.startsWith('h'))`, |
| 671 |
residual: `x.exists(val, y.exists(key, _, key == val))`, |
| 672 |
}, |
| 673 |
{ |
| 674 |
name: "nested exists partial unknown outer range", |
| 675 |
varOpts: []cel.EnvOption{ |
| 676 |
cel.Variable("x", cel.ListType(cel.IntType)), |
| 677 |
cel.Variable("y", cel.MapType(cel.IntType, cel.DynType)), |
| 678 |
}, |
| 679 |
in: map[string]any{ |
| 680 |
"x": []int{42, 0, 43}, |
| 681 |
"y": map[int]string{1: "hi", 2: "hello", 3: "howdy"}, |
| 682 |
}, |
| 683 |
unks: []*interpreter.AttributePattern{cel.AttributePattern("x").QualInt(1)}, |
| 684 |
expr: `x.exists(val, y.exists(key, _, key == val)) || x[0] == 0 || x[1] == 1 || x[2] == 2`, |
| 685 |
residual: `x.exists(val, y.exists(key, _, key == val)) || x[1] == 1`, |
| 686 |
}, |
| 687 |
{ |
| 688 |
name: "nested exists partial unknown outer range with optionals", |
| 689 |
varOpts: []cel.EnvOption{ |
| 690 |
cel.Variable("x", cel.ListType(cel.IntType)), |
| 691 |
cel.Variable("y", cel.MapType(cel.IntType, cel.DynType)), |
| 692 |
}, |
| 693 |
in: map[string]any{ |
| 694 |
"x": []int{42, 0, 43}, |
| 695 |
"y": map[int]string{1: "hi", 2: "hello", 3: "howdy"}, |
| 696 |
}, |
| 697 |
unks: []*interpreter.AttributePattern{cel.AttributePattern("x").QualInt(1)}, |
| 698 |
expr: `x.exists(val, y.exists(key, _, key == val)) || (x[?0].hasValue() && x[?1].hasValue())`, |
| 699 |
residual: `x.exists(val, y.exists(key, _, key == val)) || x[?1].hasValue()`, |
| 700 |
}, |
| 701 |
{ |
| 702 |
name: "inner value partial unknown two-var", |
| 703 |
varOpts: []cel.EnvOption{ |
| 704 |
cel.Variable("x", cel.ListType(cel.StringType)), |
| 705 |
cel.Variable("y", cel.MapType(cel.IntType, cel.StringType)), |
| 706 |
}, |
| 707 |
in: map[string]any{ |
| 708 |
"x": []string{"howdy", "hello", "hi"}, |
| 709 |
"y": map[int]string{0: "hi", 1: "hello", 2: "howdy"}, |
| 710 |
}, |
| 711 |
unks: []*interpreter.AttributePattern{cel.AttributePattern("y").QualInt(1)}, |
| 712 |
expr: `x.exists(key, val, y[?key] == optional.of(val))`, |
| 713 |
residual: `["howdy", "hello", "hi"].exists(key, val, y[?key] == optional.of(val))`, |
| 714 |
}, |
| 715 |
{ |
| 716 |
name: "inner value partial unknown one-var", |
| 717 |
varOpts: []cel.EnvOption{ |
| 718 |
cel.Variable("x", cel.ListType(cel.StringType)), |
| 719 |
cel.Variable("y", cel.MapType(cel.IntType, cel.StringType)), |
| 720 |
}, |
| 721 |
in: map[string]any{ |
| 722 |
"x": []string{"howdy"}, |
| 723 |
"y": map[int]string{0: "hello"}, |
| 724 |
}, |
| 725 |
unks: []*interpreter.AttributePattern{cel.AttributePattern("x").QualInt(0)}, |
| 726 |
expr: `y.exists(key, y[?key] == x[?key])`, |
| 727 |
residual: `{0: "hello"}.exists(key, y[?key] == x[?key])`, |
| 728 |
}, |
| 729 |
{ |
| 730 |
name: "simple bind", |
| 731 |
varOpts: []cel.EnvOption{ |
| 732 |
cel.Variable("y", cel.MapType(cel.IntType, cel.StringType)), |
| 733 |
}, |
| 734 |
in: map[string]any{ |
| 735 |
"y": map[int]string{0: "hi", 1: "hello", 2: "howdy"}, |
| 736 |
}, |
| 737 |
unks: []*interpreter.AttributePattern{cel.AttributePattern("y").QualInt(1)}, |
| 738 |
expr: `cel.bind(z, y[0], z + y[1])`, |
| 739 |
residual: `cel.bind(z, "hi", "hi" + y[1])`, |
| 740 |
}, |
| 741 |
{ |
| 742 |
name: "bind with comprehension", |
| 743 |
varOpts: []cel.EnvOption{ |
| 744 |
cel.Variable("x", cel.ListType(cel.StringType)), |
| 745 |
cel.Variable("y", cel.MapType(cel.IntType, cel.StringType)), |
| 746 |
}, |
| 747 |
in: map[string]any{ |
| 748 |
"x": []string{"hi", "hello", "howdy"}, |
| 749 |
"y": map[int]string{0: "hi", 1: "hello", 2: "howdy"}, |
| 750 |
}, |
| 751 |
unks: []*interpreter.AttributePattern{cel.AttributePattern("y").QualInt(1)}, |
| 752 |
expr: `cel.bind(z, y[0], x.all(i, val, val == z || optional.of(val) == y[?i]))`, |
| 753 |
residual: `cel.bind(z, "hi", ["hi", "hello", "howdy"].all(i, val, val == z || optional.of(val) == y[?i]))`, |
| 754 |
}, |
| 755 |
} |
| 756 |
for _, tst := range tests { |
| 757 |
tc := tst |
| 758 |
t.Run(tc.name, func(t *testing.T) { |
| 759 |
env := testCompreEnv(t, tc.varOpts...) |
| 760 |
ast, iss := env.Compile(tc.expr) |
| 761 |
if iss.Err() != nil { |
| 762 |
t.Fatalf("env.Compile(%q) failed: %v", tc.expr, iss.Err()) |
| 763 |
} |
| 764 |
prg, err := env.Program(ast, |
| 765 |
cel.EvalOptions(cel.OptTrackState, cel.OptPartialEval)) |
| 766 |
if err != nil { |
| 767 |
t.Fatalf("env.Program() failed: %v", err) |
| 768 |
} |
| 769 |
unkVars, err := cel.PartialVars(tc.in, tc.unks...) |
| 770 |
if err != nil { |
| 771 |
t.Fatalf("PartialVars() failed: %v", err) |
| 772 |
} |
| 773 |
out, det, err := prg.Eval(unkVars) |
| 774 |
if !types.IsUnknown(out) { |
| 775 |
t.Fatalf("got %v, expected unknown", out) |
| 776 |
} |
| 777 |
if err != nil { |
| 778 |
t.Fatalf("prg.Eval() failed: %v", err) |
| 779 |
} |
| 780 |
residual, err := env.ResidualAst(ast, det) |
| 781 |
if err != nil { |
| 782 |
t.Fatalf("env.ResidualAst() failed: %v", err) |
| 783 |
} |
| 784 |
expr, err := cel.AstToString(residual) |
| 785 |
if err != nil { |
| 786 |
t.Fatalf("cel.AstToString() failed: %v", err) |
| 787 |
} |
| 788 |
if expr != tc.residual { |
| 789 |
t.Errorf("got expr: %s, wanted %s", expr, tc.residual) |
| 790 |
} |
| 791 |
}) |
| 792 |
} |
| 793 |
} |
| 794 |
|
| 795 |
func testCompreEnv(t *testing.T, opts ...cel.EnvOption) *cel.Env { |
| 796 |
t.Helper() |
| 797 |
baseOpts := []cel.EnvOption{ |
| 798 |
TwoVarComprehensions(), |
| 799 |
Bindings(), |
| 800 |
Lists(), |
| 801 |
Strings(), |
| 802 |
cel.OptionalTypes(), |
| 803 |
cel.EnableMacroCallTracking(), |
| 804 |
cel.EnableHiddenAccumulatorName(true), |
| 805 |
} |
| 806 |
env, err := cel.NewEnv(append(baseOpts, opts...)...) |
| 807 |
if err != nil { |
| 808 |
t.Fatalf("cel.NewEnv(TwoVarComprehensions()) failed: %v", err) |
| 809 |
} |
| 810 |
return env |
| 811 |
} |