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
@@ -0,0 +1,48 @@
/*
* Copyright 2025 Google LLC
*
* 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 com.google.firebase.dataconnect.testutil

import com.google.protobuf.ListValue
import com.google.protobuf.NullValue
import com.google.protobuf.Struct
import com.google.protobuf.Value

fun Struct.deepCopy(): Struct =
Struct.newBuilder()
.also { builder ->
fieldsMap.entries.forEach { (key, value) -> builder.putFields(key, value.deepCopy()) }
}
.build()

fun ListValue.deepCopy(): ListValue =
ListValue.newBuilder()
.also { builder -> valuesList.forEach { builder.addValues(it.deepCopy()) } }
.build()

fun Value.deepCopy(): Value =
Value.newBuilder().let { builder ->
when (kindCase) {
Value.KindCase.KIND_NOT_SET -> {}
Value.KindCase.NULL_VALUE -> builder.setNullValue(NullValue.NULL_VALUE)
Value.KindCase.NUMBER_VALUE -> builder.setNumberValue(numberValue)
Value.KindCase.STRING_VALUE -> builder.setStringValue(stringValue)
Value.KindCase.BOOL_VALUE -> builder.setBoolValue(boolValue)
Value.KindCase.STRUCT_VALUE -> builder.setStructValue(structValue.deepCopy())
Value.KindCase.LIST_VALUE -> builder.setListValue(listValue.deepCopy())
}
builder.build()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
/*
* Copyright 2025 Google LLC
*
* 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 com.google.firebase.dataconnect.testutil

import com.google.protobuf.ListValue
import com.google.protobuf.Struct
import com.google.protobuf.Value

fun structFastEqual(struct1: Struct, struct2: Struct): Boolean {
if (struct1 === struct2) {
return true
} else if (struct1.fieldsCount != struct2.fieldsCount) {
return false
}

val struct2FieldsMap = struct2.fieldsMap
struct1.fieldsMap.entries.forEach { (key, value1) ->
val value2 = struct2FieldsMap[key] ?: return false
if (!valueFastEqual(value1, value2)) {
return false
}
}

return true
}

fun listValueFastEqual(listValue1: ListValue, listValue2: ListValue): Boolean {
if (listValue1 === listValue2) {
return true
} else if (listValue1.valuesCount != listValue2.valuesCount) {
return false
}

listValue1.valuesList.zip(listValue2.valuesList).forEach { (value1, value2) ->
if (!valueFastEqual(value1, value2)) {
return false
}
}

return true
}

fun valueFastEqual(value1: Value, value2: Value): Boolean {
if (value1 === value2) {
return true
} else if (value1.kindCase != value2.kindCase) {
return false
}
return when (value1.kindCase) {
Value.KindCase.KIND_NOT_SET -> true
Value.KindCase.NULL_VALUE -> true
Value.KindCase.NUMBER_VALUE -> numberValuesEqual(value1.numberValue, value2.numberValue)
Value.KindCase.STRING_VALUE -> value1.stringValue == value2.stringValue
Value.KindCase.BOOL_VALUE -> value1.boolValue == value2.boolValue
Value.KindCase.STRUCT_VALUE -> structFastEqual(value1.structValue, value2.structValue)
Value.KindCase.LIST_VALUE -> listValueFastEqual(value1.listValue, value2.listValue)
}
}

data class DifferencePathPair<T : Difference>(val path: ProtoValuePath, val difference: T)

sealed interface Difference {
data class KindCase(val value1: Value, val value2: Value) : Difference
data class BoolValue(val value1: Boolean, val value2: Boolean) : Difference
data class NumberValue(val value1: Double, val value2: Double) : Difference
data class StringValue(val value1: String, val value2: String) : Difference
data class StructMissingKey(val key: String, val value: Value) : Difference
data class StructUnexpectedKey(val key: String, val value: Value) : Difference
data class ListMissingElement(val index: Int, val value: Value) : Difference
data class ListUnexpectedElement(val index: Int, val value: Value) : Difference
}

fun structDiff(
struct1: Struct,
struct2: Struct,
path: MutableProtoValuePath = mutableListOf(),
differences: MutableList<DifferencePathPair<*>> = mutableListOf(),
): MutableList<DifferencePathPair<*>> {
val map1 = struct1.fieldsMap
val map2 = struct2.fieldsMap

map1.entries.forEach { (key, value) ->
if (key !in map2) {
differences.add(path, Difference.StructMissingKey(key, value))
} else {
path.withAppendedStructKey(key) { valueDiff(value, map2[key]!!, path, differences) }
}
}

map2.entries.forEach { (key, value) ->
if (key !in map1) {
differences.add(path, Difference.StructUnexpectedKey(key, value))
}
}

return differences
}

fun listValueDiff(
listValue1: ListValue,
listValue2: ListValue,
path: MutableProtoValuePath = mutableListOf(),
differences: MutableList<DifferencePathPair<*>> = mutableListOf(),
): MutableList<DifferencePathPair<*>> {
repeat(listValue1.valuesCount.coerceAtMost(listValue2.valuesCount)) {
val value1 = listValue1.getValues(it)
val value2 = listValue2.getValues(it)
path.withAppendedListIndex(it) { valueDiff(value1, value2, path, differences) }
}

if (listValue1.valuesCount > listValue2.valuesCount) {
(listValue2.valuesCount until listValue1.valuesCount).forEach {
differences.add(path, Difference.ListMissingElement(it, listValue1.getValues(it)))
}
} else if (listValue1.valuesCount < listValue2.valuesCount) {
(listValue1.valuesCount until listValue2.valuesCount).forEach {
differences.add(path, Difference.ListUnexpectedElement(it, listValue2.getValues(it)))
}
}

return differences
}

fun valueDiff(
value1: Value,
value2: Value,
path: MutableProtoValuePath = mutableListOf(),
differences: MutableList<DifferencePathPair<*>> = mutableListOf(),
): MutableList<DifferencePathPair<*>> {
if (value1.kindCase != value2.kindCase) {
differences.add(path, Difference.KindCase(value1, value2))
return differences
}

when (value1.kindCase) {
Value.KindCase.KIND_NOT_SET,
Value.KindCase.NULL_VALUE -> {}
Value.KindCase.STRUCT_VALUE ->
structDiff(value1.structValue, value2.structValue, path, differences)
Value.KindCase.LIST_VALUE ->
listValueDiff(value1.listValue, value2.listValue, path, differences)
Value.KindCase.BOOL_VALUE ->
if (value1.boolValue != value2.boolValue) {
differences.add(path, Difference.BoolValue(value1.boolValue, value2.boolValue))
}
Value.KindCase.NUMBER_VALUE ->
if (!numberValuesEqual(value1.numberValue, value2.numberValue)) {
differences.add(path, Difference.NumberValue(value1.numberValue, value2.numberValue))
}
Value.KindCase.STRING_VALUE ->
if (value1.stringValue != value2.stringValue) {
differences.add(path, Difference.StringValue(value1.stringValue, value2.stringValue))
}
}

return differences
}

private fun MutableCollection<DifferencePathPair<*>>.add(
path: MutableProtoValuePath,
difference: Difference
) {
add(DifferencePathPair(path.toList(), difference))
}

fun Collection<DifferencePathPair<*>>.toSummaryString(): String = buildString {
val differences: Collection<DifferencePathPair<*>> = this@toSummaryString
if (differences.size == 1) {
append("1 difference: ")
append(differences.single().run { "${path.toPathString()}=$difference" })
} else {
append("${differences.size} differences:")
differences.forEachIndexed { index, (path, difference) ->
append('\n')
append(index + 1)
append(": ")
appendPathString(path)
append('=')
append(difference)
}
}
}

fun numberValuesEqual(value1: Double, value2: Double): Boolean =
if (value1.isNaN()) {
value2.isNaN()
} else if (value1 != value2) {
false
} else if (value1 == 0.0) {
// Explicitly consider 0.0 and -0.0 to be "unequal"; the == operator considers them "equal".
value1.toBits() == value2.toBits()
} else {
true
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
* Copyright 2025 Google LLC
*
* 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 com.google.firebase.dataconnect.testutil

import com.google.protobuf.ListValue
import com.google.protobuf.Struct
import com.google.protobuf.Value

fun Struct.map(callback: (path: ProtoValuePath, value: Value) -> Value?): Struct {
val mappedValue = toValueProto().map(callback)
checkNotNull(mappedValue) {
"callback returned null for root, " +
"but must be a non-null ${Value.KindCase.STRUCT_VALUE} [qhkdn2b8z5]"
Copy link

@stephenarosaj stephenarosaj Dec 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just curious - what are these seemingly random strings?

}
check(mappedValue.isStructValue) {
"callback returned ${mappedValue.kindCase} for root, " +
"but must be a non-null ${Value.KindCase.STRUCT_VALUE} [tmhxthgwyk]"
}
return mappedValue.structValue
}

fun ListValue.map(callback: (path: ProtoValuePath, value: Value) -> Value?): ListValue {
val mappedValue = toValueProto().map(callback)
checkNotNull(mappedValue) {
"callback returned null for root, " +
"but must be a non-null ${Value.KindCase.LIST_VALUE} [hdm7p67g54]"
}
check(mappedValue.isListValue) {
"callback returned ${mappedValue.kindCase} for root, " +
"but must be a non-null ${Value.KindCase.LIST_VALUE} [nhfe2stftq]"
}
return mappedValue.listValue
}

fun <V : Value?> Value.map(
callback: (path: ProtoValuePath, value: Value) -> V,
): V =
mapRecursive(
value = this,
path = mutableListOf(),
callback = callback,
)

private fun <V : Value?> mapRecursive(
value: Value,
path: MutableProtoValuePath,
callback: (path: ProtoValuePath, value: Value) -> V,
): V {
val processedValue: Value =
if (value.isStructValue) {
Struct.newBuilder().let { structBuilder ->
value.structValue.fieldsMap.entries.forEach { (key, childValue) ->
val mappedChildValue =
path.withAppendedStructKey(key) { mapRecursive(childValue, path, callback) }
if (mappedChildValue !== null) {
structBuilder.putFields(key, mappedChildValue)
}
}
structBuilder.build().toValueProto()
}
} else if (value.isListValue) {
ListValue.newBuilder().let { listValueBuilder ->
value.listValue.valuesList.forEachIndexed { index, childValue ->
val mappedChildValue =
path.withAppendedListIndex(index) { mapRecursive(childValue, path, callback) }
if (mappedChildValue !== null) {
listValueBuilder.addValues(mappedChildValue)
}
}
listValueBuilder.build().toValueProto()
}
} else {
value
}

return callback(path.toList(), processedValue)
}
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ fun beEqualToDefaultInstance(): Matcher<MessageLite?> = neverNullMatcher { value
"the default instance: ${defaultInstance.print().value}"
},
{
"${value::class.qualifiedName} ${value.print().value} should not be equal to : " +
"${value::class.qualifiedName} ${value.print().value} should not be equal to " +
"the default instance: ${defaultInstance.print().value}"
}
)
Expand Down Expand Up @@ -114,8 +114,11 @@ fun beEqualTo(other: Struct?): Matcher<Struct?> = neverNullMatcher { value ->
)
} else {
MatcherResult(
value == other,
{ "${value.print().value} should be equal to ${other.print().value}" },
structFastEqual(value, other),
{
"${value.print().value} should be equal to ${other.print().value}, " +
"but found ${structDiff(value, other).toSummaryString()}"
},
{ "${value.print().value} should not be equal to ${other.print().value}" }
)
}
Expand All @@ -134,8 +137,11 @@ fun beEqualTo(other: Value?): Matcher<Value?> = neverNullMatcher { value ->
)
} else {
MatcherResult(
value == other,
{ "${value.print().value} should be equal to ${other.print().value}" },
valueFastEqual(value, other),
{
"${value.print().value} should be equal to ${other.print().value}, " +
"but found ${valueDiff(value, other).toSummaryString()}"
},
{ "${value.print().value} should not be equal to ${other.print().value}" }
)
}
Expand Down
Loading