Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,31 @@ public void optionalFieldSelection_onProtoMessage_returnsOptionalValue() throws
assertThat(result).hasValue(5L);
}

@Test
public void optionalFieldSelection_onProtoMessage_listValue() throws Exception {
Cel cel = newCelBuilder().build();
CelAbstractSyntaxTree ast =
cel.compile("optional.of(TestAllTypes{repeated_string: ['foo']}).?repeated_string.value()")
.getAst();

List<String> result = (List<String>) cel.createProgram(ast).eval();

assertThat(result).containsExactly("foo");
}

@Test
public void optionalFieldSelection_onProtoMessage_indexValue() throws Exception {
Cel cel = newCelBuilder().build();
CelAbstractSyntaxTree ast =
cel.compile(
"optional.of(TestAllTypes{repeated_string: ['foo']}).?repeated_string[0].value()")
.getAst();

String result = (String) cel.createProgram(ast).eval();

assertThat(result).isEqualTo("foo");
}

@Test
public void optionalFieldSelection_onProtoMessage_chainedSuccess() throws Exception {
Cel cel =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -140,28 +140,32 @@ public Object createMessage(String messageName, Map<String, Object> values) {
@Nullable
@SuppressWarnings("unchecked")
public Object selectField(Object message, String fieldName) {
boolean isOptionalMessage = false;
if (message instanceof Optional) {
Optional<Map<?, ?>> optionalMap = (Optional<Map<?, ?>>) message;
if (!optionalMap.isPresent()) {
return Optional.empty();
}

Map<?, ?> unwrappedMap = optionalMap.get();
if (!unwrappedMap.containsKey(fieldName)) {
isOptionalMessage = true;
Optional<Object> optionalMessage = (Optional<Object>) message;
if (!optionalMessage.isPresent()) {
return Optional.empty();
}

return Optional.of(unwrappedMap.get(fieldName));
message = optionalMessage.get();
}

if (message instanceof Map) {
Map<?, ?> map = (Map<?, ?>) message;
if (map.containsKey(fieldName)) {
return map.get(fieldName);
Object mapValue = map.get(fieldName);
return isOptionalMessage ? Optional.of(mapValue) : mapValue;
}

if (isOptionalMessage) {
return Optional.empty();
} else {
throw new CelRuntimeException(
new IllegalArgumentException(
String.format("key '%s' is not present in map.", fieldName)),
CelErrorCode.ATTRIBUTE_NOT_FOUND);
}
throw new CelRuntimeException(
new IllegalArgumentException(String.format("key '%s' is not present in map.", fieldName)),
CelErrorCode.ATTRIBUTE_NOT_FOUND);
}

MessageOrBuilder typedMessage = assertFullProtoMessage(message);
Expand Down