diff --git a/build.gradle.kts b/build.gradle.kts index bc7189bd0..891add1c6 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -144,76 +144,8 @@ tasks.register("generateTestSourcesNoImports") { ) } -tasks.register("generateCelConformance") { - dependsOn("generateCelConformanceTestTypes", "filterBufGenYaml") - description = "Generates CEL conformance code with buf generate for unit tests." - val template = layout.buildDirectory.file("buf-gen-templates/src/test/resources/proto/buf.gen.cel.yaml") - inputs.files(buf) - inputs.file(template) - inputs.property("celSpecVersion", project.findProperty("cel.spec.version").toString()) - outputs.dir(layout.buildDirectory.dir("generated/test-sources/bufgen-cel")) - commandLine( - buf.asPath, - "generate", - "--template", - template.get().asFile.absolutePath, - "buf.build/google/cel-spec:${project.findProperty("cel.spec.version")}", - "--exclude-path", - "cel/expr/conformance/proto2", - "--exclude-path", - "cel/expr/conformance/proto3", - ) -} - -// The conformance tests use the Protobuf package path for tests that use these types. -// i.e. cel.expr.conformance.proto3.TestAllTypes. But, if we use managed mode it adds 'com' -// to the prefix. Additionally, we can't disable managed mode because the java_package option -// specified in these proto files is "dev.cel.expr.conformance.proto3". So, to get around this, -// we're generating these separately and specifying a java_package override of the package we need. -tasks.register("generateCelConformanceTestTypes") { - dependsOn("exportProtovalidateModule", "filterBufGenYaml") - description = "Generates CEL conformance test types with buf generate for unit tests using a Java package override." - val template = layout.buildDirectory.file("buf-gen-templates/src/test/resources/proto/buf.gen.cel.testtypes.yaml") - inputs.files(buf) - inputs.file(template) - inputs.property("celSpecVersion", project.findProperty("cel.spec.version").toString()) - outputs.dir(layout.buildDirectory.dir("generated/test-sources/bufgen-cel-testtypes")) - commandLine( - buf.asPath, - "generate", - "--template", - template.get().asFile.absolutePath, - "buf.build/google/cel-spec:${project.findProperty("cel.spec.version")}", - "--path", - "cel/expr/conformance/proto3", - ) -} - -var getCelTestData = - tasks.register("getCelTestData") { - val celVersion = project.findProperty("cel.spec.version") - val fileUrl = "https://raw.githubusercontent.com/google/cel-spec/refs/tags/$celVersion/tests/simple/testdata/string_ext.textproto" - val targetDir = File("${project.projectDir}/src/test/resources/testdata") - val file = File(targetDir, "string_ext_$celVersion.textproto") - - onlyIf { - // Only run curl if file doesn't exist - !file.exists() - } - doFirst { - file.parentFile.mkdirs() - commandLine( - "curl", - "-fsSL", - "-o", - file.absolutePath, - fileUrl, - ) - } - } - tasks.register("generateTestSources") { - dependsOn("generateTestSourcesImports", "generateTestSourcesNoImports", "generateCelConformance") + dependsOn("generateTestSourcesImports", "generateTestSourcesNoImports") description = "Generates code with buf generate for unit tests" } @@ -309,8 +241,6 @@ sourceSets { java { srcDir(layout.buildDirectory.dir("generated/test-sources/bufgen-imports")) srcDir(layout.buildDirectory.dir("generated/test-sources/bufgen-noimports")) - srcDir(layout.buildDirectory.dir("generated/test-sources/bufgen-cel")) - srcDir(layout.buildDirectory.dir("generated/test-sources/bufgen-cel-testtypes")) } } } @@ -351,7 +281,6 @@ allprojects { } } tasks.withType().configureEach { - dependsOn(getCelTestData) useJUnitPlatform() this.testLogging { events("failed") diff --git a/gradle.properties b/gradle.properties index fb1eaea7f..fd9222118 100644 --- a/gradle.properties +++ b/gradle.properties @@ -6,6 +6,3 @@ protovalidate.conformance.args = --strict_message --strict_error --expected_fail # Argument to the license-header CLI license-header.years = 2023-2026 - -# Version of the cel-spec that this implementation is conformant with -cel.spec.version = v0.24.0 diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 466745b2b..96fb88d2b 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -1,7 +1,7 @@ [versions] assertj = "3.27.7" buf = "1.75.0" -cel = "0.14.0" +cel = "0.15.0" error-prone = "2.51.0" junit = "5.14.4" maven-publish = "0.37.0" diff --git a/src/main/java/build/buf/protovalidate/CustomDeclarations.java b/src/main/java/build/buf/protovalidate/CustomDeclarations.java index a4f61bf8b..5492b6b67 100644 --- a/src/main/java/build/buf/protovalidate/CustomDeclarations.java +++ b/src/main/java/build/buf/protovalidate/CustomDeclarations.java @@ -186,16 +186,6 @@ static List create() { } decls.add(newFunctionDeclaration("unique", uniqueOverloads)); - // Add 'format' function declaration - List formatOverloads = new ArrayList<>(); - formatOverloads.add( - newMemberOverload( - "format_list_dyn", - SimpleType.STRING, - Arrays.asList(SimpleType.STRING, ListType.create(SimpleType.DYN)))); - - decls.add(newFunctionDeclaration("format", formatOverloads)); - return Collections.unmodifiableList(decls); } } diff --git a/src/main/java/build/buf/protovalidate/CustomOverload.java b/src/main/java/build/buf/protovalidate/CustomOverload.java index 197fcfd42..0dd74f9b8 100644 --- a/src/main/java/build/buf/protovalidate/CustomOverload.java +++ b/src/main/java/build/buf/protovalidate/CustomOverload.java @@ -55,7 +55,6 @@ static List create( bindings.addAll( Arrays.asList( celGetField(), - celFormat(), celStartsWithBytes(), celEndsWithBytes(), celContainsBytes(), @@ -99,15 +98,6 @@ private static CelFunctionBinding celGetField() { }); } - /** - * Creates a custom binary function overload for the "format" operation. - * - * @return The {@link CelFunctionBinding} instance for the "format" operation. - */ - private static CelFunctionBinding celFormat() { - return CelFunctionBinding.from("format_list_dyn", String.class, List.class, Format::format); - } - /** * Creates a custom unary function overload for the "unique" operation. * diff --git a/src/main/java/build/buf/protovalidate/Format.java b/src/main/java/build/buf/protovalidate/Format.java deleted file mode 100644 index af476f83e..000000000 --- a/src/main/java/build/buf/protovalidate/Format.java +++ /dev/null @@ -1,354 +0,0 @@ -// Copyright 2023-2026 Buf Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build.buf.protovalidate; - -import static java.time.format.DateTimeFormatter.ISO_INSTANT; - -import com.google.common.primitives.UnsignedLong; -import com.google.protobuf.Duration; -import com.google.protobuf.Timestamp; -import dev.cel.common.types.TypeType; -import dev.cel.common.values.CelByteString; -import dev.cel.runtime.CelEvaluationException; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.text.DecimalFormat; -import java.time.Instant; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.stream.Collectors; - -/** String formatter for CEL evaluation. */ -final class Format { - /** - * Format the string with a {@link List}. - * - * @param fmtString the string to format. - * @param list the arguments. - * @return the formatted string. - * @throws CelEvaluationException If an error occurs formatting the string. - */ - static String format(String fmtString, List list) throws CelEvaluationException { - // StringBuilder to accumulate the formatted string - StringBuilder builder = new StringBuilder(); - int index = 0; - int argIndex = 0; - while (index < fmtString.length()) { - char c = fmtString.charAt(index++); - if (c != '%') { - // Append non-format characters directly - builder.append(c); - // Add the entire character if it's not a UTF-8 character. - if ((c & 0x80) != 0) { - // Add the rest of the UTF-8 character. - while (index < fmtString.length() && (fmtString.charAt(index) & 0xc0) == 0x80) { - builder.append(fmtString.charAt(index++)); - } - } - continue; - } - if (index >= fmtString.length()) { - throw new CelEvaluationException("format: expected format specifier"); - } - if (fmtString.charAt(index) == '%') { - // Escaped '%', append '%' and move to the next character - builder.append('%'); - index++; - continue; - } - if (argIndex >= list.size()) { - throw new CelEvaluationException("index " + argIndex + " out of range"); - } - Object arg = list.get(argIndex++); - c = fmtString.charAt(index++); - int precision = 6; - if (c == '.') { - // parse the precision - precision = 0; - while (index < fmtString.length() - && '0' <= fmtString.charAt(index) - && fmtString.charAt(index) <= '9') { - precision = precision * 10 + (fmtString.charAt(index++) - '0'); - } - if (index >= fmtString.length()) { - throw new CelEvaluationException("format: expected format specifier"); - } - c = fmtString.charAt(index++); - } - - switch (c) { - case 'd': - builder.append(formatDecimal(arg)); - break; - case 'x': - builder.append(formatHex(arg)); - break; - case 'X': - // We can use a root locale, because the only characters are hex (A-F). - builder.append(formatHex(arg).toUpperCase(Locale.ROOT)); - break; - case 's': - builder.append(formatString(arg)); - break; - case 'e': - builder.append(formatExponential(arg, precision)); - break; - case 'f': - builder.append(formatFloat(arg, precision)); - break; - case 'b': - builder.append(formatBinary(arg)); - break; - case 'o': - builder.append(formatOctal(arg)); - break; - default: - throw new CelEvaluationException( - "could not parse formatting clause: unrecognized formatting clause \"" + c + "\""); - } - } - return builder.toString(); - } - - private static String formatString(Object val) throws CelEvaluationException { - if (val instanceof String) { - return (String) val; - } else if (val instanceof TypeType) { - return ((TypeType) val).containingTypeName(); - } else if (val instanceof Boolean) { - return Boolean.toString((Boolean) val); - } else if (val instanceof Long || val instanceof UnsignedLong) { - Optional str = validateNumber(val); - return str.orElseGet(val::toString); - } else if (val instanceof CelByteString) { - String byteStr = ((CelByteString) val).toStringUtf8(); - // Collapse any contiguous placeholders into one - return byteStr.replaceAll("\\ufffd+", "\ufffd"); - } else if (val instanceof Double) { - Optional result = validateNumber(val); - if (result.isPresent()) { - return result.get(); - } - return formatDecimal(val); - } else if (val instanceof Duration) { - return formatDuration((Duration) val); - } else if (val instanceof java.time.Duration) { - return formatJavaDuration((java.time.Duration) val); - } else if (val instanceof Timestamp) { - return formatTimestamp((Timestamp) val); - } else if (val instanceof java.time.Instant) { - return formatInstant((java.time.Instant) val); - } else if (val instanceof List) { - return formatList((List) val); - } else if (val instanceof Map) { - return formatMap((Map) val); - } else if (val == null || val instanceof dev.cel.common.values.NullValue) { - return "null"; - } - throw new CelEvaluationException( - "error during formatting: string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps, was given " - + val.getClass()); - } - - /** - * Formats a list value. - * - * @param val the value to format. - */ - private static String formatList(List val) throws CelEvaluationException { - StringBuilder builder = new StringBuilder(); - builder.append('['); - - Iterator iter = val.iterator(); - while (iter.hasNext()) { - Object v = iter.next(); - builder.append(formatString(v)); - if (iter.hasNext()) { - builder.append(", "); - } - } - builder.append(']'); - return builder.toString(); - } - - private static String formatMap(Map val) throws CelEvaluationException { - StringBuilder builder = new StringBuilder(); - builder.append('{'); - - SortedMap sorted = new TreeMap<>(); - - for (Entry entry : val.entrySet()) { - sorted.put(formatString(entry.getKey()), formatString(entry.getValue())); - } - - String result = - sorted.entrySet().stream() - .map(entry -> entry.getKey() + ": " + entry.getValue()) - .collect(Collectors.joining(", ")); - - builder.append(result).append('}'); - - return builder.toString(); - } - - private static String formatTimestamp(Timestamp timestamp) { - return ISO_INSTANT.format(Instant.ofEpochSecond(timestamp.getSeconds(), timestamp.getNanos())); - } - - private static String formatInstant(Instant instant) { - return ISO_INSTANT.format(instant); - } - - private static String formatDuration(Duration duration) { - StringBuilder builder = new StringBuilder(); - - double totalSeconds = duration.getSeconds() + (duration.getNanos() / 1_000_000_000.0); - - DecimalFormat formatter = new DecimalFormat("0.#########"); - builder.append(formatter.format(totalSeconds)); - builder.append("s"); - - return builder.toString(); - } - - private static String formatJavaDuration(java.time.Duration duration) { - StringBuilder builder = new StringBuilder(); - double totalSeconds = duration.getSeconds() + (duration.getNano() / 1_000_000_000.0); - - DecimalFormat formatter = new DecimalFormat("0.#########"); - builder.append(formatter.format(totalSeconds)); - builder.append("s"); - - return builder.toString(); - } - - private static String formatHex(Object val) throws CelEvaluationException { - if (val instanceof Long) { - return Long.toHexString((Long) val); - } else if (val instanceof UnsignedLong) { - return Long.toHexString(((UnsignedLong) val).longValue()); - } else if (val instanceof CelByteString) { - StringBuilder hexString = new StringBuilder(); - byte[] celBytes = ((CelByteString) val).toByteArray(); - for (byte b : celBytes) { - hexString.append(String.format("%02x", b)); - } - return hexString.toString(); - } else if (val instanceof String) { - String arg = (String) val; - return String.format("%x", new BigInteger(1, arg.getBytes(StandardCharsets.UTF_8))); - } else { - throw new CelEvaluationException( - "error during formatting: only integers, byte buffers, and strings can be formatted as hex, was given " - + val.getClass()); - } - } - - private static String formatDecimal(Object val) throws CelEvaluationException { - if (val instanceof Long || val instanceof UnsignedLong || val instanceof Double) { - Optional str = validateNumber(val); - if (str.isPresent()) { - return str.get(); - } - DecimalFormat formatter = new DecimalFormat("0.#########"); - return formatter.format(val); - } else { - throw new CelEvaluationException( - "error during formatting: decimal clause can only be used on integers, was given " - + val.getClass()); - } - } - - private static String formatOctal(Object val) throws CelEvaluationException { - if (val instanceof Long) { - return Long.toOctalString((Long) val); - } else if (val instanceof UnsignedLong) { - return Long.toOctalString(((UnsignedLong) val).longValue()); - } else { - throw new CelEvaluationException( - "error during formatting: octal clause can only be used on integers, was given " - + val.getClass()); - } - } - - private static String formatBinary(Object val) throws CelEvaluationException { - if (val instanceof Long) { - return Long.toBinaryString((Long) val); - } else if (val instanceof UnsignedLong) { - return Long.toBinaryString(((UnsignedLong) val).longValue()); - } else if (val instanceof Boolean) { - return Boolean.TRUE.equals(val) ? "1" : "0"; - } else { - throw new CelEvaluationException( - "error during formatting: only integers and bools can be formatted as binary, was given " - + val.getClass()); - } - } - - private static String formatExponential(Object val, int precision) throws CelEvaluationException { - if (val instanceof Double) { - Optional str = validateNumber(val); - if (str.isPresent()) { - return str.get(); - } - String pattern = "%." + precision + "e"; - return String.format(pattern, val); - } else { - throw new CelEvaluationException( - "error during formatting: scientific clause can only be used on doubles, was given " - + val.getClass()); - } - } - - private static String formatFloat(Object val, int precision) throws CelEvaluationException { - if (val instanceof Double) { - Optional str = validateNumber(val); - if (str.isPresent()) { - return str.get(); - } - StringBuilder pattern = new StringBuilder("0."); - if (precision > 0) { - for (int i = 0; i < precision; i++) { - pattern.append("0"); - } - } else { - pattern.append("########"); - } - DecimalFormat formatter = new DecimalFormat(pattern.toString()); - return formatter.format(val); - } else { - throw new CelEvaluationException( - "error during formatting: fixed-point clause can only be used on doubles, was given " - + val.getClass()); - } - } - - private static Optional validateNumber(Object val) { - if (val instanceof Double) { - if ((Double) val == Double.POSITIVE_INFINITY) { - return Optional.of("Infinity"); - } else if ((Double) val == Double.NEGATIVE_INFINITY) { - return Optional.of("-Infinity"); - } - } - return Optional.empty(); - } -} diff --git a/src/main/java/build/buf/protovalidate/ValidateLibrary.java b/src/main/java/build/buf/protovalidate/ValidateLibrary.java index 7d1cbcca0..e03100d4a 100644 --- a/src/main/java/build/buf/protovalidate/ValidateLibrary.java +++ b/src/main/java/build/buf/protovalidate/ValidateLibrary.java @@ -55,12 +55,9 @@ final class ValidateLibrary implements CelCompilerLibrary, CelRuntimeLibrary { static Cel newCel() { ValidateLibrary validateLibrary = new ValidateLibrary(); // Wired by hand instead of via plannerCelBuilder(): CelRuntimeImpl directs callers to subset - // stdlib via setStandardFunctions rather than setStandardEnvironmentEnabled, so the runtime - // does that while the checker uses setStandardEnvironmentEnabled(false). + // stdlib via setStandardFunctions and the checker via setStandardDeclarations. CelCompiler compiler = - CelCompilerImpl.newBuilder( - CelParserImpl.newBuilder(), - CelCheckerLegacyImpl.newBuilder().setStandardEnvironmentEnabled(false)) + CelCompilerImpl.newBuilder(CelParserImpl.newBuilder(), CelCheckerLegacyImpl.newBuilder()) .setOptions(CEL_OPTIONS) // Drop stdlib matches; CustomOverload provides a caching replacement. // Ref: https://github.com/google/cel-java/issues/1038 diff --git a/src/test/java/build/buf/protovalidate/FormatTest.java b/src/test/java/build/buf/protovalidate/FormatTest.java deleted file mode 100644 index c167e03ae..000000000 --- a/src/test/java/build/buf/protovalidate/FormatTest.java +++ /dev/null @@ -1,194 +0,0 @@ -// Copyright 2023-2026 Buf Technologies, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package build.buf.protovalidate; - -import static org.assertj.core.api.Assertions.*; - -import cel.expr.conformance.proto3.TestAllTypes; -import com.cel.expr.Decl; -import com.cel.expr.ExprValue; -import com.cel.expr.Value; -import com.cel.expr.conformance.test.SimpleTest; -import com.cel.expr.conformance.test.SimpleTestFile; -import com.cel.expr.conformance.test.SimpleTestSection; -import com.google.protobuf.TextFormat; -import dev.cel.bundle.Cel; -import dev.cel.bundle.CelBuilder; -import dev.cel.common.CelValidationException; -import dev.cel.common.CelValidationResult; -import dev.cel.common.types.SimpleType; -import dev.cel.runtime.CelEvaluationException; -import dev.cel.runtime.CelRuntime.Program; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Named; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.Arguments; -import org.junit.jupiter.params.provider.MethodSource; - -class FormatTest { - // Version of the cel-spec that this implementation is conformant with - // This should be kept in sync with the version in gradle.properties - private static final String CEL_SPEC_VERSION = "v0.24.0"; - - private static Cel cel; - - private static List formatTests; - private static List formatErrorTests; - - @BeforeAll - public static void setUp() throws Exception { - // The test data from the cel-spec conformance tests - List celSpecSections = - loadTestData("src/test/resources/testdata/string_ext_" + CEL_SPEC_VERSION + ".textproto"); - // Our supplemental tests of functionality not in the cel conformance file, but defined in the - // spec. - List supplementalSections = - loadTestData("src/test/resources/testdata/string_ext_supplemental.textproto"); - - // Combine the test data from both files into one - List sections = - Stream.concat(celSpecSections.stream(), supplementalSections.stream()) - .collect(Collectors.toList()); - - // Find the format tests which test successful formatting - formatTests = - sections.stream() - .filter(s -> s.getName().equals("format")) - .flatMap(s -> s.getTestList().stream()) - .collect(Collectors.toList()); - - // Find the format error tests which test errors during formatting - formatErrorTests = - sections.stream() - .filter(s -> s.getName().equals("format_errors")) - .flatMap(s -> s.getTestList().stream()) - .collect(Collectors.toList()); - - cel = ValidateLibrary.newCel(); - } - - @ParameterizedTest - @MethodSource("getFormatTests") - void testFormatSuccess(SimpleTest test) throws CelValidationException, CelEvaluationException { - Object result = evaluate(test); - assertThat(result).isEqualTo(getExpectedResult(test)); - assertThat(result).isInstanceOf(String.class); - } - - @ParameterizedTest - @MethodSource("getFormatErrorTests") - void testFormatError(SimpleTest test) { - assertThatThrownBy(() -> evaluate(test)).isInstanceOf(CelEvaluationException.class); - } - - // Loads test data from the given text format file - private static List loadTestData(String fileName) throws Exception { - byte[] encoded = Files.readAllBytes(Paths.get(fileName)); - String data = new String(encoded, StandardCharsets.UTF_8); - SimpleTestFile.Builder bldr = SimpleTestFile.newBuilder(); - TextFormat.getParser().merge(data, bldr); - SimpleTestFile testData = bldr.build(); - - return testData.getSectionList(); - } - - // Runs a test by extending the cel environment with the specified - // types, variables and declarations, then evaluating it with the cel runtime. - private static Object evaluate(SimpleTest test) - throws CelValidationException, CelEvaluationException { - - CelBuilder builder = cel.toCelBuilder().addMessageTypes(TestAllTypes.getDescriptor()); - addDecls(builder, test); - Cel newCel = builder.build(); - - CelValidationResult validationResult = newCel.compile(test.getExpr()); - if (!validationResult.getAllIssues().isEmpty()) { - fail("error building AST for evaluation: " + validationResult.getIssueString()); - } - Program program = newCel.createProgram(validationResult.getAst()); - return program.eval(buildVariables(test.getBindingsMap())); - } - - private static Stream getTestStream(List tests) { - List args = new ArrayList<>(); - for (SimpleTest test : tests) { - args.add(Arguments.arguments(Named.named(test.getName(), test))); - } - - return args.stream(); - } - - private static Stream getFormatTests() { - return getTestStream(formatTests); - } - - private static Stream getFormatErrorTests() { - return getTestStream(formatErrorTests); - } - - // Builds the variable definitions to be used during evaluation - private static Map buildVariables(Map bindings) { - Map vars = new HashMap<>(); - for (Map.Entry entry : bindings.entrySet()) { - ExprValue exprValue = entry.getValue(); - if (exprValue.hasValue()) { - Value val = exprValue.getValue(); - if (val.hasStringValue()) { - vars.put(entry.getKey(), val.getStringValue()); - } - } - } - return vars; - } - - // Gets the expected result for a given test - private static String getExpectedResult(SimpleTest test) { - if (test.hasValue()) { - if (test.getValue().hasStringValue()) { - return test.getValue().getStringValue(); - } - } else if (test.hasEvalError()) { - // Note that we only expect a single eval error for all the conformance tests - if (test.getEvalError().getErrorsList().size() == 1) { - return test.getEvalError().getErrorsList().get(0).getMessage(); - } - } - return ""; - } - - // Builds the declarations for a given test - private static void addDecls(CelBuilder builder, SimpleTest test) { - for (Decl decl : test.getTypeEnvList()) { - if (decl.hasIdent()) { - Decl.IdentDecl ident = decl.getIdent(); - com.cel.expr.Type type = ident.getType(); - if (type.hasPrimitive()) { - if (type.getPrimitive() == com.cel.expr.Type.PrimitiveType.STRING) { - builder.addVar(decl.getName(), SimpleType.STRING); - } - } - } - } - } -} diff --git a/src/test/resources/proto/buf.gen.cel.testtypes.yaml b/src/test/resources/proto/buf.gen.cel.testtypes.yaml deleted file mode 100644 index 7617ebcfd..000000000 --- a/src/test/resources/proto/buf.gen.cel.testtypes.yaml +++ /dev/null @@ -1,9 +0,0 @@ -version: v2 -managed: - enabled: true - override: - - file_option: java_package - value: cel.expr.conformance.proto3 -plugins: - - remote: buf.build/protocolbuffers/java:$protocJavaPluginVersion - out: build/generated/test-sources/bufgen-cel-testtypes diff --git a/src/test/resources/proto/buf.gen.cel.yaml b/src/test/resources/proto/buf.gen.cel.yaml deleted file mode 100644 index 1eada8cb8..000000000 --- a/src/test/resources/proto/buf.gen.cel.yaml +++ /dev/null @@ -1,6 +0,0 @@ -version: v2 -managed: - enabled: true -plugins: - - remote: buf.build/protocolbuffers/java:$protocJavaPluginVersion - out: build/generated/test-sources/bufgen-cel diff --git a/src/test/resources/testdata/string_ext_supplemental.textproto b/src/test/resources/testdata/string_ext_supplemental.textproto deleted file mode 100644 index dde7b83b9..000000000 --- a/src/test/resources/testdata/string_ext_supplemental.textproto +++ /dev/null @@ -1,26 +0,0 @@ -# proto-file: ../../../proto/cel/expr/conformance/test/simple.proto -# proto-message: cel.expr.conformance.test.SimpleTestFile - -# Ideally these tests should be in the cel-spec conformance test suite. -# Until they are added, we can use this to test for additional functionality -# listed in the spec. - -name: "string_ext_supplemental" -description: "Supplemental tests for the strings extension library." -section: { - name: "format" - test: { - name: "bytes support for string with invalid utf-8 encoding" - expr: '"%s".format([b"\\xF0abc\\x8C\\xF0xyz"])' - value: { - string_value: '\ufffdabc\ufffdxyz', - } - } - test: { - name: "bytes support for string with only invalid utf-8 sequences" - expr: '"%s".format([b"\\xF0\\x8C\\xF0"])' - value: { - string_value: '\ufffd', - } - } -} diff --git a/src/test/resources/testdata/string_ext_v0.24.0.textproto b/src/test/resources/testdata/string_ext_v0.24.0.textproto deleted file mode 100644 index d2455583f..000000000 --- a/src/test/resources/testdata/string_ext_v0.24.0.textproto +++ /dev/null @@ -1,1417 +0,0 @@ -# proto-file: ../../../proto/cel/expr/conformance/test/simple.proto -# proto-message: cel.expr.conformance.test.SimpleTestFile - -name: "string_ext" -description: "Tests for the strings extension library." -section: { - name: "char_at" - test: { - name: "middle_index" - expr: "'tacocat'.charAt(3)" - value: { - string_value: "o" - } - } - test: { - name: "end_index" - expr: "'tacocat'.charAt(7)" - value: { - string_value: "" - } - } - test: { - name: "multiple" - expr: "'©αT'.charAt(0) == '©' && '©αT'.charAt(1) == 'α' && '©αT'.charAt(2) == 'T'" - } -} -section: { - name: "index_of" - test: { - name: "empty_index" - expr: "'tacocat'.indexOf('')" - value: { - int64_value: 0 - } - } - test: { - name: "string_index" - expr: "'tacocat'.indexOf('ac')" - value: { - int64_value: 1 - } - } - test: { - name: "nomatch" - expr: "'tacocat'.indexOf('none') == -1" - } - test: { - name: "empty_index" - expr: "'tacocat'.indexOf('', 3) == 3" - } - test: { - name: "char_index" - expr: "'tacocat'.indexOf('a', 3) == 5" - } - test: { - name: "string_index" - expr: "'tacocat'.indexOf('at', 3) == 5" - } - test: { - name: "unicode_char" - expr: "'ta©o©αT'.indexOf('©') == 2" - } - test: { - name: "unicode_char_index" - expr: "'ta©o©αT'.indexOf('©', 3) == 4" - } - test: { - name: "unicode_string_index" - expr: "'ta©o©αT'.indexOf('©αT', 3) == 4" - } - test: { - name: "unicode_string_nomatch_index" - expr: "'ta©o©αT'.indexOf('©α', 5) == -1" - } - test: { - name: "char_index" - expr: "'ijk'.indexOf('k') == 2" - } - test: { - name: "string_with_space_fullmatch" - expr: "'hello wello'.indexOf('hello wello') == 0" - } - test: { - name: "string_with_space_index" - expr: "'hello wello'.indexOf('ello', 6) == 7" - } - test: { - name: "string_nomatch_index" - expr: "'hello wello'.indexOf('elbo room!!') == -1" - } -} -section: { - name: "last_index_of" - test: { - name: "empty" - expr: "'tacocat'.lastIndexOf('') == 7" - } - test: { - name: "string" - expr: "'tacocat'.lastIndexOf('at') == 5" - } - test: { - name: "string_nomatch" - expr: "'tacocat'.lastIndexOf('none') == -1" - } - test: { - name: "empty_index" - expr: "'tacocat'.lastIndexOf('', 3) == 3" - } - test: { - name: "char_index" - expr: "'tacocat'.lastIndexOf('a', 3) == 1" - } - test: { - name: "unicode_char" - expr: "'ta©o©αT'.lastIndexOf('©') == 4" - } - test: { - name: "unicode_char_index" - expr: "'ta©o©αT'.lastIndexOf('©', 3) == 2" - } - test: { - name: "unicode_string_index" - expr: "'ta©o©αT'.lastIndexOf('©α', 4) == 4" - } - test: { - name: "string_with_space_string_index" - expr: "'hello wello'.lastIndexOf('ello', 6) == 1" - } - test: { - name: "string_with_space_string_nomatch" - expr: "'hello wello'.lastIndexOf('low') == -1" - } - test: { - name: "string_with_space_string_with_space_nomatch" - expr: "'hello wello'.lastIndexOf('elbo room!!') == -1" - } - test: { - name: "string_with_space_fullmatch" - expr: "'hello wello'.lastIndexOf('hello wello') == 0" - } - test: { - name: "repeated_string" - expr: "'bananananana'.lastIndexOf('nana', 7) == 6" - } -} -section: { - name: "ascii_casing" - test: { - name: "lowerascii" - expr: "'TacoCat'.lowerAscii() == 'tacocat'" - } - test: { - name: "lowerascii_unicode" - expr: "'TacoCÆt'.lowerAscii() == 'tacocÆt'" - } - test: { - name: "lowerascii_unicode_with_space" - expr: "'TacoCÆt Xii'.lowerAscii() == 'tacocÆt xii'" - } - test: { - name: "upperascii" - expr: "'tacoCat'.upperAscii() == 'TACOCAT'" - } - test: { - name: "upperascii_unicode" - expr: "'tacoCαt'.upperAscii() == 'TACOCαT'" - } - test: { - name: "upperascii_unicode_with_space" - expr: "'TacoCÆt Xii'.upperAscii() == 'TACOCÆT XII'" - } -} -section: { - name: "replace" - test: { - name: "no_placeholder" - expr: "'12 days 12 hours'.replace('{0}', '2') == '12 days 12 hours'" - } - test: { - name: "basic" - expr: "'{0} days {0} hours'.replace('{0}', '2') == '2 days 2 hours'" - } - test: { - name: "chained" - expr: "'{0} days {0} hours'.replace('{0}', '2', 1).replace('{0}', '23') == '2 days 23 hours'" - } - test: { - name: "unicode" - expr: "'1 ©αT taco'.replace('αT', 'o©α') == '1 ©o©α taco'" - } -} -section: { - name: "split" - test: { - name: "empty" - expr: "'hello world'.split(' ') == ['hello', 'world']" - } - test: { - name: "zero_limit" - expr: "'hello world events!'.split(' ', 0) == []" - } - test: { - name: "one_limit" - expr: "'hello world events!'.split(' ', 1) == ['hello world events!']" - } - test: { - name: "unicode_negative_limit" - expr: "'o©o©o©o'.split('©', -1) == ['o', 'o', 'o', 'o']" - } -} -section: { - name: "substring" - test: { - name: "start" - expr: "'tacocat'.substring(4) == 'cat'" - } - test: { - name: "start_with_max_length" - expr: "'tacocat'.substring(7) == ''" - } - test: { - name: "start_and_end" - expr: "'tacocat'.substring(0, 4) == 'taco'" - } - test: { - name: "start_and_end_equal_value" - expr: "'tacocat'.substring(4, 4) == ''" - } - test: { - name: "unicode_start_and_end" - expr: "'ta©o©αT'.substring(2, 6) == '©o©α'" - } - test: { - name: "unicode_start_and_end_equal_value" - expr: "'ta©o©αT'.substring(7, 7) == ''" - } -} -section: { - name: "trim" - test: { - name: "blank_spaces_escaped_chars" - expr: "' \\f\\n\\r\\t\\vtext '.trim() == 'text'" - } - test: { - name: "unicode_space_chars_1" - expr: "'\\u0085\\u00a0\\u1680text'.trim() == 'text'" - } - test: { - name: "unicode_space_chars_2" - expr: "'text\\u2000\\u2001\\u2002\\u2003\\u2004\\u2004\\u2006\\u2007\\u2008\\u2009'.trim() == 'text'" - } - test: { - name: "unicode_space_chars_3" - expr: "'\\u200atext\\u2028\\u2029\\u202F\\u205F\\u3000'.trim() == 'text'" - } - test: { - name: "unicode_no_trim" - expr: "'\\u180etext\\u200b\\u200c\\u200d\\u2060\\ufeff'.trim() == '\\u180etext\\u200b\\u200c\\u200d\\u2060\\ufeff'" - } -} -section: { - name: "join" - test: { - name: "empty_separator" - expr: "['x', 'y'].join() == 'xy'" - } - test: { - name: "dash_separator" - expr: "['x', 'y'].join('-') == 'x-y'" - } - test: { - name: "empty_string_empty_separator" - expr: "[].join() == ''" - } - test: { - name: "empty_string_dash_separator" - expr: "[].join('-') == ''" - } -} -section: { - name: "quote" - test: { - name: "multiline" - expr: "strings.quote(\"first\\nsecond\") == \"\\\"first\\\\nsecond\\\"\"" - } - test: { - name: "escaped" - expr: "strings.quote(\"bell\\a\") == \"\\\"bell\\\\a\\\"\"" - } - test: { - name: "backspace" - expr: "strings.quote(\"\\bbackspace\") == \"\\\"\\\\bbackspace\\\"\"" - } - test: { - name: "form_feed" - expr: "strings.quote(\"\\fform feed\") == \"\\\"\\\\fform feed\\\"\"" - } - test: { - name: "carriage_return" - expr: "strings.quote(\"carriage \\r return\") == \"\\\"carriage \\\\r return\\\"\"" - } - test: { - name: "horizontal_tab" - expr: "strings.quote(\"horizontal tab\\t\") == \"\\\"horizontal tab\\\\t\\\"\"" - } - test: { - name: "vertical_tab" - expr: "strings.quote(\"vertical \\v tab\") == \"\\\"vertical \\\\v tab\\\"\"" - } - test: { - name: "double_slash" - expr: "strings.quote(\"double \\\\\\\\ slash\") == \"\\\"double \\\\\\\\\\\\\\\\ slash\\\"\"" - } - test: { - name: "two_escape_sequences" - expr: "strings.quote(\"two escape sequences \\\\a\\\\n\") == \"\\\"two escape sequences \\\\\\\\a\\\\\\\\n\\\"\"" - } - test: { - name: "verbatim" - expr: "strings.quote(\"verbatim\") == \"\\\"verbatim\\\"\"" - } - test: { - name: "ends_with" - expr: "strings.quote(\"ends with \\\\\") == \"\\\"ends with \\\\\\\\\\\"\"" - } - test: { - name: "starts_with" - expr: "strings.quote(\"\\\\ starts with\") == \"\\\"\\\\\\\\ starts with\\\"\"" - } - test: { - name: "printable_unicode" - expr: "strings.quote(\"printable unicode😀\") == \"\\\"printable unicode😀\\\"\"" - } - test: { - name: "mid_string_quote" - expr: "strings.quote(\"mid string \\\" quote\") == \"\\\"mid string \\\\\\\" quote\\\"\"" - } - test: { - name: "single_quote_with_double_quote" - expr: "strings.quote('single-quote with \"double quote\"') == \"\\\"single-quote with \\\\\\\"double quote\\\\\\\"\\\"\"" - } - test: { - name: "size_unicode_char" - expr: "strings.quote(\"size('ÿ')\") == \"\\\"size('ÿ')\\\"\"" - } - test: { - name: "size_unicode_string" - expr: "strings.quote(\"size('πέντε')\") == \"\\\"size('πέντε')\\\"\"" - } - test: { - name: "unicode" - expr: "strings.quote(\"завтра\") == \"\\\"завтра\\\"\"" - } - test: { - name: "unicode_code_points" - expr: "strings.quote(\"\\U0001F431\\U0001F600\\U0001F61B\")" - value: { - string_value: "\"🐱😀😛\"" - } - } - test: { - name: "unicode_2" - expr: "strings.quote(\"ta©o©αT\") == \"\\\"ta©o©αT\\\"\"" - } - test: { - name: "empty_quote" - expr: "strings.quote(\"\")" - value: { - string_value: "\"\"" - } - } -} -section: { - name: "format" - test: { - name: "no-op" - expr: '"no substitution".format([])' - value: { - string_value: 'no substitution', - } - } - test: { - name: "mid-string substitution" - expr: '"str is %s and some more".format(["filler"])' - value: { - string_value: 'str is filler and some more', - } - } - test: { - name: "percent escaping" - expr: '"%% and also %%".format([])' - value: { - string_value: '% and also %', - } - } - test: { - name: "substitution inside escaped percent signs" - expr: '"%%%s%%".format(["text"])' - value: { - string_value: '%text%', - } - } - test: { - name: "substitution with one escaped percent sign on the right" - expr: '"%s%%".format(["percent on the right"])' - value: { - string_value: 'percent on the right%', - } - } - test: { - name: "substitution with one escaped percent sign on the left" - expr: '"%%%s".format(["percent on the left"])' - value: { - string_value: '%percent on the left', - } - } - test: { - name: "multiple substitutions" - expr: '"%d %d %d, %s %s %s, %d %d %d, %s %s %s".format([1, 2, 3, "A", "B", "C", 4, 5, 6, "D", "E", "F"])' - value: { - string_value: '1 2 3, A B C, 4 5 6, D E F', - } - } - test: { - name: "percent sign escape sequence support" - expr: '"%%escaped %s%%".format(["percent"])' - value: { - string_value: '%escaped percent%', - } - } - test: { - name: "fixed point formatting clause" - expr: '"%.3f".format([1.2345])' - value: { - string_value: '1.234', - } - } - test: { - name: "binary formatting clause" - expr: '"this is 5 in binary: %b".format([5])' - value: { - string_value: 'this is 5 in binary: 101', - } - } - test: { - name: "uint support for binary formatting" - expr: '"unsigned 64 in binary: %b".format([uint(64)])' - value: { - string_value: 'unsigned 64 in binary: 1000000', - } - } - test: { - name: "bool support for binary formatting" - expr: '"bit set from bool: %b".format([true])' - value: { - string_value: 'bit set from bool: 1', - } - } - test: { - name: "octal formatting clause" - expr: '"%o".format([11])' - value: { - string_value: '13', - } - } - test: { - name: "uint support for octal formatting clause" - expr: '"this is an unsigned octal: %o".format([uint(65535)])' - value: { - string_value: 'this is an unsigned octal: 177777', - } - } - test: { - name: "lowercase hexadecimal formatting clause" - expr: '"%x is 20 in hexadecimal".format([30])' - value: { - string_value: '1e is 20 in hexadecimal', - } - } - test: { - name: "uppercase hexadecimal formatting clause" - expr: '"%X is 20 in hexadecimal".format([30])' - value: { - string_value: '1E is 20 in hexadecimal', - } - } - test: { - name: "unsigned support for hexadecimal formatting clause" - expr: '"%X is 6000 in hexadecimal".format([uint(6000)])' - value: { - string_value: '1770 is 6000 in hexadecimal', - } - } - test: { - name: "string support with hexadecimal formatting clause" - expr: '"%x".format(["Hello world!"])' - value: { - string_value: '48656c6c6f20776f726c6421', - } - } - test: { - name: "string support with uppercase hexadecimal formatting clause" - expr: '"%X".format(["Hello world!"])' - value: { - string_value: '48656C6C6F20776F726C6421', - } - } - test: { - name: "byte support with hexadecimal formatting clause" - expr: '"%x".format([b"byte string"])' - value: { - string_value: '6279746520737472696e67', - } - } - test: { - name: "byte support with uppercase hexadecimal formatting clause" - expr: '"%X".format([b"byte string"])' - value: { - string_value: '6279746520737472696E67', - } - } - test: { - name: "scientific notation formatting clause" - expr: '"%.6e".format([1052.032911275])' - value: { - string_value: '1.052033e+03', - } - } - test: { - name: "default precision for fixed-point clause" - expr: '"%f".format([2.71828])' - value: { - string_value: '2.718280', - } - } - test: { - name: "default precision for scientific notation" - expr: '"%e".format([2.71828])' - value: { - string_value: '2.718280e+00', - } - } - test: { - name: "NaN support for scientific notation" - expr: '"%e".format([double("NaN")])' - value: { - string_value: 'NaN', - } - } - test: { - name: "positive infinity support for scientific notation" - expr: '"%e".format([double("Infinity")])' - value: { - string_value: 'Infinity', - } - } - test: { - name: "negative infinity support for scientific notation" - expr: '"%e".format([double("-Infinity")])' - value: { - string_value: '-Infinity', - } - } - test: { - name: "NaN support for decimal" - expr: '"%d".format([double("NaN")])' - value: { - string_value: 'NaN', - } - } - test: { - name: "positive infinity support for decimal" - expr: '"%d".format([double("Infinity")])' - value: { - string_value: 'Infinity', - } - } - test: { - name: "negative infinity support for decimal" - expr: '"%d".format([double("-Infinity")])' - value: { - string_value: '-Infinity', - } - } - test: { - name: "NaN support for fixed-point" - expr: '"%f".format([double("NaN")])' - value: { - string_value: 'NaN', - } - } - test: { - name: "positive infinity support for fixed-point" - expr: '"%f".format([double("Infinity")])' - value: { - string_value: 'Infinity', - } - } - test: { - name: "negative infinity support for fixed-point" - expr: '"%f".format([double("-Infinity")])' - value: { - string_value: '-Infinity', - } - } - test: { - name: "uint support for decimal clause" - expr: '"%d".format([uint(64)])' - value: { - string_value: '64', - } - } - test: { - name: "null support for string" - expr: '"%s".format([null])' - value: { - string_value: 'null', - } - } - test: { - name: "int support for string" - expr: '"%s".format([999999999999])' - value: { - string_value: '999999999999', - } - } - test: { - name: "bytes support for string" - expr: '"%s".format([b"xyz"])' - value: { - string_value: 'xyz', - } - } - test: { - name: "type() support for string" - expr: '"%s".format([type("test string")])' - value: { - string_value: 'string', - } - } - test: { - name: "timestamp support for string" - expr: '"%s".format([timestamp("2023-02-03T23:31:20+00:00")])' - value: { - string_value: '2023-02-03T23:31:20Z', - } - } - test: { - name: "duration support for string" - expr: '"%s".format([duration("1h45m47s")])' - value: { - string_value: '6347s', - } - } - test: { - name: "list support for string" - expr: '"%s".format([["abc", 3.14, null, [9, 8, 7, 6], timestamp("2023-02-03T23:31:20Z")]])' - value: { - string_value: '[abc, 3.14, null, [9, 8, 7, 6], 2023-02-03T23:31:20Z]', - } - } - test: { - name: "map support for string" - expr: '"%s".format([{"key1": b"xyz", "key5": null, "key2": duration("2h"), "key4": true, "key3": 2.71828}])' - value: { - string_value: '{key1: xyz, key2: 7200s, key3: 2.71828, key4: true, key5: null}', - } - } - test: { - name: "map support (all key types)" - expr: '"%s".format([{1: "value1", uint(2): "value2", true: double("NaN")}])' - value: { - string_value: '{1: value1, 2: value2, true: NaN}', - } - } - test: { - name: "boolean support for %s" - expr: '"%s, %s".format([true, false])' - value: { - string_value: 'true, false', - } - } - test: { - name: "dyntype support for string formatting clause" - expr: '"%s".format([dyn("a string")])' - value: { - string_value: 'a string', - } - } - test: { - name: "dyntype support for numbers with string formatting clause" - expr: '"%s, %s".format([dyn(32), dyn(56.8)])' - value: { - string_value: '32, 56.8', - } - } - test: { - name: "dyntype support for integer formatting clause" - expr: '"%d".format([dyn(128)])' - value: { - string_value: '128', - } - } - test: { - name: "dyntype support for integer formatting clause (unsigned)" - expr: '"%d".format([dyn(256u)])' - value: { - string_value: '256', - } - } - test: { - name: "dyntype support for hex formatting clause" - expr: '"%x".format([dyn(22)])' - value: { - string_value: '16', - } - } - test: { - name: "dyntype support for hex formatting clause (uppercase)" - expr: '"%X".format([dyn(26)])' - value: { - string_value: '1A', - } - } - test: { - name: "dyntype support for unsigned hex formatting clause" - expr: '"%x".format([dyn(500u)])' - value: { - string_value: '1f4', - } - } - test: { - name: "dyntype support for fixed-point formatting clause" - expr: '"%.3f".format([dyn(4.5)])' - value: { - string_value: '4.500', - } - } - test: { - name: "dyntype support for scientific notation" - expr: '"%e".format([dyn(2.71828)])' - value: { - string_value: '2.718280e+00', - } - } - test: { - name: "dyntype NaN/infinity support" - expr: '"%s".format([[double("NaN"), double("Infinity"), double("-Infinity")]])' - value: { - string_value: '[NaN, Infinity, -Infinity]', - } - } - test: { - name: "dyntype support for timestamp" - expr: '"%s".format([dyn(timestamp("2009-11-10T23:00:00Z"))])' - value: { - string_value: '2009-11-10T23:00:00Z', - } - } - test: { - name: "dyntype support for duration" - expr: '"%s".format([dyn(duration("8747s"))])' - value: { - string_value: '8747s', - } - } - test: { - name: "dyntype support for lists" - expr: '"%s".format([dyn([6, 4.2, "a string"])])' - value: { - string_value: '[6, 4.2, a string]', - } - } - test: { - name: "dyntype support for maps" - expr: '"%s".format([{"strKey":"x", 6:duration("422s"), true:42}])' - value: { - string_value: '{6: 422s, strKey: x, true: 42}', - } - } - test: { - name: "string substitution in a string variable" - expr: 'str_var.format(["filler"])' - type_env: { - name: "str_var", - ident: { type: { primitive: STRING } } - } - bindings: { - key: "str_var" - value: { value: { string_value: "%s" } } - } - value: { - string_value: 'filler', - } - } - test: { - name: "multiple substitutions in a string variable" - expr: 'str_var.format([1, 2, 3, "A", "B", "C", 4, 5, 6, "D", "E", "F"])' - type_env: { - name: "str_var", - ident: { type: { primitive: STRING } } - } - bindings: { - key: "str_var" - value: { value: { string_value: "%d %d %d, %s %s %s, %d %d %d, %s %s %s" } } - } - value: { - string_value: '1 2 3, A B C, 4 5 6, D E F', - } - } - test: { - name: "substitution inside escaped percent signs in a string variable" - expr: 'str_var.format(["text"])' - type_env: { - name: "str_var", - ident: { type: { primitive: STRING } } - } - bindings: { - key: "str_var" - value: { value: { string_value: "%%%s%%" } } - } - value: { - string_value: '%text%', - } - } - test: { - name: "fixed point formatting clause in a string variable" - expr: 'str_var.format([1.2345])' - type_env: { - name: "str_var", - ident: { type: { primitive: STRING } } - } - bindings: { - key: "str_var" - value: { value: { string_value: "%.3f" } } - } - value: { - string_value: '1.234', - } - } - test: { - name: "binary formatting clause in a string variable" - expr: 'str_var.format([5])' - type_env: { - name: "str_var", - ident: { type: { primitive: STRING } } - } - bindings: { - key: "str_var" - value: { value: { string_value: "%b" } } - } - value: { - string_value: '101', - } - } - test: { - name: "scientific notation formatting clause in a string variable" - expr: 'str_var.format([1052.032911275])' - type_env: { - name: "str_var", - ident: { type: { primitive: STRING } } - } - bindings: { - key: "str_var" - value: { value: { string_value: "%.6e" } } - } - value: { - string_value: '1.052033e+03', - } - } - test: { - name: "default precision for fixed-point clause in a string variable" - expr: 'str_var.format([2.71828])' - type_env: { - name: "str_var", - ident: { type: { primitive: STRING } } - } - bindings: { - key: "str_var" - value: { value: { string_value: "%f" } } - } - value: { - string_value: '2.718280', - } - } -} -section: { - name: "format_errors" - test: { - name: "unrecognized formatting clause" - expr: '"%a".format([1])' - disable_check: true - eval_error: { - errors: { - message: 'could not parse formatting clause: unrecognized formatting clause "a"' - } - } - } - test: { - name: "out of bounds arg index" - expr: '"%d %d %d".format([0, 1])' - disable_check: true - eval_error: { - errors: { - message: 'index 2 out of range' - } - } - } - test: { - name: "string substitution is not allowed with binary clause" - expr: '"string is %b".format(["abc"])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: only integers and bools can be formatted as binary, was given string' - } - } - } - test: { - name: "duration substitution not allowed with decimal clause" - expr: '"%d".format([duration("30m2s")])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: decimal clause can only be used on integers, was given google.protobuf.Duration' - } - } - } - test: { - name: "string substitution not allowed with octal clause" - expr: '"octal: %o".format(["a string"])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: octal clause can only be used on integers, was given string' - } - } - } - test: { - name: "double substitution not allowed with hex clause" - expr: '"double is %x".format([0.5])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: only integers, byte buffers, and strings can be formatted as hex, was given double' - } - } - } - test: { - name: "uppercase not allowed for scientific clause" - expr: '"double is %E".format([0.5])' - disable_check: true - eval_error: { - errors: { - message: 'could not parse formatting clause: unrecognized formatting clause "E"' - } - } - } - test: { - name: "object not allowed" - expr: '"object is %s".format([cel.expr.conformance.proto3.TestAllTypes{}])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps, was given cel.expr.conformance.proto3.TestAllTypes' - } - } - } - test: { - name: "object inside list" - expr: '"%s".format([[1, 2, cel.expr.conformance.proto3.TestAllTypes{}]])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps, was given cel.expr.conformance.proto3.TestAllTypes' - } - } - } - test: { - name: "object inside map" - expr: '"%s".format([{1: "a", 2: cel.expr.conformance.proto3.TestAllTypes{}}])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: string clause can only be used on strings, bools, bytes, ints, doubles, maps, lists, types, durations, and timestamps, was given cel.expr.conformance.proto3.TestAllTypes' - } - } - } - test: { - name: "null not allowed for %d" - expr: '"null: %d".format([null])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: decimal clause can only be used on integers, was given null_type' - } - } - } - test: { - name: "null not allowed for %e" - expr: '"null: %e".format([null])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: scientific clause can only be used on doubles, was given null_type' - } - } - } - test: { - name: "null not allowed for %f" - expr: '"null: %f".format([null])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: fixed-point clause can only be used on doubles, was given null_type' - } - } - } - test: { - name: "null not allowed for %x" - expr: '"null: %x".format([null])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: only integers, byte buffers, and strings can be formatted as hex, was given null_type' - } - } - } - test: { - name: "null not allowed for %X" - expr: '"null: %X".format([null])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: only integers, byte buffers, and strings can be formatted as hex, was given null_type' - } - } - } - test: { - name: "null not allowed for %b" - expr: '"null: %b".format([null])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: only integers and bools can be formatted as binary, was given null_type' - } - } - } - test: { - name: "null not allowed for %o" - expr: '"null: %o".format([null])' - disable_check: true - eval_error: { - errors: { - message: 'error during formatting: octal clause can only be used on integers, was given null_type' - } - } - } -} -section: { - name: "value_errors" - test: { - name: "charat_out_of_range" - expr: "'tacocat'.charAt(30) == ''" - eval_error: { - errors: { - message: "index out of range: 30" - } - } - } - test: { - name: "indexof_out_of_range" - expr: "'tacocat'.indexOf('a', 30) == -1" - eval_error: { - errors: { - message: "index out of range: 30" - } - } - } - test: { - name: "lastindexof_negative_index" - expr: "'tacocat'.lastIndexOf('a', -1) == -1" - eval_error: { - errors: { - message: "index out of range: -1" - } - } - } - test: { - name: "lastindexof_out_of_range" - expr: "'tacocat'.lastIndexOf('a', 30) == -1" - eval_error: { - errors: { - message: "index out of range: 30" - } - } - } - test: { - name: "substring_out_of_range" - expr: "'tacocat'.substring(40) == 'cat'" - eval_error: { - errors: { - message: "index out of range: 40" - } - } - } - test: { - name: "substring_negative_index" - expr: "'tacocat'.substring(-1) == 'cat'" - eval_error: { - errors: { - message: "index out of range: -1" - } - } - } - test: { - name: "substring_end_index_out_of_range" - expr: "'tacocat'.substring(1, 50) == 'cat'" - eval_error: { - errors: { - message: "index out of range: 50" - } - } - } - test: { - name: "substring_begin_index_out_of_range" - expr: "'tacocat'.substring(49, 50) == 'cat'" - eval_error: { - errors: { - message: "index out of range: 49" - } - } - } - test: { - name: "substring_end_index_greater_than_begin_index" - expr: "'tacocat'.substring(4, 3) == ''" - eval_error: { - errors: { - message: "invalid substring range. start: 4, end: 3" - } - } - } -} -section: { - name: "type_errors" - test: { - name: "charat_invalid_type" - expr: "42.charAt(2) == ''" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "charat_invalid_argument" - expr: "'hello'.charAt(true) == ''" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "indexof_unary_invalid_type" - expr: "24.indexOf('2') == 0" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "indexof_unary_invalid_argument" - expr: "'hello'.indexOf(true) == 1" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "indexof_binary_invalid_argument" - expr: "42.indexOf('4', 0) == 0" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "indexof_binary_invalid_argument_2" - expr: "'42'.indexOf(4, 0) == 0" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "indexof_binary_both_invalid_arguments" - expr: "'42'.indexOf('4', '0') == 0" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "indexof_ternary_invalid_arguments" - expr: "'42'.indexOf('4', 0, 1) == 0" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "split_invalid_type" - expr: "42.split('2') == ['4']" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "replace_invalid_type" - expr: "42.replace(2, 1) == '41'" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "replace_binary_invalid_argument" - expr: "'42'.replace(2, 1) == '41'" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "replace_binary_invalid_argument_2" - expr: "'42'.replace('2', 1) == '41'" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "replace_ternary_invalid_argument" - expr: "42.replace('2', '1', 1) == '41'" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "replace_ternary_invalid_argument_2" - expr: "'42'.replace(2, '1', 1) == '41'" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "replace_ternary_invalid_argument_3" - expr: "'42'.replace('2', 1, 1) == '41'" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "replace_ternary_invalid_argument_4" - expr: "'42'.replace('2', '1', '1') == '41'" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "replace_quaternary_invalid_argument" - expr: "'42'.replace('2', '1', 1, false) == '41'" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "split_invalid_type_empty_arg" - expr: "42.split('') == ['4', '2']" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "split_invalid_argument" - expr: "'42'.split(2) == ['4']" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "split_binary_invalid_type" - expr: "42.split('2', '1') == ['4']" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "split_binary_invalid_argument" - expr: "'42'.split(2, 1) == ['4']" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "split_binary_invalid_argument_2" - expr: "'42'.split('2', '1') == ['4']" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "split_ternary_invalid_argument" - expr: "'42'.split('2', 1, 1) == ['4']" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "substring_ternary_invalid_argument" - expr: "'hello'.substring(1, 2, 3) == ''" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "substring_binary_invalid_type" - expr: "30.substring(true, 3) == ''" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "substring_binary_invalid_argument" - expr: "'tacocat'.substring(true, 3) == ''" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } - test: { - name: "substring_binary_invalid_argument_2" - expr: "'tacocat'.substring(0, false) == ''" - disable_check: true - eval_error: { - errors: { - message: "no such overload" - } - } - } -}