Skip to content

Commit

Permalink
protobuf: Add unit test for empty map value deserialization
Browse files Browse the repository at this point in the history
Motivation:
It is valid to not encode an empty map value and token, and we
don't have a unit test to verify this behavior.
  • Loading branch information
Scottmitch committed Sep 18, 2023
1 parent c9b1fc5 commit 397d5cb
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,13 @@
package io.servicetalk.data.protobuf;

import io.servicetalk.buffer.api.Buffer;
import io.servicetalk.buffer.api.BufferAllocator;
import io.servicetalk.data.protobuf.test.TestProtos.DummyMessage;
import io.servicetalk.data.protobuf.test.TestProtos.MapMessage;
import io.servicetalk.serializer.api.SerializerDeserializer;
import io.servicetalk.serializer.api.StreamingSerializerDeserializer;

import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Parser;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
Expand Down Expand Up @@ -69,6 +72,20 @@ void serializeDeserializeClass() {
serializeDeserialize(testMessage, PROTOBUF.serializerDeserializer(DummyMessage.class));
}

@Test
void serializeEmptyMap() throws InvalidProtocolBufferException {
// These bytes were serialized from scala protobuf and don't include the trailing empty map value.
final byte[] emptyMessageMapEmptyValueBytes = {0xa, 0x5, 0xa, 0x3, 0x66, 0x6f, 0x6f};
final BufferAllocator allocator = DEFAULT_ALLOCATOR;
final Buffer buffer = allocator.wrap(emptyMessageMapEmptyValueBytes);
final MapMessage mapMessage = MapMessage.parseFrom(emptyMessageMapEmptyValueBytes);
SerializerDeserializer<MapMessage> serializer = PROTOBUF.serializerDeserializer(MapMessage.class);
assertThat(serializer.deserialize(buffer, allocator), equalTo(mapMessage));
// Serializing in java currently writes "0x12, 0x0" for "map value tag, empty string" so we can't compare number
// of bytes directly, but we can ensure it deserializes back to an equal object.
assertThat(serializer.deserialize(serializer.serialize(mapMessage, allocator), allocator), equalTo(mapMessage));
}

private static void serializeDeserialize(final DummyMessage testMessage,
final SerializerDeserializer<DummyMessage> serializer) {
final byte[] testMessageBytes = testMessage.toByteArray();
Expand Down
4 changes: 4 additions & 0 deletions servicetalk-data-protobuf/src/test/proto/test_message.proto
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,7 @@ option java_outer_classname = "TestProtos";
message DummyMessage {
string message = 1;
}

message MapMessage {
map<string, string> attributes = 1;
}

0 comments on commit 397d5cb

Please sign in to comment.