diff --git a/settings.gradle.kts b/settings.gradle.kts index a7c22d980d..339d9d4307 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -70,6 +70,7 @@ include(":wire-tests:jvm-annotations-interop") include(":wire-tests:jvm-java-kotlin") include(":wire-tests:jvm-json-java") include(":wire-tests:jvm-json-kotlin") +include(":wire-tests:jvm-json-oneof") include(":wire-tests:jvm-kotlin-interop") include(":wire-tests:jvm-kotlin-proto-reader-32") include(":wire-tests:multiplatform") diff --git a/wire-gson-support/src/main/java/com/squareup/wire/MessageTypeAdapter.kt b/wire-gson-support/src/main/java/com/squareup/wire/MessageTypeAdapter.kt index a57dedd0ed..3e1912d83b 100644 --- a/wire-gson-support/src/main/java/com/squareup/wire/MessageTypeAdapter.kt +++ b/wire-gson-support/src/main/java/com/squareup/wire/MessageTypeAdapter.kt @@ -82,7 +82,7 @@ internal class MessageTypeAdapter, B : Message.Builder>( ) } - jsonField.fieldBinding.set(builder, value) + jsonField.fieldBinding.setFromJson(builder, value) } input.endObject() return builder.build() diff --git a/wire-moshi-adapter/src/main/java/com/squareup/wire/MessageJsonAdapter.kt b/wire-moshi-adapter/src/main/java/com/squareup/wire/MessageJsonAdapter.kt index c64d5784d2..38630db1e5 100644 --- a/wire-moshi-adapter/src/main/java/com/squareup/wire/MessageJsonAdapter.kt +++ b/wire-moshi-adapter/src/main/java/com/squareup/wire/MessageJsonAdapter.kt @@ -92,7 +92,7 @@ internal class MessageJsonAdapter, B : Message.Builder>( ) } - fieldBinding.set(builder, value) + fieldBinding.setFromJson(builder, value) } input.endObject() return builder.build() diff --git a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/FieldOrOneOfBinding.kt b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/FieldOrOneOfBinding.kt index 5f8a0e812a..d743870ff0 100644 --- a/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/FieldOrOneOfBinding.kt +++ b/wire-runtime/src/commonMain/kotlin/com/squareup/wire/internal/FieldOrOneOfBinding.kt @@ -85,6 +85,16 @@ abstract class FieldOrOneOfBinding { abstract fun set(builder: B, value: Any?) + /** + * Assigns [value], read from JSON, to the builder. + * + * Binary decoding keeps the last member that the input sets in a oneof, so [set] does too. For + * oneofs of generated Java and of generated Kotlin with flat members, JSON decoding instead + * fails when the input sets two members. Wire 7 did this, and protobuf-java does it too. + * Other bindings keep the last member, as [set] does. + */ + open fun setFromJson(builder: B, value: Any?) = set(builder, value) + abstract operator fun get(message: M): Any? abstract fun getFromBuilder(builder: B): Any? diff --git a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/FieldBinding.kt b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/FieldBinding.kt index 4e30c130f9..0ed0e339dd 100644 --- a/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/FieldBinding.kt +++ b/wire-runtime/src/jvmMain/kotlin/com/squareup/wire/internal/FieldBinding.kt @@ -44,7 +44,8 @@ class FieldBinding, B : Message.Builder> internal constr private val keyAdapterString = wireField.keyAdapter private val adapterString = wireField.adapter override val redacted: Boolean = wireField.redacted - private val builderSetter = getBuilderSetter(builderType, wireField) + private val builderSetter = getBuilderSetter(builderType, wireField, lastOneOfMemberWins = true) + private val jsonBuilderSetter = getBuilderSetter(builderType, wireField, lastOneOfMemberWins = false) private val builderGetter = getBuilderGetter(builderType, wireField) private val instanceGetter = getInstanceGetter(messageType) @@ -63,7 +64,21 @@ class FieldBinding, B : Message.Builder> internal constr override val isMessage: Boolean get() = Message::class.java.isAssignableFrom(singleAdapter.type?.javaObjectType!!) - private fun getBuilderSetter(builderType: Class<*>, wireField: WireField): (B, Any?) -> Unit = when { + /** + * Returns a function that assigns a value to the builder. + * + * When [lastOneOfMemberWins] is true, setting a oneof member clears the other members. Binary + * decoding needs this, because the protobuf rule is that the last member on the wire wins. + * + * When it is false, a oneof member that generated Java or Kotlin code declares as a plain field + * is assigned without clearing the other members. If the input sets two members, `build()` then + * throws, as it did in Wire 7. JSON decoding uses this. + */ + private fun getBuilderSetter( + builderType: Class<*>, + wireField: WireField, + lastOneOfMemberWins: Boolean, + ): (B, Any?) -> Unit = when { builderType.isAssignableFrom(KotlinConstructorBuilder::class.java) -> { builder, value -> (builder as KotlinConstructorBuilder<*, *>).set(wireField, value) } @@ -81,7 +96,11 @@ class FieldBinding, B : Message.Builder> internal constr else -> { // Generated Java does not emit `ONE_OF` labels. The builder method of a oneof member clears // the other members, so the last member on the wire wins. - val oneOfMethod = if (wireField.oneofName.isNotEmpty()) builderOneOfMethod(builderType) else null + val oneOfMethod = if (lastOneOfMemberWins && wireField.oneofName.isNotEmpty()) { + builderOneOfMethod(builderType) + } else { + null + } if (oneOfMethod != null) { { builder, value -> oneOfMethod.invoke(builder, value) @@ -179,6 +198,8 @@ class FieldBinding, B : Message.Builder> internal constr /** Assign a single value for required/optional fields, or a list for repeated/packed fields. */ override fun set(builder: B, value: Any?) = builderSetter(builder, value) + override fun setFromJson(builder: B, value: Any?) = jsonBuilderSetter(builder, value) + override operator fun get(message: M): Any? = instanceGetter(message) override fun getFromBuilder(builder: B): Any? = builderGetter(builder) diff --git a/wire-tests/jvm-json-oneof/build.gradle.kts b/wire-tests/jvm-json-oneof/build.gradle.kts new file mode 100644 index 0000000000..d9737d425a --- /dev/null +++ b/wire-tests/jvm-json-oneof/build.gradle.kts @@ -0,0 +1,56 @@ +plugins { + kotlin("jvm") + id("com.squareup.wire") +} + +dependencies { + implementation(libs.assertk) + implementation(libs.kotlin.test.junit) + implementation(projects.wireGsonSupport) + implementation(projects.wireMoshiAdapter) +} + +wire { + java { + includes = listOf("squareup.wire.json.oneof.java.*") + } + + // Flat oneofs. Without `javaInterop` or `buildersOnly`, Wire uses a reflective builder. + kotlin { + includes = listOf("squareup.wire.json.oneof.kotlin.*") + } + kotlin { + includes = listOf("squareup.wire.json.oneof.kotlin_interop.*") + javaInterop = true + } + kotlin { + includes = listOf("squareup.wire.json.oneof.kotlin_builders.*") + buildersOnly = true + } + kotlin { + includes = listOf("squareup.wire.json.oneof.kotlin_interop_builders.*") + javaInterop = true + buildersOnly = true + } + + kotlin { + includes = listOf("squareup.wire.json.oneof.boxed.*") + oneofMode = "boxed" + javaInterop = true + } + kotlin { + includes = listOf("squareup.wire.json.oneof.boxed_builders.*") + oneofMode = "boxed" + buildersOnly = true + } + kotlin { + includes = listOf("squareup.wire.json.oneof.sealed.*") + oneofMode = "sealed_class" + javaInterop = true + } + kotlin { + includes = listOf("squareup.wire.json.oneof.sealed_builders.*") + oneofMode = "sealed_class" + buildersOnly = true + } +} diff --git a/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/boxed.proto b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/boxed.proto new file mode 100644 index 0000000000..42c29529ae --- /dev/null +++ b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/boxed.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; + +package squareup.wire.json.oneof.boxed; + +option java_package = "squareup.wire.json.oneof.boxed"; + +message Nested { + string name = 1; +} + +message Choice { + oneof choice { + string text = 1; + int32 number = 2; + Nested nested = 3; + } + string other = 4; +} diff --git a/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/boxed_builders.proto b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/boxed_builders.proto new file mode 100644 index 0000000000..a0aebe2114 --- /dev/null +++ b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/boxed_builders.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; + +package squareup.wire.json.oneof.boxed_builders; + +option java_package = "squareup.wire.json.oneof.boxed_builders"; + +message Nested { + string name = 1; +} + +message Choice { + oneof choice { + string text = 1; + int32 number = 2; + Nested nested = 3; + } + string other = 4; +} diff --git a/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/java.proto b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/java.proto new file mode 100644 index 0000000000..7dbbdd4d0a --- /dev/null +++ b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/java.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; + +package squareup.wire.json.oneof.java; + +option java_package = "squareup.wire.json.oneof.java"; + +message Nested { + string name = 1; +} + +message Choice { + oneof choice { + string text = 1; + int32 number = 2; + Nested nested = 3; + } + string other = 4; +} diff --git a/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin.proto b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin.proto new file mode 100644 index 0000000000..4872d3b476 --- /dev/null +++ b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; + +package squareup.wire.json.oneof.kotlin; + +option java_package = "squareup.wire.json.oneof.kotlin"; + +message Nested { + string name = 1; +} + +message Choice { + oneof choice { + string text = 1; + int32 number = 2; + Nested nested = 3; + } + string other = 4; +} diff --git a/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin_builders.proto b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin_builders.proto new file mode 100644 index 0000000000..c169d86f62 --- /dev/null +++ b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin_builders.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; + +package squareup.wire.json.oneof.kotlin_builders; + +option java_package = "squareup.wire.json.oneof.kotlin_builders"; + +message Nested { + string name = 1; +} + +message Choice { + oneof choice { + string text = 1; + int32 number = 2; + Nested nested = 3; + } + string other = 4; +} diff --git a/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin_interop.proto b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin_interop.proto new file mode 100644 index 0000000000..1ab4eb609a --- /dev/null +++ b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin_interop.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; + +package squareup.wire.json.oneof.kotlin_interop; + +option java_package = "squareup.wire.json.oneof.kotlin_interop"; + +message Nested { + string name = 1; +} + +message Choice { + oneof choice { + string text = 1; + int32 number = 2; + Nested nested = 3; + } + string other = 4; +} diff --git a/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin_interop_builders.proto b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin_interop_builders.proto new file mode 100644 index 0000000000..b35bc6be6e --- /dev/null +++ b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/kotlin_interop_builders.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; + +package squareup.wire.json.oneof.kotlin_interop_builders; + +option java_package = "squareup.wire.json.oneof.kotlin_interop_builders"; + +message Nested { + string name = 1; +} + +message Choice { + oneof choice { + string text = 1; + int32 number = 2; + Nested nested = 3; + } + string other = 4; +} diff --git a/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/sealed.proto b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/sealed.proto new file mode 100644 index 0000000000..e6d50d900d --- /dev/null +++ b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/sealed.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; + +package squareup.wire.json.oneof.sealed; + +option java_package = "squareup.wire.json.oneof.sealed"; + +message Nested { + string name = 1; +} + +message Choice { + oneof choice { + string text = 1; + int32 number = 2; + Nested nested = 3; + } + string other = 4; +} diff --git a/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/sealed_builders.proto b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/sealed_builders.proto new file mode 100644 index 0000000000..8099e98cf8 --- /dev/null +++ b/wire-tests/jvm-json-oneof/src/main/proto/squareup/wire/json/oneof/sealed_builders.proto @@ -0,0 +1,18 @@ +syntax = "proto3"; + +package squareup.wire.json.oneof.sealed_builders; + +option java_package = "squareup.wire.json.oneof.sealed_builders"; + +message Nested { + string name = 1; +} + +message Choice { + oneof choice { + string text = 1; + int32 number = 2; + Nested nested = 3; + } + string other = 4; +} diff --git a/wire-tests/jvm-json-oneof/src/test/kotlin/com/squareup/wire/OneOfJsonTest.kt b/wire-tests/jvm-json-oneof/src/test/kotlin/com/squareup/wire/OneOfJsonTest.kt new file mode 100644 index 0000000000..23de4c294e --- /dev/null +++ b/wire-tests/jvm-json-oneof/src/test/kotlin/com/squareup/wire/OneOfJsonTest.kt @@ -0,0 +1,183 @@ +/* + * Copyright (C) 2026 Square, 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 + * + * https://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 com.squareup.wire + +import assertk.assertThat +import assertk.assertions.isEqualTo +import assertk.assertions.isInstanceOf +import assertk.assertions.isNotNull +import com.google.gson.GsonBuilder +import com.squareup.moshi.JsonAdapter +import com.squareup.moshi.Moshi +import java.lang.reflect.InvocationTargetException +import kotlin.test.Test +import kotlin.test.assertFailsWith +import okio.Buffer +import org.junit.runner.RunWith +import org.junit.runners.Parameterized +import org.junit.runners.Parameterized.Parameters + +/** + * Reads JSON that sets two members of one oneof with Moshi and Gson, for each style of generated + * code that Wire's reflective adapters support. + * + * Wire 7 rejected two members for generated Java and for generated Kotlin with flat oneofs, like + * protobuf-java does. It kept the last member for boxed and sealed oneofs, and so does Wire 8. + * Binary decoding keeps the last member for every style. + */ +@RunWith(Parameterized::class) +class OneOfJsonTest( + private val style: Style, + private val library: Library, +) { + enum class Library { + MOSHI, + GSON, + } + + /** How a style of generated code reacts to JSON that sets two members of one oneof. */ + enum class Rejection { + /** Generated Java throws an [IllegalArgumentException] from `build()`. */ + JAVA, + + /** Generated Kotlin throws an [IllegalArgumentException] from a constructor or `build()`. */ + KOTLIN, + + /** A reflective constructor call wraps the [IllegalArgumentException] of generated Kotlin. */ + KOTLIN_REFLECTIVE, + + /** The last member wins. */ + NONE, + } + + enum class Style(val packageName: String, val rejection: Rejection) { + JAVA("java", Rejection.JAVA), + KOTLIN("kotlin", Rejection.KOTLIN_REFLECTIVE), + KOTLIN_INTEROP("kotlin_interop", Rejection.KOTLIN), + KOTLIN_BUILDERS("kotlin_builders", Rejection.KOTLIN), + KOTLIN_INTEROP_BUILDERS("kotlin_interop_builders", Rejection.KOTLIN), + BOXED("boxed", Rejection.NONE), + BOXED_BUILDERS("boxed_builders", Rejection.NONE), + SEALED("sealed", Rejection.NONE), + SEALED_BUILDERS("sealed_builders", Rejection.NONE), + } + + private val type: Class<*> = Class.forName("squareup.wire.json.oneof.${style.packageName}.Choice") + + @Test fun twoMembersInEitherOrder() { + for ((json, lastWins) in listOf( + """{"text":"a","number":1}""" to """{"number":1}""", + """{"number":1,"text":"a"}""" to """{"text":"a"}""", + """{"text":"a","nested":{"name":"n"}}""" to """{"nested":{"name":"n"}}""", + """{"nested":{"name":"n"},"number":2}""" to """{"number":2}""", + """{"text":"a","other":"o","number":1}""" to """{"number":1,"other":"o"}""", + )) { + if (style.rejection == Rejection.NONE) { + assertThat(roundTrip(json)).isEqualTo(lastWins) + } else { + assertRejected { fromJson(json) } + } + } + } + + @Test fun nullNextToValueKeepsTheValue() { + for ((json, expected) in listOf( + """{"text":"a","number":null}""" to """{"text":"a"}""", + """{"number":null,"text":"a"}""" to """{"text":"a"}""", + """{"number":1,"text":null}""" to """{"number":1}""", + """{"text":null,"number":1}""" to """{"number":1}""", + """{"text":"a","number":null,"nested":null}""" to """{"text":"a"}""", + """{"text":null,"number":null}""" to """{}""", + )) { + assertThat(roundTrip(json)).isEqualTo(expected) + } + } + + @Test fun sameMemberTwiceKeepsTheLastValue() { + assertThat(roundTrip("""{"text":"a","text":"b"}""")).isEqualTo("""{"text":"b"}""") + } + + @Test fun lastMemberWinsOnBinaryDecoding() { + @Suppress("UNCHECKED_CAST") + val reflective = ProtoAdapter::class.java.getMethod("newMessageAdapter", Class::class.java) + .invoke(null, type) as ProtoAdapter + val generated = adapterOf(type) + // Tag 1 is `text` with "a", then tag 2 is `number` with 1. Then in the other order. + val textThenNumber = Buffer().writeByte(0x0a).writeByte(1).writeUtf8("a").writeByte(0x10).writeByte(1).readByteString() + val numberThenText = Buffer().writeByte(0x10).writeByte(1).writeByte(0x0a).writeByte(1).writeUtf8("a").readByteString() + + // The reflective builder of Kotlin without `javaInterop` or `buildersOnly` does not clear the + // other members of a flat oneof. It has not done so in Wire 7 either, so skip it here. + val decoders = if (style == Style.KOTLIN) listOf(generated) else listOf(reflective, generated) + for (decoder in decoders) { + assertThat(roundTripJson(decoder.decode(textThenNumber))).isEqualTo("""{"number":1}""") + assertThat(roundTripJson(decoder.decode(numberThenText))).isEqualTo("""{"text":"a"}""") + } + } + + private fun assertRejected(block: () -> Unit) { + val message = "t most one of text, number, nested may be non-null" + when (style.rejection) { + Rejection.JAVA -> { + val e = assertFailsWith { block() } + assertThat(e.message).isEqualTo("a$message") + } + Rejection.KOTLIN -> { + val e = assertFailsWith { block() } + assertThat(e.message).isEqualTo("A$message") + } + Rejection.KOTLIN_REFLECTIVE -> { + val e = assertFailsWith { block() } + assertThat(e.cause).isNotNull().isInstanceOf() + assertThat(e.cause!!.message).isEqualTo("A$message") + } + Rejection.NONE -> error("not rejected") + } + } + + @Suppress("UNCHECKED_CAST") + private fun adapterOf(type: Class<*>): ProtoAdapter { + val companion = type.getField("ADAPTER").get(null) + return companion as ProtoAdapter + } + + @Suppress("UNCHECKED_CAST") + private fun fromJson(json: String): Any = when (library) { + Library.MOSHI -> (moshi.adapter(type) as JsonAdapter).fromJson(json)!! + Library.GSON -> gson.fromJson(json, type) + } + + @Suppress("UNCHECKED_CAST") + private fun toJson(value: Any): String = when (library) { + Library.MOSHI -> (moshi.adapter(type) as JsonAdapter).toJson(value) + Library.GSON -> gson.toJson(value, type) + } + + private fun roundTrip(json: String): String = toJson(fromJson(json)) + + private fun roundTripJson(value: Any): String = toJson(value) + + companion object { + private val moshi = Moshi.Builder().add(WireJsonAdapterFactory()).build() + private val gson = GsonBuilder().registerTypeAdapterFactory(WireTypeAdapterFactory()).create() + + @Parameters(name = "{0} {1}") + @JvmStatic + fun parameters(): List> = Style.entries.flatMap { style -> + Library.entries.map { library -> arrayOf(style, library) } + } + } +} diff --git a/wire-tests/wire-json-shared-kotlin-tests/com/squareup/wire/WireJsonTest.kt b/wire-tests/wire-json-shared-kotlin-tests/com/squareup/wire/WireJsonTest.kt index 513df8c6db..80fe1c1dbb 100644 --- a/wire-tests/wire-json-shared-kotlin-tests/com/squareup/wire/WireJsonTest.kt +++ b/wire-tests/wire-json-shared-kotlin-tests/com/squareup/wire/WireJsonTest.kt @@ -33,6 +33,7 @@ import com.squareup.wire.proto2.alltypes.AllTypes as AllTypesProto2 import com.squareup.wire.proto3.alltypes.AllTypes as AllTypesProto3 import java.io.File import java.util.Collections +import kotlin.test.assertFailsWith import okio.Buffer import okio.ByteString import okio.ByteString.Companion.decodeHex @@ -366,29 +367,57 @@ class WireJsonTest { assertThat(value.delivered_within_or_free).isEqualTo(durationOfSeconds(5L, 3L)) } - @Test fun lastMemberOfOneOfWinsOnReading() { - val parsed = jsonLibrary.fromJson( + @Test fun twoMembersOfOneOfAreRejectedOnReading() { + for (json in listOf( """{"oneof_string":"a","oneof_int32":1}""", + """{"oneof_int32":1,"oneof_string":"a"}""", + """{"oneof_string":"a","oneof_nested_message":{"a":1}}""", + )) { + val exception = assertFailsWith { + jsonLibrary.fromJson(json, AllTypesProto3::class.java) + } + // Generated Java and generated Kotlin differ in the case of the first letter. + assertThat(exception.message!!).contains("t most one of ") + assertThat(exception.message!!).contains("may be non-null") + } + } + + @Test fun nullMemberOfOneOfNextToValueIsIgnoredOnReading() { + val string = AllTypesProto3.Builder().oneof_string("a").build() + val int32 = AllTypesProto3.Builder().oneof_int32(1).build() + for ((json, expected) in listOf( + """{"oneof_string":"a","oneof_int32":null}""" to string, + """{"oneof_int32":null,"oneof_string":"a"}""" to string, + """{"oneof_int32":1,"oneof_string":null}""" to int32, + """{"oneof_string":null,"oneof_int32":1}""" to int32, + """{"oneof_string":null,"oneof_int32":null}""" to AllTypesProto3.Builder().build(), + )) { + assertThat(jsonLibrary.fromJson(json, AllTypesProto3::class.java)).isEqualTo(expected) + } + } + + @Test fun sameMemberOfOneOfTwiceKeepsTheLastValueOnReading() { + val parsed = jsonLibrary.fromJson( + """{"oneof_string":"a","oneof_string":"b"}""", AllTypesProto3::class.java, ) - assertThat(parsed).isEqualTo(AllTypesProto3.Builder().oneof_int32(1).build()) + assertThat(parsed).isEqualTo(AllTypesProto3.Builder().oneof_string("b").build()) } - // This decodes binary, not JSON. It lives here because jvm-json-java sets compact = true, so only the - // reflective adapter runs. Moving it to another suite would stop it from covering that adapter. - @Test fun lastMemberOfOneOfWinsOnDecoding() { - val string = AllTypesProto3.ADAPTER.encodeByteString(AllTypesProto3.Builder().oneof_string("a").build()) - val int32 = AllTypesProto3.ADAPTER.encodeByteString(AllTypesProto3.Builder().oneof_int32(1).build()) - - fun decode(vararg members: ByteString): AllTypesProto3 { - val buffer = Buffer() - members.forEach { buffer.write(it) } - return AllTypesProto3.ADAPTER.decode(buffer.readByteString()) + @Test fun lastMemberOfOneOfWinsOnDecodingBinary() { + val string = AllTypesProto3.Builder().oneof_string("a").build() + val int32 = AllTypesProto3.Builder().oneof_int32(1).build() + val adapter = ProtoAdapter.newMessageAdapter(AllTypesProto3::class.java) + for ((members, expected) in listOf( + listOf(string, int32) to int32, + listOf(int32, string) to string, + )) { + val bytes = members.fold(Buffer()) { buffer, member -> + buffer.write(AllTypesProto3.ADAPTER.encodeByteString(member)) + }.readByteString() + assertThat(AllTypesProto3.ADAPTER.decode(bytes)).isEqualTo(expected) + assertThat(adapter.decode(bytes)).isEqualTo(expected) } - - assertThat(decode(string, int32)).isEqualTo(AllTypesProto3.Builder().oneof_int32(1).build()) - assertThat(decode(int32, string, int32)).isEqualTo(AllTypesProto3.Builder().oneof_int32(1).build()) - assertThat(decode(int32, string)).isEqualTo(AllTypesProto3.Builder().oneof_string("a").build()) } @Test fun unknownEnumValueIsKeptAsUnknownField() {