Debian Codegraph @

libartservice/service/javatests/com/android/server/art/testing/TestingUtils.java

raw
1 /*
2 * Copyright (C) 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.server.art.testing;
18
19 import static org.mockito.Mockito.argThat;
20
21 import android.annotation.NonNull;
22 import android.annotation.Nullable;
23 import android.util.Log;
24
25 import com.google.common.truth.Correspondence;
26 import com.google.common.truth.Truth;
27
28 import java.lang.reflect.Field;
29 import java.lang.reflect.Modifier;
30 import java.util.List;
31
32 public final class TestingUtils {
33 private static final String TAG = "ArtServiceTesting";
34
35 private TestingUtils() {}
36
37 /**
38 * Recursively compares two objects using reflection. Returns true if the two objects are equal.
39 * For simplicity, this method only supports types that every field is a primitive type, a
40 * string, a {@link List}, or a supported type.
41 */
42 public static boolean deepEquals(
43 @Nullable Object a, @Nullable Object b, @NonNull StringBuilder errorMsg) {
44 try {
45 if (a == null && b == null) {
46 return true;
47 }
48 if (a == null || b == null) {
49 errorMsg.append(String.format("Nullability mismatch: %s != %s",
50 a == null ? "null" : "nonnull", b == null ? "null" : "nonnull"));
51 return false;
52 }
53 if (a instanceof List && b instanceof List) {
54 return listDeepEquals((List<?>) a, (List<?>) b, errorMsg);
55 }
56 if (a.getClass() != b.getClass()) {
57 errorMsg.append(
58 String.format("Type mismatch: %s != %s", a.getClass(), b.getClass()));
59 return false;
60 }
61 if (a.getClass() == String.class) {
62 if (!a.equals(b)) {
63 errorMsg.append(String.format("%s != %s", a, b));
64 }
65 return a.equals(b);
66 }
67 if (a.getClass().isArray()) {
68 throw new UnsupportedOperationException("Array type is not supported");
69 }
70 for (Field field : a.getClass().getDeclaredFields()) {
71 if (Modifier.isStatic(field.getModifiers())) {
72 continue;
73 }
74 field.setAccessible(true);
75 if (field.getType().isPrimitive()) {
76 if (!field.get(a).equals(field.get(b))) {
77 errorMsg.append(String.format("Field %s mismatch: %s != %s",
78 field.getName(), field.get(a), field.get(b)));
79 return false;
80 }
81 } else if (!deepEquals(field.get(a), field.get(b), errorMsg)) {
82 errorMsg.insert(0, String.format("Field %s mismatch: ", field.getName()));
83 return false;
84 }
85 }
86 return true;
87 } catch (ReflectiveOperationException e) {
88 throw new RuntimeException(e);
89 }
90 }
91
92 /** Same as above, but ignores any error message. */
93 public static boolean deepEquals(@Nullable Object a, @Nullable Object b) {
94 var errorMsgIgnored = new StringBuilder();
95 return deepEquals(a, b, errorMsgIgnored);
96 }
97
98 /**
99 * A Mockito argument matcher that uses {@link #deepEquals} to compare objects and logs any
100 * mismatch.
101 */
102 public static <T> T deepEq(@Nullable T expected) {
103 return argThat(arg -> {
104 var errorMsg = new StringBuilder();
105 boolean result = deepEquals(arg, expected, errorMsg);
106 if (!result) {
107 Log.e(TAG, errorMsg.toString());
108 }
109 return result;
110 });
111 }
112
113 /**
114 * A Mockito argument matcher that matches a list containing expected in any order.
115 */
116 @SafeVarargs
117 public static <ListType extends List<ItemType>, ItemType> ListType inAnyOrder(
118 @Nullable ItemType... expected) {
119 return argThat(argument -> {
120 try {
121 Truth.assertThat(argument).containsExactlyElementsIn(expected);
122 return true;
123 } catch (AssertionError error) {
124 return false;
125 }
126 });
127 }
128
129 /**
130 * {@link #inAnyOrder(Object[])} but using {@link #deepEquals(Object, Object)}} for comparisons.
131 *
132 * @see #inAnyOrder(Object[])
133 */
134 @SafeVarargs
135 public static <ListType extends List<ItemType>, ItemType> ListType inAnyOrderDeepEquals(
136 @Nullable ItemType... expected) {
137 return argThat(argument -> {
138 try {
139 Truth.assertThat(argument)
140 .comparingElementsUsing(deepEquality())
141 .containsExactlyElementsIn(expected);
142 return true;
143 } catch (AssertionError error) {
144 return false;
145 }
146 });
147 }
148
149 /**
150 * A Truth correspondence that uses {@link #deepEquals} to compare objects and reports any
151 * mismatch.
152 */
153 public static <T> Correspondence<T, T> deepEquality() {
154 return Correspondence.<T, T>from(TestingUtils::deepEquals, "deeply equals")
155 .formattingDiffsUsing((actual, expected) -> {
156 var errorMsg = new StringBuilder();
157 deepEquals(actual, expected, errorMsg);
158 return errorMsg.toString();
159 });
160 }
161
162 private static boolean listDeepEquals(
163 @NonNull List<?> a, @NonNull List<?> b, @NonNull StringBuilder errorMsg) {
164 if (a.size() != b.size()) {
165 errorMsg.append(String.format("List length mismatch: %d != %d", a.size(), b.size()));
166 return false;
167 }
168 for (int i = 0; i < a.size(); i++) {
169 if (!deepEquals(a.get(i), b.get(i), errorMsg)) {
170 errorMsg.insert(0, String.format("Element %d mismatch: ", i));
171 return false;
172 }
173 }
174 return true;
175 };
176 }