/
ProtoSubject.java
306 lines (267 loc) · 11.2 KB
/
ProtoSubject.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/*
* Copyright (c) 2016 Google, 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
*
* 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.common.truth.extensions.proto;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.asList;
import static com.google.common.truth.extensions.proto.FieldScopeUtil.asList;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.truth.FailureStrategy;
import com.google.common.truth.extensions.proto.MessageDifferencer.ReportType;
import com.google.common.truth.extensions.proto.MessageDifferencer.SpecificField;
import com.google.common.truth.extensions.proto.MessageDifferencer.StreamReporter;
import com.google.protobuf.Descriptors.FieldDescriptor;
import com.google.protobuf.Message;
import com.google.protobuf.TextFormat;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
/**
* Truth subject for the full version of Protocol Buffers.
*
* <p>{@code ProtoTruth.assertThat(actual).isEqualTo(expected)} performs the same assertion as
* {@code Truth.assertThat(actual).isEqualTo(expected)}, but with a better failure message. By
* default, the assertions are strict with respect to repeated field order, missing fields, etc.
* This behavior can be changed with the configuration methods on this subject, e.g. {@code
* ProtoTruth.assertThat(actual).ignoringRepeatedFieldOrder().isEqualTo(expected)}.
*
* <p>Equality tests, and other methods, may yield slightly different behavior for versions 2 and 3
* of Protocol Buffers. If testing protos of multiple versions, make sure you understand the
* behaviors of default and unknown fields so you don't under or over test.
*
* @param <S> subject class type.
* @param <M> message type.
*/
public class ProtoSubject<S extends ProtoSubject<S, M>, M extends Message>
extends LiteProtoSubject<S, M> implements ProtoFluentAssertion {
// TODO(user): Type this if we solve the typing assertAbout() problem for
// IterableOfProtosSubject and there is use for such typing.
private final FluentEqualityConfig config;
protected ProtoSubject(FailureStrategy failureStrategy, @Nullable M message) {
this(failureStrategy, FluentEqualityConfig.defaultInstance(), message);
}
ProtoSubject(FailureStrategy failureStrategy, FluentEqualityConfig config, @Nullable M message) {
super(failureStrategy, message);
this.config = config;
}
ProtoSubject<?, Message> usingConfig(FluentEqualityConfig newConfig) {
MessageSubject newSubject = new MessageSubject(failureStrategy, newConfig, getSubject());
if (internalCustomName() != null) {
newSubject = newSubject.named(internalCustomName());
}
return newSubject;
}
@Override
public ProtoFluentAssertion ignoringFieldAbsence() {
return usingConfig(config.ignoringFieldAbsence());
}
@Override
public ProtoFluentAssertion ignoringRepeatedFieldOrder() {
return usingConfig(config.ignoringRepeatedFieldOrder());
}
@Override
public ProtoFluentAssertion withPartialScope(FieldScope fieldScope) {
return usingConfig(config.withPartialScope(checkNotNull(fieldScope, "fieldScope")));
}
@Override
public ProtoFluentAssertion ignoringFields(int firstFieldNumber, int... rest) {
return ignoringFields(asList(firstFieldNumber, rest));
}
@Override
public ProtoFluentAssertion ignoringFields(Iterable<Integer> fieldNumbers) {
return usingConfig(config.ignoringFields(fieldNumbers));
}
@Override
public ProtoFluentAssertion ignoringFieldDescriptors(
FieldDescriptor firstFieldDescriptor, FieldDescriptor... rest) {
return ignoringFieldDescriptors(asList(firstFieldDescriptor, rest));
}
@Override
public ProtoFluentAssertion ignoringFieldDescriptors(Iterable<FieldDescriptor> fieldDescriptors) {
return usingConfig(config.ignoringFieldDescriptors(fieldDescriptors));
}
@Override
public ProtoFluentAssertion ignoringFieldScope(FieldScope fieldScope) {
return usingConfig(config.ignoringFieldScope(checkNotNull(fieldScope, "fieldScope")));
}
@Override
public ProtoFluentAssertion reportingMismatchesOnly() {
return usingConfig(config.reportingMismatchesOnly());
}
@Override
public void isEqualTo(@Nullable Object expected) {
if (getSubject() == null
|| expected == null
|| getSubject().getClass() != expected.getClass()) {
super.isEqualTo(expected);
} else {
Reporter reporter = new Reporter();
if (!makeDifferencer().compare((Message) expected, getSubject(), reporter)) {
reporter.failEqual((Message) expected);
}
}
}
/**
* Same as {@link #isEqualTo(Object)}, except it returns true on success and false on failure
* without throwing any exceptions.
*/
boolean testIsEqualTo(@Nullable Object expected) {
if (getSubject() == null || expected == null) {
return getSubject() == expected; // Only true if both null.
} else if (getSubject().getClass() != expected.getClass()) {
return false;
} else {
return makeDifferencer().compare((Message) expected, getSubject(), null);
}
}
@Override
public void isNotEqualTo(@Nullable Object expected) {
if (getSubject() == null
|| expected == null
|| getSubject().getClass() != expected.getClass()) {
super.isNotEqualTo(expected);
} else {
Reporter reporter = new Reporter();
if (makeDifferencer().compare((Message) expected, getSubject(), reporter)) {
reporter.failNotEqual((Message) expected);
}
}
}
@Override
public void hasAllRequiredFields() {
if (!getSubject().isInitialized()) {
failWithRawMessage(
"Not true that %s has all required fields set. Missing: %s",
getTrimmedDisplaySubject(), getSubject().findInitializationErrors());
}
}
private MessageDifferencer makeDifferencer() {
return config.toMessageDifferencer(getSubject().getDescriptorForType());
}
/**
* {@link MessageDifferencer.Reporter} implementation for reporting the results of {@link
* #isEqualTo(Object)}.
*/
private class Reporter implements MessageDifferencer.Reporter {
private final List<ReporterRecord> records = new ArrayList<ReporterRecord>();
private boolean anyFailures = false;
private boolean anyNotices = false;
@Override
public void report(
ReportType type, Message message1, Message message2, ImmutableList<SpecificField> path) {
ReporterRecord record = ReporterRecord.of(type, message1, message2, path);
anyFailures |= record.isFailure();
anyNotices |= !record.isFailure();
records.add(record);
}
void failEqual(Message expected) {
StringBuilder rawMessage = new StringBuilder();
rawMessage.append("Not true that ");
if (ProtoSubject.this.internalCustomName() != null) {
rawMessage.append(ProtoSubject.this.internalCustomName()).append(" compares equal. ");
} else {
rawMessage.append("messages compare equal. ");
}
StreamReporter streamReporter = new StreamReporter(rawMessage);
if (anyFailures) {
rawMessage.append("Differences were found:\n");
for (ReporterRecord record : records) {
if (record.isFailure()) {
streamReporter.report(
record.type(), record.message1(), record.message2(), record.path());
}
}
if (anyNotices && !ProtoSubject.this.config.reportMismatchesOnly()) {
// Append the full report.
rawMessage.append("\nFull diff:\n");
for (ReporterRecord record : records) {
streamReporter.report(
record.type(), record.message1(), record.message2(), record.path());
}
}
} else {
rawMessage.append("No differences were reported.");
if (!ProtoSubject.this.config.reportMismatchesOnly()) {
if (anyNotices) {
rawMessage.append("\nFull diff:\n");
for (ReporterRecord record : records) {
streamReporter.report(
record.type(), record.message1(), record.message2(), record.path());
}
} else {
// Shouldn't really happen, but it's better to print something than nothing if it does.
rawMessage.append("\nActual:\n");
rawMessage.append(TextFormat.printToString(getSubject()));
rawMessage.append("Expected:\n");
rawMessage.append(TextFormat.printToString(expected));
}
}
}
ProtoSubject.this.failWithRawMessage(rawMessage.toString());
}
void failNotEqual(Message expected) {
StringBuilder rawMessage = new StringBuilder();
rawMessage.append("Not true that ");
if (ProtoSubject.this.internalCustomName() != null) {
rawMessage.append(ProtoSubject.this.internalCustomName()).append(" compares not equal. ");
} else {
rawMessage.append("messages compare not equal. ");
}
if (!records.isEmpty() && !ProtoSubject.this.config.reportMismatchesOnly()) {
rawMessage.append("Only ignorable differences were found:\n");
StreamReporter streamReporter = new StreamReporter(rawMessage);
for (ReporterRecord record : records) {
streamReporter.report(record.type(), record.message1(), record.message2(), record.path());
}
} else {
rawMessage.append("No differences were found.");
if (!ProtoSubject.this.config.reportMismatchesOnly()) {
rawMessage.append("\nActual:\n");
rawMessage.append(TextFormat.printToString(getSubject()));
rawMessage.append("Expected:\n");
rawMessage.append(TextFormat.printToString(expected));
}
}
ProtoSubject.this.failWithRawMessage(rawMessage.toString());
}
}
@AutoValue
abstract static class ReporterRecord {
abstract ReportType type();
abstract Message message1();
abstract Message message2();
abstract ImmutableList<SpecificField> path();
// Whether this ReporterRecord indicates an actionable message difference.
final boolean isFailure() {
return type() == ReportType.ADDED
|| type() == ReportType.DELETED
|| type() == ReportType.MODIFIED;
}
static ReporterRecord of(
ReportType type, Message message1, Message message2, ImmutableList<SpecificField> path) {
return new AutoValue_ProtoSubject_ReporterRecord(type, message1, message2, path);
}
}
static final class MessageSubject extends ProtoSubject<MessageSubject, Message> {
MessageSubject(FailureStrategy failureStrategy, @Nullable Message message) {
super(failureStrategy, message);
}
private MessageSubject(
FailureStrategy failureStrategy, FluentEqualityConfig config, @Nullable Message message) {
super(failureStrategy, config, message);
}
}
}