MCPcopy Create free account
hub / github.com/cel-expr/cel-go / TestLiteralOutput

Function TestLiteralOutput

ext/formatting_test.go:1080–1144  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

1078}
1079
1080func TestLiteralOutput(t *testing.T) {
1081 tests := []struct {
1082 name string
1083 formatLiteral string
1084 expectedType string
1085 }{
1086 {
1087 name: "map literal support",
1088 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}`,
1089 expectedType: `map`,
1090 },
1091 {
1092 name: "list literal support",
1093 formatLiteral: `["abc", 3.14, uint(32), b"def", null, type(string), duration("7m"), [9, 8, 7, 6], timestamp("2023-02-03T23:31:20Z")]`,
1094 expectedType: `list`,
1095 },
1096 }
1097 for _, tt := range tests {
1098 parseAndEval := func(expr string, t *testing.T) (ref.Val, error) {
1099 env, err := cel.NewEnv(Strings(StringsVersion(3)))
1100 if err != nil {
1101 t.Fatalf("cel.NewEnv(Strings(StringsVersion(3))) failed: %v", err)
1102 }
1103 parsedAst, issues := env.Parse(expr)
1104 if issues.Err() != nil {
1105 t.Fatalf("env.Parse(%v) failed: %v", expr, issues.Err())
1106 }
1107 checkedAst, issues := env.Check(parsedAst)
1108 if issues.Err() != nil {
1109 t.Fatalf("env.Check(%v) failed: %v", expr, issues.Err())
1110 }
1111 program, err := env.Program(checkedAst)
1112 if err != nil {
1113 t.Fatal(err)
1114 }
1115 out, _, err := program.Eval(cel.NoVars())
1116 return out, err
1117 }
1118 t.Run(tt.name, func(t *testing.T) {
1119 expr := fmt.Sprintf(`"%%s".format([%s])`, tt.formatLiteral)
1120 literalVal, err := parseAndEval(expr, t)
1121 if err != nil {
1122 t.Fatalf("program.Eval failed: %v", err)
1123 }
1124 out, err := parseAndEval(literalVal.Value().(string), t)
1125 if err != nil {
1126 t.Fatalf("literal evaluation failed: %v", err)
1127 }
1128 if out.Type().TypeName() != tt.expectedType {
1129 t.Errorf("expected literal to evaluate to type %s, got %s", tt.expectedType, out.Type().TypeName())
1130 }
1131 equivalentVal, err := parseAndEval(literalVal.Value().(string)+" == "+tt.formatLiteral, t)
1132 if err != nil {
1133 t.Fatalf("equality evaluation failed: %v:", err)
1134 }
1135 if equivalentVal.Type().TypeName() != "bool" {
1136 t.Errorf("expected equality expression to evaluation to type bool, got %s", equivalentVal.Type().TypeName())
1137 }

Callers

nothing calls this directly

Calls 12

ParseMethod · 0.95
CheckMethod · 0.95
ProgramMethod · 0.95
NewEnvFunction · 0.92
NoVarsFunction · 0.92
StringsFunction · 0.85
StringsVersionFunction · 0.85
ErrMethod · 0.80
EvalMethod · 0.65
ValueMethod · 0.65
TypeNameMethod · 0.65
TypeMethod · 0.65

Tested by

no test coverage detected