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);
// })
}
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);
// })
}
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));
}
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()));
}
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);
}
}
Aggregations