Search in sources :

Example 1 with True

use of org.projectnessie.cel.common.types.BoolT.True in project cel-java by projectnessie.

the class CELTest method HomogeneousAggregateLiterals.

@Test
void HomogeneousAggregateLiterals() {
    Env e = newCustomEnv(declarations(Decls.newVar("name", Decls.String), Decls.newFunction(Operator.In.id, Decls.newOverload(Overloads.InList, asList(Decls.String, Decls.newListType(Decls.String)), Decls.Bool), Decls.newOverload(Overloads.InMap, asList(Decls.String, Decls.newMapType(Decls.String, Decls.Bool)), Decls.Bool))), homogeneousAggregateLiterals());
    // t.Run("err_list", func(t *testing.T) {
    AstIssuesTuple xIss = e.compile("name in ['hello', 0]");
    assertThat(xIss.getIssues()).isNotNull();
    assertThat(xIss.hasIssues()).isTrue();
    // })
    // t.Run("err_map_key", func(t *testing.T) {
    xIss = e.compile("name in {'hello':'world', 1:'!'}");
    assertThat(xIss.getIssues()).isNotNull();
    assertThat(xIss.hasIssues()).isTrue();
    // })
    // t.Run("err_map_val", func(t *testing.T) {
    xIss = e.compile("name in {'hello':'world', 'goodbye':true}");
    assertThat(xIss.getIssues()).isNotNull();
    assertThat(xIss.hasIssues()).isTrue();
    // })
    ProgramOption funcs = functions(Overload.binary(Operator.In.id, (lhs, rhs) -> {
        if (rhs.type().hasTrait(Trait.ContainerType)) {
            return ((Container) rhs).contains(lhs);
        }
        return valOrErr(rhs, "no such overload");
    }));
    // t.Run("ok_list", func(t *testing.T) {
    AstIssuesTuple astIss = e.compile("name in ['hello', 'world']");
    assertThat(astIss.hasIssues()).isFalse();
    Program prg = e.program(astIss.getAst(), funcs);
    EvalResult out = prg.eval(mapOf("name", "world"));
    assertThat(out.getVal()).isSameAs(True);
    // })
    // t.Run("ok_map", func(t *testing.T) {
    astIss = e.compile("name in {'hello': false, 'world': true}");
    assertThat(astIss.hasIssues()).isFalse();
    prg = e.program(astIss.getAst(), funcs);
    out = prg.eval(mapOf("name", "world"));
    assertThat(out.getVal()).isSameAs(True);
// })
}
Also used : BoolT(org.projectnessie.cel.common.types.BoolT) Interpretable(org.projectnessie.cel.interpreter.Interpretable) Macro(org.projectnessie.cel.parser.Macro) Call(com.google.api.expr.v1alpha1.Expr.Call) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) PartialActivation(org.projectnessie.cel.interpreter.Activation.PartialActivation) EnvOption.container(org.projectnessie.cel.EnvOption.container) Macro.newReceiverMacro(org.projectnessie.cel.parser.Macro.newReceiverMacro) Activation.emptyActivation(org.projectnessie.cel.interpreter.Activation.emptyActivation) Disabled(org.junit.jupiter.api.Disabled) InterpretableDecorator(org.projectnessie.cel.interpreter.InterpretableDecorator) Collections.singletonList(java.util.Collections.singletonList) True(org.projectnessie.cel.common.types.BoolT.True) Err.isError(org.projectnessie.cel.common.types.Err.isError) Container(org.projectnessie.cel.common.types.traits.Container) Arrays.asList(java.util.Arrays.asList) CEL.estimateCost(org.projectnessie.cel.CEL.estimateCost) OptPartialEval(org.projectnessie.cel.EvalOption.OptPartialEval) ProtoTypeRegistry.newEmptyRegistry(org.projectnessie.cel.common.types.pb.ProtoTypeRegistry.newEmptyRegistry) ParsedExpr(com.google.api.expr.v1alpha1.ParsedExpr) EnvOption.customTypeProvider(org.projectnessie.cel.EnvOption.customTypeProvider) Val(org.projectnessie.cel.common.types.ref.Val) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) InterpretableAttribute(org.projectnessie.cel.interpreter.Interpretable.InterpretableAttribute) Collections.emptyList(java.util.Collections.emptyList) Expr(com.google.api.expr.v1alpha1.Expr) Ident(com.google.api.expr.v1alpha1.Expr.Ident) InterpretableCall(org.projectnessie.cel.interpreter.Interpretable.InterpretableCall) OptExhaustiveEval(org.projectnessie.cel.EvalOption.OptExhaustiveEval) OptTrackState(org.projectnessie.cel.EvalOption.OptTrackState) StringT.stringOf(org.projectnessie.cel.common.types.StringT.stringOf) Decls(org.projectnessie.cel.checker.Decls) CEL.attributePattern(org.projectnessie.cel.CEL.attributePattern) Executors(java.util.concurrent.Executors) Test(org.junit.jupiter.api.Test) ProgramOption.functions(org.projectnessie.cel.ProgramOption.functions) DefaultTypeAdapter(org.projectnessie.cel.common.types.pb.DefaultTypeAdapter) Overload(org.projectnessie.cel.interpreter.functions.Overload) EvalResult(org.projectnessie.cel.Program.EvalResult) Err.newErr(org.projectnessie.cel.common.types.Err.newErr) IntOne(org.projectnessie.cel.common.types.IntT.IntOne) IntStream(java.util.stream.IntStream) Overloads(org.projectnessie.cel.common.types.Overloads) Env.newEnv(org.projectnessie.cel.Env.newEnv) StdLib(org.projectnessie.cel.Library.StdLib) IntT(org.projectnessie.cel.common.types.IntT) Trait(org.projectnessie.cel.common.types.traits.Trait) EnvOption.declarations(org.projectnessie.cel.EnvOption.declarations) CompletableFuture(java.util.concurrent.CompletableFuture) Err.valOrErr(org.projectnessie.cel.common.types.Err.valOrErr) CEL.partialVars(org.projectnessie.cel.CEL.partialVars) AtomicReference(java.util.concurrent.atomic.AtomicReference) EnvOption.customTypeAdapter(org.projectnessie.cel.EnvOption.customTypeAdapter) AstIssuesTuple(org.projectnessie.cel.Env.AstIssuesTuple) Mapper(org.projectnessie.cel.common.types.traits.Mapper) ProgramOption.evalOptions(org.projectnessie.cel.ProgramOption.evalOptions) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Type(com.google.api.expr.v1alpha1.Type) CEL.astToCheckedExpr(org.projectnessie.cel.CEL.astToCheckedExpr) CEL.noVars(org.projectnessie.cel.CEL.noVars) ExecutorService(java.util.concurrent.ExecutorService) Collections.emptyMap(java.util.Collections.emptyMap) CEL.astToString(org.projectnessie.cel.CEL.astToString) ProgramOption.globals(org.projectnessie.cel.ProgramOption.globals) Operator(org.projectnessie.cel.common.operators.Operator) NamespacedAttribute(org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute) UnknownT(org.projectnessie.cel.common.types.UnknownT) Cost(org.projectnessie.cel.interpreter.Coster.Cost) EnvOption.types(org.projectnessie.cel.EnvOption.types) ProgramOption.customDecorator(org.projectnessie.cel.ProgramOption.customDecorator) EnvOption.macros(org.projectnessie.cel.EnvOption.macros) Interpretable.newConstValue(org.projectnessie.cel.interpreter.Interpretable.newConstValue) CheckedExpr(com.google.api.expr.v1alpha1.CheckedExpr) CEL.parsedExprToAst(org.projectnessie.cel.CEL.parsedExprToAst) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) InterpretableConst(org.projectnessie.cel.interpreter.Interpretable.InterpretableConst) CEL.astToParsedExpr(org.projectnessie.cel.CEL.astToParsedExpr) CEL.checkedExprToAst(org.projectnessie.cel.CEL.checkedExprToAst) EvalState(org.projectnessie.cel.interpreter.EvalState) Util.mapOf(org.projectnessie.cel.Util.mapOf) StringT(org.projectnessie.cel.common.types.StringT) EnvOption.homogeneousAggregateLiterals(org.projectnessie.cel.EnvOption.homogeneousAggregateLiterals) Env.newCustomEnv(org.projectnessie.cel.Env.newCustomEnv) EnvOption.abbrevs(org.projectnessie.cel.EnvOption.abbrevs) EvalResult(org.projectnessie.cel.Program.EvalResult) Env.newEnv(org.projectnessie.cel.Env.newEnv) Env.newCustomEnv(org.projectnessie.cel.Env.newCustomEnv) AstIssuesTuple(org.projectnessie.cel.Env.AstIssuesTuple) Test(org.junit.jupiter.api.Test)

Example 2 with True

use of org.projectnessie.cel.common.types.BoolT.True in project cel-java by projectnessie.

the class CELTest method GlobalVars.

@Test
void GlobalVars() {
    Type mapStrDyn = Decls.newMapType(Decls.String, Decls.Dyn);
    Env e = newEnv(declarations(Decls.newVar("attrs", mapStrDyn), Decls.newVar("default", Decls.Dyn), Decls.newFunction("get", Decls.newInstanceOverload("get_map", asList(mapStrDyn, Decls.String, Decls.Dyn), Decls.Dyn))));
    AstIssuesTuple astIss = e.compile("attrs.get(\"first\", attrs.get(\"second\", default))");
    // Create the program.
    ProgramOption funcs = functions(Overload.function("get", args -> {
        if (args.length != 3) {
            return newErr("invalid arguments to 'get'");
        }
        if (!(args[0] instanceof Mapper)) {
            return newErr("invalid operand of type '%s' to obj.get(key, def)", args[0].type());
        }
        Mapper attrs = (Mapper) args[0];
        if (!(args[1] instanceof StringT)) {
            return newErr("invalid key of type '%s' to obj.get(key, def)", args[1].type());
        }
        StringT key = (StringT) args[1];
        Val defVal = args[2];
        if (attrs.contains(key) == True) {
            return attrs.get(key);
        }
        return defVal;
    }));
    // Global variables can be configured as a ProgramOption and optionally overridden on Eval.
    Program prg = e.program(astIss.getAst(), funcs, globals(mapOf("default", "third")));
    // t.Run("global_default", func(t *testing.T) {
    Object vars = mapOf("attrs", mapOf());
    EvalResult out = prg.eval(vars);
    assertThat(out.getVal().equal(stringOf("third"))).isSameAs(True);
    // })
    // t.Run("attrs_alt", func(t *testing.T) {
    vars = mapOf("attrs", mapOf("second", "yep"));
    out = prg.eval(vars);
    assertThat(out.getVal().equal(stringOf("yep"))).isSameAs(True);
    // })
    // t.Run("local_default", func(t *testing.T) {
    vars = mapOf("attrs", mapOf(), "default", "fourth");
    out = prg.eval(vars);
    assertThat(out.getVal().equal(stringOf("fourth"))).isSameAs(True);
// })
}
Also used : BoolT(org.projectnessie.cel.common.types.BoolT) Interpretable(org.projectnessie.cel.interpreter.Interpretable) Macro(org.projectnessie.cel.parser.Macro) Call(com.google.api.expr.v1alpha1.Expr.Call) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) PartialActivation(org.projectnessie.cel.interpreter.Activation.PartialActivation) EnvOption.container(org.projectnessie.cel.EnvOption.container) Macro.newReceiverMacro(org.projectnessie.cel.parser.Macro.newReceiverMacro) Activation.emptyActivation(org.projectnessie.cel.interpreter.Activation.emptyActivation) Disabled(org.junit.jupiter.api.Disabled) InterpretableDecorator(org.projectnessie.cel.interpreter.InterpretableDecorator) Collections.singletonList(java.util.Collections.singletonList) True(org.projectnessie.cel.common.types.BoolT.True) Err.isError(org.projectnessie.cel.common.types.Err.isError) Container(org.projectnessie.cel.common.types.traits.Container) Arrays.asList(java.util.Arrays.asList) CEL.estimateCost(org.projectnessie.cel.CEL.estimateCost) OptPartialEval(org.projectnessie.cel.EvalOption.OptPartialEval) ProtoTypeRegistry.newEmptyRegistry(org.projectnessie.cel.common.types.pb.ProtoTypeRegistry.newEmptyRegistry) ParsedExpr(com.google.api.expr.v1alpha1.ParsedExpr) EnvOption.customTypeProvider(org.projectnessie.cel.EnvOption.customTypeProvider) Val(org.projectnessie.cel.common.types.ref.Val) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) InterpretableAttribute(org.projectnessie.cel.interpreter.Interpretable.InterpretableAttribute) Collections.emptyList(java.util.Collections.emptyList) Expr(com.google.api.expr.v1alpha1.Expr) Ident(com.google.api.expr.v1alpha1.Expr.Ident) InterpretableCall(org.projectnessie.cel.interpreter.Interpretable.InterpretableCall) OptExhaustiveEval(org.projectnessie.cel.EvalOption.OptExhaustiveEval) OptTrackState(org.projectnessie.cel.EvalOption.OptTrackState) StringT.stringOf(org.projectnessie.cel.common.types.StringT.stringOf) Decls(org.projectnessie.cel.checker.Decls) CEL.attributePattern(org.projectnessie.cel.CEL.attributePattern) Executors(java.util.concurrent.Executors) Test(org.junit.jupiter.api.Test) ProgramOption.functions(org.projectnessie.cel.ProgramOption.functions) DefaultTypeAdapter(org.projectnessie.cel.common.types.pb.DefaultTypeAdapter) Overload(org.projectnessie.cel.interpreter.functions.Overload) EvalResult(org.projectnessie.cel.Program.EvalResult) Err.newErr(org.projectnessie.cel.common.types.Err.newErr) IntOne(org.projectnessie.cel.common.types.IntT.IntOne) IntStream(java.util.stream.IntStream) Overloads(org.projectnessie.cel.common.types.Overloads) Env.newEnv(org.projectnessie.cel.Env.newEnv) StdLib(org.projectnessie.cel.Library.StdLib) IntT(org.projectnessie.cel.common.types.IntT) Trait(org.projectnessie.cel.common.types.traits.Trait) EnvOption.declarations(org.projectnessie.cel.EnvOption.declarations) CompletableFuture(java.util.concurrent.CompletableFuture) Err.valOrErr(org.projectnessie.cel.common.types.Err.valOrErr) CEL.partialVars(org.projectnessie.cel.CEL.partialVars) AtomicReference(java.util.concurrent.atomic.AtomicReference) EnvOption.customTypeAdapter(org.projectnessie.cel.EnvOption.customTypeAdapter) AstIssuesTuple(org.projectnessie.cel.Env.AstIssuesTuple) Mapper(org.projectnessie.cel.common.types.traits.Mapper) ProgramOption.evalOptions(org.projectnessie.cel.ProgramOption.evalOptions) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Type(com.google.api.expr.v1alpha1.Type) CEL.astToCheckedExpr(org.projectnessie.cel.CEL.astToCheckedExpr) CEL.noVars(org.projectnessie.cel.CEL.noVars) ExecutorService(java.util.concurrent.ExecutorService) Collections.emptyMap(java.util.Collections.emptyMap) CEL.astToString(org.projectnessie.cel.CEL.astToString) ProgramOption.globals(org.projectnessie.cel.ProgramOption.globals) Operator(org.projectnessie.cel.common.operators.Operator) NamespacedAttribute(org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute) UnknownT(org.projectnessie.cel.common.types.UnknownT) Cost(org.projectnessie.cel.interpreter.Coster.Cost) EnvOption.types(org.projectnessie.cel.EnvOption.types) ProgramOption.customDecorator(org.projectnessie.cel.ProgramOption.customDecorator) EnvOption.macros(org.projectnessie.cel.EnvOption.macros) Interpretable.newConstValue(org.projectnessie.cel.interpreter.Interpretable.newConstValue) CheckedExpr(com.google.api.expr.v1alpha1.CheckedExpr) CEL.parsedExprToAst(org.projectnessie.cel.CEL.parsedExprToAst) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) InterpretableConst(org.projectnessie.cel.interpreter.Interpretable.InterpretableConst) CEL.astToParsedExpr(org.projectnessie.cel.CEL.astToParsedExpr) CEL.checkedExprToAst(org.projectnessie.cel.CEL.checkedExprToAst) EvalState(org.projectnessie.cel.interpreter.EvalState) Util.mapOf(org.projectnessie.cel.Util.mapOf) StringT(org.projectnessie.cel.common.types.StringT) EnvOption.homogeneousAggregateLiterals(org.projectnessie.cel.EnvOption.homogeneousAggregateLiterals) Env.newCustomEnv(org.projectnessie.cel.Env.newCustomEnv) EnvOption.abbrevs(org.projectnessie.cel.EnvOption.abbrevs) Val(org.projectnessie.cel.common.types.ref.Val) Mapper(org.projectnessie.cel.common.types.traits.Mapper) Type(com.google.api.expr.v1alpha1.Type) EvalResult(org.projectnessie.cel.Program.EvalResult) Env.newEnv(org.projectnessie.cel.Env.newEnv) Env.newCustomEnv(org.projectnessie.cel.Env.newCustomEnv) AstIssuesTuple(org.projectnessie.cel.Env.AstIssuesTuple) StringT(org.projectnessie.cel.common.types.StringT) Test(org.junit.jupiter.api.Test)

Example 3 with True

use of org.projectnessie.cel.common.types.BoolT.True in project cel-java by projectnessie.

the class ProviderTest method typeRegistryGetters.

@Test
void typeRegistryGetters() {
    TypeRegistry reg = newRegistry(ParsedExpr.getDefaultInstance());
    Val sourceInfo = reg.newValue("google.api.expr.v1alpha1.SourceInfo", mapOf("location", stringOf("TestTypeRegistryGetFieldValue"), "line_offsets", newGenericArrayList(reg, new Long[] { 0L, 2L }), "positions", newMaybeWrappedMap(reg, mapOf(1L, 2L, 3L, 4L))));
    assertThat(sourceInfo).matches(v -> !Err.isError(v));
    Indexer si = (Indexer) sourceInfo;
    Val loc = si.get(stringOf("location"));
    assertThat(loc.equal(stringOf("TestTypeRegistryGetFieldValue"))).isSameAs(True);
    Val pos = si.get(stringOf("positions"));
    assertThat(pos.equal(newMaybeWrappedMap(reg, mapOf(1, 2, 3, 4)))).isSameAs(True);
    Val posKeyVal = ((Indexer) pos).get(intOf(1));
    assertThat(posKeyVal.intValue()).isEqualTo(2);
    Val offsets = si.get(stringOf("line_offsets"));
    assertThat(offsets).matches(v -> !Err.isError(v));
    Val offset1 = ((Lister) offsets).get(intOf(1));
    assertThat(offset1).matches(v -> !Err.isError(v)).isEqualTo(intOf(2));
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) Lister(org.projectnessie.cel.common.types.traits.Lister) Indexer(org.projectnessie.cel.common.types.traits.Indexer) Date(java.util.Date) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) StringValue(com.google.protobuf.StringValue) ULong(org.projectnessie.cel.common.ULong) Disabled(org.junit.jupiter.api.Disabled) True(org.projectnessie.cel.common.types.BoolT.True) Arrays.asList(java.util.Arrays.asList) Duration(java.time.Duration) ProtoTypeRegistry.newEmptyRegistry(org.projectnessie.cel.common.types.pb.ProtoTypeRegistry.newEmptyRegistry) ParsedExpr(com.google.api.expr.v1alpha1.ParsedExpr) Val(org.projectnessie.cel.common.types.ref.Val) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) FloatValue(com.google.protobuf.FloatValue) False(org.projectnessie.cel.common.types.BoolT.False) DoubleT.doubleOf(org.projectnessie.cel.common.types.DoubleT.doubleOf) Expr(com.google.api.expr.v1alpha1.Expr) StringT.stringOf(org.projectnessie.cel.common.types.StringT.stringOf) Instant(java.time.Instant) IntT.intOf(org.projectnessie.cel.common.types.IntT.intOf) StandardCharsets(java.nio.charset.StandardCharsets) UintT.uintOf(org.projectnessie.cel.common.types.UintT.uintOf) ByteString(com.google.protobuf.ByteString) Test(org.junit.jupiter.api.Test) TimestampT.timestampOf(org.projectnessie.cel.common.types.TimestampT.timestampOf) BytesValue(com.google.protobuf.BytesValue) ListT.newGenericArrayList(org.projectnessie.cel.common.types.ListT.newGenericArrayList) NULL_VALUE(com.google.protobuf.NullValue.NULL_VALUE) ZoneIdZ(org.projectnessie.cel.common.types.TimestampT.ZoneIdZ) SourceInfo(com.google.api.expr.v1alpha1.SourceInfo) Int64Value(com.google.protobuf.Int64Value) BoolValue(com.google.protobuf.BoolValue) UInt64Value(com.google.protobuf.UInt64Value) DurationT.durationOf(org.projectnessie.cel.common.types.DurationT.durationOf) Timestamp(com.google.protobuf.Timestamp) ProtoTypeRegistry(org.projectnessie.cel.common.types.pb.ProtoTypeRegistry) ProtoTypeRegistry.newRegistry(org.projectnessie.cel.common.types.pb.ProtoTypeRegistry.newRegistry) Calendar(java.util.Calendar) GlobalEnum(com.google.api.expr.test.v1.proto3.TestAllTypesProto.GlobalEnum) Constant(com.google.api.expr.v1alpha1.Constant) DoubleValue(com.google.protobuf.DoubleValue) Int32Value(com.google.protobuf.Int32Value) UInt32Value(com.google.protobuf.UInt32Value) CheckedExpr(com.google.api.expr.v1alpha1.CheckedExpr) BytesT.bytesOf(org.projectnessie.cel.common.types.BytesT.bytesOf) TimeUnit(java.util.concurrent.TimeUnit) IntZero(org.projectnessie.cel.common.types.IntT.IntZero) TestAllTypes(com.google.api.expr.test.v1.proto3.TestAllTypesProto.TestAllTypes) Message(com.google.protobuf.Message) Util.mapOf(org.projectnessie.cel.Util.mapOf) MapT.newMaybeWrappedMap(org.projectnessie.cel.common.types.MapT.newMaybeWrappedMap) NullValue(org.projectnessie.cel.common.types.NullT.NullValue) Indexer(org.projectnessie.cel.common.types.traits.Indexer) Lister(org.projectnessie.cel.common.types.traits.Lister) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) ProtoTypeRegistry(org.projectnessie.cel.common.types.pb.ProtoTypeRegistry) Test(org.junit.jupiter.api.Test)

Example 4 with True

use of org.projectnessie.cel.common.types.BoolT.True in project cel-java by projectnessie.

the class JacksonTypeDescriptionTest method collectionsObjectTypeTest.

@Test
void collectionsObjectTypeTest() throws Exception {
    CollectionsObject collectionsObject = new CollectionsObject();
    // populate (primitive) map types
    collectionsObject.stringBooleanMap = singletonMap("a", true);
    collectionsObject.byteShortMap = singletonMap((byte) 1, (short) 2);
    collectionsObject.intLongMap = singletonMap(1, 2L);
    collectionsObject.ulongTimestampMap = singletonMap(ULong.valueOf(1), Timestamp.newBuilder().setSeconds(1).build());
    collectionsObject.ulongZonedDateTimeMap = singletonMap(ULong.valueOf(1), ZonedDateTime.of(LocalDateTime.ofEpochSecond(1, 0, ZoneOffset.UTC), ZoneId.of("UTC")));
    collectionsObject.stringProtoDurationMap = singletonMap("a", Duration.newBuilder().setSeconds(1).build());
    collectionsObject.stringJavaDurationMap = singletonMap("a", java.time.Duration.ofSeconds(1));
    collectionsObject.stringBytesMap = singletonMap("a", ByteString.copyFrom(new byte[] { (byte) 1 }));
    collectionsObject.floatDoubleMap = singletonMap(1f, 2d);
    // populate (primitive) list types
    collectionsObject.stringList = asList("a", "b", "c");
    collectionsObject.booleanList = asList(true, true, false, false);
    collectionsObject.byteList = asList((byte) 1, (byte) 2, (byte) 3);
    collectionsObject.shortList = asList((short) 4, (short) 5, (short) 6);
    collectionsObject.intList = asList(7, 8, 9);
    collectionsObject.longList = asList(10L, 11L, 12L);
    collectionsObject.ulongList = asList(ULong.valueOf(1), ULong.valueOf(2), ULong.valueOf(3));
    collectionsObject.timestampList = asList(Timestamp.newBuilder().setSeconds(1).build(), Timestamp.newBuilder().setSeconds(2).build(), Timestamp.newBuilder().setSeconds(3).build());
    collectionsObject.zonedDateTimeList = asList(ZonedDateTime.of(LocalDateTime.ofEpochSecond(1, 0, ZoneOffset.UTC), ZoneId.of("UTC")), ZonedDateTime.of(LocalDateTime.ofEpochSecond(2, 0, ZoneOffset.UTC), ZoneId.of("UTC")), ZonedDateTime.of(LocalDateTime.ofEpochSecond(3, 0, ZoneOffset.UTC), ZoneId.of("UTC")));
    collectionsObject.durationList = asList(Duration.newBuilder().setSeconds(1).build(), Duration.newBuilder().setSeconds(2).build(), Duration.newBuilder().setSeconds(3).build());
    collectionsObject.javaDurationList = asList(java.time.Duration.ofSeconds(1), java.time.Duration.ofSeconds(2), java.time.Duration.ofSeconds(3));
    collectionsObject.bytesList = asList(ByteString.copyFrom(new byte[] { (byte) 1 }), ByteString.copyFrom(new byte[] { (byte) 2 }), ByteString.copyFrom(new byte[] { (byte) 3 }));
    collectionsObject.floatList = asList(1f, 2f, 3f);
    collectionsObject.doubleList = asList(1d, 2d, 3d);
    // populate inner/nested type list/map
    InnerType inner1 = new InnerType();
    inner1.intProp = 1;
    inner1.wrappedIntProp = 2;
    collectionsObject.stringInnerMap = singletonMap("a", inner1);
    InnerType inner2 = new InnerType();
    inner2.intProp = 3;
    inner2.wrappedIntProp = 4;
    collectionsObject.innerTypes = asList(inner1, inner2);
    // populate enum-related fields
    collectionsObject.anEnum = AnEnum.ENUM_VALUE_2;
    collectionsObject.anEnumList = asList(AnEnum.ENUM_VALUE_2, AnEnum.ENUM_VALUE_3);
    collectionsObject.anEnumStringMap = singletonMap(AnEnum.ENUM_VALUE_2, "a");
    collectionsObject.stringAnEnumMap = singletonMap("a", AnEnum.ENUM_VALUE_2);
    // prepare registry
    JacksonRegistry reg = (JacksonRegistry) newRegistry();
    reg.register(CollectionsObject.class);
    Val collectionsVal = reg.nativeToValue(collectionsObject);
    assertThat(collectionsVal).isInstanceOf(ObjectT.class);
    ObjectT obj = (ObjectT) collectionsVal;
    for (String field : CollectionsObject.ALL_PROPERTIES) {
        assertThat(obj.isSet(stringOf(field))).isSameAs(True);
        assertThat(obj.get(stringOf(field))).isNotNull();
        Val fieldVal = obj.get(stringOf(field));
        Object fieldObj = CollectionsObject.class.getDeclaredField(field).get(collectionsObject);
        if (fieldObj instanceof Map) {
            assertThat(fieldVal).isInstanceOf(MapT.class);
        } else if (fieldObj instanceof List) {
            assertThat(fieldVal).isInstanceOf(ListT.class);
        }
        assertThat(fieldVal.equal(reg.nativeToValue(fieldObj))).isSameAs(True);
    }
    // check a few properties manually/explicitly
    MapT mapVal = (MapT) obj.get(stringOf("intLongMap"));
    assertThat(mapVal).extracting(MapT::size, m -> m.contains(intOf(42)), m -> m.contains(intOf(1)), m -> m.contains(intOf(2)), m -> m.contains(intOf(3)), m -> m.get(intOf(1))).containsExactly(intOf(1), False, True, False, False, intOf(2));
    ListT listVal = (ListT) obj.get(stringOf("ulongList"));
    assertThat(listVal).extracting(ListT::size, l -> l.contains(uintOf(42)), l -> l.contains(uintOf(1)), l -> l.contains(uintOf(2)), l -> l.contains(uintOf(3)), l -> l.get(intOf(0)), l -> l.get(intOf(1)), l -> l.get(intOf(2))).containsExactly(intOf(3), False, True, True, True, uintOf(1), uintOf(2), uintOf(3));
    mapVal = (MapT) obj.get(stringOf("stringInnerMap"));
    assertThat(mapVal).extracting(MapT::size, m -> m.contains(stringOf("42")), m -> m.contains(stringOf("a"))).containsExactly(intOf(1), False, True);
    ObjectT i = (ObjectT) mapVal.get(stringOf("a"));
    assertThat(i).extracting(o -> o.get(stringOf("intProp")), o -> o.get(stringOf("wrappedIntProp"))).containsExactly(intOf(1), intOf(2));
    listVal = (ListT) obj.get(stringOf("innerTypes"));
    assertThat(listVal).extracting(ListT::size).isEqualTo(intOf(2));
    i = (ObjectT) listVal.get(intOf(0));
    assertThat(i).extracting(o -> o.get(stringOf("intProp")), o -> o.get(stringOf("wrappedIntProp"))).containsExactly(intOf(1), intOf(2));
    i = (ObjectT) listVal.get(intOf(1));
    assertThat(i).extracting(o -> o.get(stringOf("intProp")), o -> o.get(stringOf("wrappedIntProp"))).containsExactly(intOf(3), intOf(4));
    // verify enums
    Val x = obj.get(stringOf("anEnum"));
    assertThat(x).isInstanceOf(IntT.class).isEqualTo(intOf(AnEnum.ENUM_VALUE_2.ordinal()));
    listVal = (ListT) obj.get(stringOf("anEnumList"));
    assertThat(listVal).extracting(l -> l.get(intOf(0)), l -> l.get(intOf(1))).containsExactly(intOf(AnEnum.ENUM_VALUE_2.ordinal()), intOf(AnEnum.ENUM_VALUE_3.ordinal()));
    mapVal = (MapT) obj.get(stringOf("anEnumStringMap"));
    assertThat(mapVal).extracting(l -> l.get(intOf(AnEnum.ENUM_VALUE_2.ordinal()))).isEqualTo(stringOf("a"));
    mapVal = (MapT) obj.get(stringOf("stringAnEnumMap"));
    assertThat(mapVal).extracting(l -> l.get(stringOf("a"))).isEqualTo(intOf(AnEnum.ENUM_VALUE_2.ordinal()));
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) ListT(org.projectnessie.cel.common.types.ListT) MapT(org.projectnessie.cel.common.types.MapT) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ZonedDateTime(java.time.ZonedDateTime) LocalDateTime(java.time.LocalDateTime) AnEnum(org.projectnessie.cel.types.jackson.types.AnEnum) IntT(org.projectnessie.cel.common.types.IntT) ULong(org.projectnessie.cel.common.ULong) Timestamp(com.google.protobuf.Timestamp) ListType(com.google.api.expr.v1alpha1.Type.ListType) Err(org.projectnessie.cel.common.types.Err) True(org.projectnessie.cel.common.types.BoolT.True) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) JavaType(com.fasterxml.jackson.databind.JavaType) ZoneOffset(java.time.ZoneOffset) Val(org.projectnessie.cel.common.types.ref.Val) JacksonRegistry.newRegistry(org.projectnessie.cel.types.jackson.JacksonRegistry.newRegistry) MapType(com.google.api.expr.v1alpha1.Type.MapType) False(org.projectnessie.cel.common.types.BoolT.False) StringT.stringOf(org.projectnessie.cel.common.types.StringT.stringOf) NullT(org.projectnessie.cel.common.types.NullT) IntT.intOf(org.projectnessie.cel.common.types.IntT.intOf) ZoneId(java.time.ZoneId) UintT.uintOf(org.projectnessie.cel.common.types.UintT.uintOf) ByteString(com.google.protobuf.ByteString) Test(org.junit.jupiter.api.Test) CollectionsObject(org.projectnessie.cel.types.jackson.types.CollectionsObject) TypeT(org.projectnessie.cel.common.types.TypeT) InnerType(org.projectnessie.cel.types.jackson.types.InnerType) Duration(com.google.protobuf.Duration) List(java.util.List) ObjectT(org.projectnessie.cel.common.types.ObjectT) Checked(org.projectnessie.cel.common.types.pb.Checked) TypeKindCase(com.google.api.expr.v1alpha1.Type.TypeKindCase) IntT(org.projectnessie.cel.common.types.IntT) InnerType(org.projectnessie.cel.types.jackson.types.InnerType) ByteString(com.google.protobuf.ByteString) CollectionsObject(org.projectnessie.cel.types.jackson.types.CollectionsObject) ListT(org.projectnessie.cel.common.types.ListT) ObjectT(org.projectnessie.cel.common.types.ObjectT) CollectionsObject(org.projectnessie.cel.types.jackson.types.CollectionsObject) Arrays.asList(java.util.Arrays.asList) List(java.util.List) MapT(org.projectnessie.cel.common.types.MapT) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) Test(org.junit.jupiter.api.Test)

Example 5 with True

use of org.projectnessie.cel.common.types.BoolT.True in project cel-java by projectnessie.

the class AttributesTest method attributeStateTracking.

@ParameterizedTest
@MethodSource("attributeStateTrackingTests")
void attributeStateTracking(TestDef tc) {
    Source src = Source.newTextSource(tc.expr);
    ParseResult parsed = Parser.parseAllMacros(src);
    assertThat(parsed.hasErrors()).isFalse();
    Container cont = Container.defaultContainer;
    TypeRegistry reg = newRegistry();
    CheckerEnv env = newStandardCheckerEnv(cont, reg);
    if (tc.env != null) {
        env.add(tc.env);
    }
    CheckResult checkResult = Checker.Check(parsed, src, env);
    if (parsed.hasErrors()) {
        throw new IllegalArgumentException(parsed.getErrors().toDisplayString());
    }
    AttributeFactory attrs = newAttributeFactory(cont, reg, reg);
    Interpreter interp = newStandardInterpreter(cont, reg, reg, attrs);
    // Show that program planning will now produce an error.
    EvalState st = newEvalState();
    Interpretable i = interp.newInterpretable(checkResult.getCheckedExpr(), optimize(), trackState(st));
    Activation in = newActivation(tc.in);
    Val out = i.eval(in);
    assertThat(out).extracting(o -> o.equal(tc.out)).isSameAs(True);
    for (Entry<Object, Object> iv : tc.state.entrySet()) {
        long id = ((Number) iv.getKey()).longValue();
        Object val = iv.getValue();
        Val stVal = st.value(id);
        assertThat(stVal).withFailMessage(() -> String.format("id(%d), val=%s, stVal=%s", id, val, stVal)).isNotNull();
        assertThat(stVal).withFailMessage(() -> String.format("id(%d), val=%s, stVal=%s", id, val, stVal)).isEqualTo(DefaultTypeAdapter.Instance.nativeToValue(val));
        deepEquals(String.format("id(%d)", id), stVal.value(), val);
    }
}
Also used : Val(org.projectnessie.cel.common.types.ref.Val) Cost.estimateCost(org.projectnessie.cel.interpreter.Coster.Cost.estimateCost) Arrays(java.util.Arrays) AttributePattern.newPartialAttributeFactory(org.projectnessie.cel.interpreter.AttributePattern.newPartialAttributeFactory) ParseResult(org.projectnessie.cel.parser.Parser.ParseResult) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Interpreter.optimize(org.projectnessie.cel.interpreter.Interpreter.optimize) Source(org.projectnessie.cel.common.Source) AttributePattern.newAttributePattern(org.projectnessie.cel.interpreter.AttributePattern.newAttributePattern) Activation.emptyActivation(org.projectnessie.cel.interpreter.Activation.emptyActivation) IntType(org.projectnessie.cel.common.types.IntT.IntType) True(org.projectnessie.cel.common.types.BoolT.True) Interpreter.trackState(org.projectnessie.cel.interpreter.Interpreter.trackState) Map(java.util.Map) CheckerEnv.newStandardCheckerEnv(org.projectnessie.cel.checker.CheckerEnv.newStandardCheckerEnv) Val(org.projectnessie.cel.common.types.ref.Val) Container.newContainer(org.projectnessie.cel.common.containers.Container.newContainer) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) MethodSource(org.junit.jupiter.params.provider.MethodSource) False(org.projectnessie.cel.common.types.BoolT.False) StringT.stringOf(org.projectnessie.cel.common.types.StringT.stringOf) Decls(org.projectnessie.cel.checker.Decls) IntT.intOf(org.projectnessie.cel.common.types.IntT.intOf) Test(org.junit.jupiter.api.Test) CheckerEnv(org.projectnessie.cel.checker.CheckerEnv) List(java.util.List) UnknownT.unknownOf(org.projectnessie.cel.common.types.UnknownT.unknownOf) Entry(java.util.Map.Entry) DefaultTypeAdapter(org.projectnessie.cel.common.types.pb.DefaultTypeAdapter) Activation.newPartialActivation(org.projectnessie.cel.interpreter.Activation.newPartialActivation) Any(com.google.protobuf.Any) Err.newErr(org.projectnessie.cel.common.types.Err.newErr) NestedMessage(com.google.api.expr.test.v1.proto3.TestAllTypesProto.TestAllTypes.NestedMessage) Checker(org.projectnessie.cel.checker.Checker) CheckResult(org.projectnessie.cel.checker.Checker.CheckResult) Parser(org.projectnessie.cel.parser.Parser) EvalState.newEvalState(org.projectnessie.cel.interpreter.EvalState.newEvalState) Util.deepEquals(org.projectnessie.cel.Util.deepEquals) Qualifier(org.projectnessie.cel.interpreter.AttributeFactory.Qualifier) ProtoTypeRegistry.newRegistry(org.projectnessie.cel.common.types.pb.ProtoTypeRegistry.newRegistry) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) Type(com.google.api.expr.v1alpha1.Type) AttributeFactory.newAttributeFactory(org.projectnessie.cel.interpreter.AttributeFactory.newAttributeFactory) NamespacedAttribute(org.projectnessie.cel.interpreter.AttributeFactory.NamespacedAttribute) UnknownT(org.projectnessie.cel.common.types.UnknownT) Container(org.projectnessie.cel.common.containers.Container) Interpretable.newConstValue(org.projectnessie.cel.interpreter.Interpretable.newConstValue) Attribute(org.projectnessie.cel.interpreter.AttributeFactory.Attribute) Decl(com.google.api.expr.v1alpha1.Decl) InterpretableConst(org.projectnessie.cel.interpreter.Interpretable.InterpretableConst) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Activation.newActivation(org.projectnessie.cel.interpreter.Activation.newActivation) TestAllTypes(com.google.api.expr.test.v1.proto3.TestAllTypesProto.TestAllTypes) Util.mapOf(org.projectnessie.cel.Util.mapOf) Interpreter.newStandardInterpreter(org.projectnessie.cel.interpreter.Interpreter.newStandardInterpreter) Interpreter.newStandardInterpreter(org.projectnessie.cel.interpreter.Interpreter.newStandardInterpreter) ParseResult(org.projectnessie.cel.parser.Parser.ParseResult) AttributePattern.newPartialAttributeFactory(org.projectnessie.cel.interpreter.AttributePattern.newPartialAttributeFactory) AttributeFactory.newAttributeFactory(org.projectnessie.cel.interpreter.AttributeFactory.newAttributeFactory) Activation.emptyActivation(org.projectnessie.cel.interpreter.Activation.emptyActivation) Activation.newPartialActivation(org.projectnessie.cel.interpreter.Activation.newPartialActivation) Activation.newActivation(org.projectnessie.cel.interpreter.Activation.newActivation) TypeRegistry(org.projectnessie.cel.common.types.ref.TypeRegistry) Source(org.projectnessie.cel.common.Source) MethodSource(org.junit.jupiter.params.provider.MethodSource) Container.newContainer(org.projectnessie.cel.common.containers.Container.newContainer) Container(org.projectnessie.cel.common.containers.Container) CheckResult(org.projectnessie.cel.checker.Checker.CheckResult) CheckerEnv.newStandardCheckerEnv(org.projectnessie.cel.checker.CheckerEnv.newStandardCheckerEnv) CheckerEnv(org.projectnessie.cel.checker.CheckerEnv) EvalState.newEvalState(org.projectnessie.cel.interpreter.EvalState.newEvalState) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Aggregations

Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)6 Test (org.junit.jupiter.api.Test)6 True (org.projectnessie.cel.common.types.BoolT.True)6 StringT.stringOf (org.projectnessie.cel.common.types.StringT.stringOf)6 Val (org.projectnessie.cel.common.types.ref.Val)6 Assertions.assertThatThrownBy (org.assertj.core.api.Assertions.assertThatThrownBy)5 Util.mapOf (org.projectnessie.cel.Util.mapOf)5 TypeRegistry (org.projectnessie.cel.common.types.ref.TypeRegistry)5 Arrays.asList (java.util.Arrays.asList)4 CheckedExpr (com.google.api.expr.v1alpha1.CheckedExpr)3 Expr (com.google.api.expr.v1alpha1.Expr)3 ParsedExpr (com.google.api.expr.v1alpha1.ParsedExpr)3 TimeUnit (java.util.concurrent.TimeUnit)3 Disabled (org.junit.jupiter.api.Disabled)3 IntT (org.projectnessie.cel.common.types.IntT)3 ProtoTypeRegistry.newEmptyRegistry (org.projectnessie.cel.common.types.pb.ProtoTypeRegistry.newEmptyRegistry)3 Decl (com.google.api.expr.v1alpha1.Decl)2 Call (com.google.api.expr.v1alpha1.Expr.Call)2 Ident (com.google.api.expr.v1alpha1.Expr.Ident)2 Type (com.google.api.expr.v1alpha1.Type)2