| 460 | } |
| 461 | |
| 462 | func TestNetwork_RuntimeErrors(t *testing.T) { |
| 463 | tests := []struct { |
| 464 | name string |
| 465 | expr string |
| 466 | errContains string |
| 467 | }{ |
| 468 | { |
| 469 | name: "containsIP string overload invalid", |
| 470 | expr: "cidr('10.0.0.0/8').containsIP('not-an-ip')", |
| 471 | errContains: "parse error", |
| 472 | }, |
| 473 | { |
| 474 | name: "containsCIDR string overload invalid", |
| 475 | expr: "cidr('10.0.0.0/8').containsCIDR('not-a-cidr')", |
| 476 | errContains: "parse error", |
| 477 | }, |
| 478 | { |
| 479 | name: "ip.isCanonical invalid ipv4", |
| 480 | expr: "ip.isCanonical('127.0.0.1.0')", |
| 481 | errContains: "parse error", |
| 482 | }, |
| 483 | { |
| 484 | name: "ip.isCanonical invalid ipv6", |
| 485 | expr: "ip.isCanonical('2001:db8:::68')", |
| 486 | errContains: "parse error", |
| 487 | }, |
| 488 | } |
| 489 | |
| 490 | env, err := cel.NewEnv(Network()) |
| 491 | if err != nil { |
| 492 | t.Fatalf("cel.NewEnv(Network()) failed: %v", err) |
| 493 | } |
| 494 | |
| 495 | for _, tst := range tests { |
| 496 | t.Run(tst.name, func(t *testing.T) { |
| 497 | ast, iss := env.Compile(tst.expr) |
| 498 | if iss.Err() != nil { |
| 499 | // Note: We only check runtime errors here. Compile errors are unexpected |
| 500 | // because these functions accept strings, so type-check passes. |
| 501 | t.Fatalf("Compile(%q) failed unexpectedly: %v", tst.expr, iss.Err()) |
| 502 | } |
| 503 | |
| 504 | prg, err := env.Program(ast) |
| 505 | if err != nil { |
| 506 | t.Fatalf("Program(%q) failed: %v", tst.expr, err) |
| 507 | } |
| 508 | |
| 509 | _, _, err = prg.Eval(cel.NoVars()) |
| 510 | if err == nil { |
| 511 | t.Errorf("Expected runtime error for %q, got nil", tst.expr) |
| 512 | return |
| 513 | } |
| 514 | |
| 515 | // CEL errors are sometimes wrapped, so we check substring |
| 516 | if !types.IsError(types.NewErr("%s", err.Error())) { |
| 517 | // Just a sanity check that it is indeed a CEL-compatible error structure |
| 518 | // Not strictly necessary but good practice |
| 519 | } |