-
Notifications
You must be signed in to change notification settings - Fork 115
/
JsonAssert.java
444 lines (399 loc) · 15.1 KB
/
JsonAssert.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/**
* Copyright 2009-2019 the original author or authors.
*
* 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 net.javacrumbs.jsonunit.assertj;
import static net.javacrumbs.jsonunit.core.internal.Diff.quoteTextValue;
import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getNode;
import static net.javacrumbs.jsonunit.core.internal.JsonUtils.getPathPrefix;
import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.ARRAY;
import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.BOOLEAN;
import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NULL;
import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.NUMBER;
import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.OBJECT;
import static net.javacrumbs.jsonunit.core.internal.Node.NodeType.STRING;
import static net.javacrumbs.jsonunit.jsonpath.InternalJsonPathUtils.resolveJsonPaths;
import static org.assertj.core.description.Description.mostRelevantDescription;
import static org.assertj.core.util.Strings.isNullOrEmpty;
import java.math.BigDecimal;
import java.net.URI;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import net.javacrumbs.jsonunit.core.Configuration;
import net.javacrumbs.jsonunit.core.ConfigurationWhen.ApplicableForPath;
import net.javacrumbs.jsonunit.core.ConfigurationWhen.PathsParam;
import net.javacrumbs.jsonunit.core.Option;
import net.javacrumbs.jsonunit.core.internal.Diff;
import net.javacrumbs.jsonunit.core.internal.JsonUtils;
import net.javacrumbs.jsonunit.core.internal.Node;
import net.javacrumbs.jsonunit.core.internal.Path;
import net.javacrumbs.jsonunit.core.internal.matchers.InternalMatcher;
import net.javacrumbs.jsonunit.core.listener.DifferenceListener;
import net.javacrumbs.jsonunit.jsonpath.JsonPathAdapter;
import org.assertj.core.api.AbstractAssert;
import org.assertj.core.api.AbstractStringAssert;
import org.assertj.core.api.BigDecimalAssert;
import org.assertj.core.api.BigIntegerAssert;
import org.assertj.core.api.BooleanAssert;
import org.assertj.core.api.StringAssert;
import org.assertj.core.api.UriAssert;
import org.assertj.core.description.Description;
import org.assertj.core.error.MessageFormatter;
import org.hamcrest.Matcher;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class JsonAssert extends AbstractAssert<JsonAssert, Object> {
final Path path;
final Configuration configuration;
private final Object actualForMatcher;
JsonAssert(Path path, Configuration configuration, Object actual, boolean alreadyParsed) {
super(
alreadyParsed ? JsonUtils.wrapDeserializedObject(actual) : JsonUtils.convertToJson(actual, "actual"),
JsonAssert.class);
this.path = path;
this.configuration = configuration;
this.actualForMatcher = alreadyParsed ? JsonUtils.wrapDeserializedObject(actual) : actual;
usingComparator(new JsonComparator(configuration, path, false));
}
JsonAssert(Path path, Configuration configuration, Object actual) {
this(path, configuration, actual, false);
}
JsonAssert(Object actual, Configuration configuration) {
this(Path.create("", getPathPrefix(actual)), configuration, actual);
}
/**
* Moves comparison to given node. Second call navigates from the last position in the JSON.
*/
@NotNull
public JsonAssert node(@NotNull String node) {
return new JsonAssert(path.to(node), configuration, getNode(actual, node));
}
/**
* Allows to do multiple comparisons on a document like
*
* <code>
* assertThatJson("{\"test\":{\"a\":1, \"b\":2, \"c\":3}}").and(
* a -> a.node("test").isObject(),
* a -> a.node("test.b").isEqualTo(3)
* );
* </code>
*/
@NotNull
public JsonAssert and(@NotNull JsonAssertion... assertions) {
Arrays.stream(assertions).forEach(a -> a.doAssert(this));
return this;
}
/**
* Compares JSONs.
*/
@Override
@NotNull
public JsonAssert isEqualTo(@Nullable Object expected) {
Diff diff = Diff.create(expected, actual, "fullJson", path.asPrefix(), configuration);
String overridingErrorMessage = info.overridingErrorMessage();
if (!isNullOrEmpty(overridingErrorMessage) && !diff.similar()) {
failWithMessage(overridingErrorMessage);
} else {
diff.failIfDifferent(MessageFormatter.instance().format(info.description(), info.representation(), ""));
}
return this;
}
/**
* Asserts that given node is present and is of type object.
*
* @return MapAssert where the object is serialized as Map
*/
@NotNull
@SuppressWarnings("unchecked")
public JsonMapAssert isObject() {
Node node = assertType(OBJECT);
return new JsonMapAssert((Map<String, Object>) node.getValue(), path.asPrefix(), configuration)
.as("Different value found in node \"%s\"", path);
}
/**
* Asserts that given node is present and is of type number.
*/
@NotNull
public BigDecimalAssert isNumber() {
Node node = assertType(NUMBER);
return createBigDecimalAssert(node.decimalValue());
}
/**
* Asserts that the value is an integer. 1 is an integer 1.0, 1.1, 1e3, 1e0, 1e-3 is not.
*/
public BigIntegerAssert isIntegralNumber() {
Node node = internalMatcher().assertIntegralNumber();
return new BigIntegerAssert(node.decimalValue().toBigIntegerExact())
.as("Different value found in node \"%s\"", path);
}
/**
* Asserts that given node is present and is of type number or a string that can be parsed as a number.
*/
@NotNull
public BigDecimalAssert asNumber() {
internalMatcher().isPresent(NUMBER.getDescription());
Node node = getNode(actual, "");
if (node.getNodeType() == NUMBER) {
return createBigDecimalAssert(node.decimalValue());
} else if (node.getNodeType() == STRING) {
try {
return createBigDecimalAssert(new BigDecimal(node.asText()));
} catch (NumberFormatException e) {
failWithMessage("Node \"" + path + "\" can not be converted to number expected: <a number> but was: <"
+ quoteTextValue(node.getValue()) + ">.");
}
} else {
internalMatcher().failOnType(node, "number or string");
}
//noinspection DataFlowIssue
return null;
}
private BigDecimalAssert createBigDecimalAssert(BigDecimal value) {
return new BigDecimalAssert(value).as("Different value found in node \"%s\"", path);
}
private InternalMatcher internalMatcher() {
String description = mostRelevantDescription(info.description(), "Node \"" + path + "\"");
return new InternalMatcher(actualForMatcher, path.asPrefix(), "", configuration, description);
}
/**
* Asserts that given node is present and is of type array.
*
* @return
*/
@NotNull
public JsonListAssert isArray() {
Node node = assertType(ARRAY);
return new JsonListAssert((List<?>) node.getValue(), path.asPrefix(), configuration).as("Node \"%s\"", path);
}
/**
* Asserts that given node is present and is of type boolean.
*
* @return
*/
@NotNull
public BooleanAssert isBoolean() {
Node node = assertType(BOOLEAN);
return new BooleanAssert((Boolean) node.getValue()).as("Different value found in node \"%s\"", path);
}
/**
* Asserts that given node is present and is of type string.
*
* @return
*/
@NotNull
public StringAssert isString() {
Node node = assertType(STRING);
return new StringAssert((String) node.getValue()).as("Different value found in node \"%s\"", path);
}
@Override
@NotNull
public AbstractStringAssert<?> asString() {
return isString();
}
/**
* Asserts that given node is present and is null.
*
* @return
*/
@Override
public void isNull() {
assertType(NULL);
}
/**
* Asserts that given node is present and is URI.
*
* @return
*/
@NotNull
public UriAssert isUri() {
Node node = assertType(STRING);
return new UriAssert(URI.create((String) node.getValue())).as("Different value found in node \"%s\"", path);
}
/**
* Asserts that given node is present.
*/
@NotNull
public JsonAssert isPresent() {
internalMatcher().isPresent();
return this;
}
/**
* Asserts that given node is absent.
*/
public void isAbsent() {
internalMatcher().isAbsent();
}
/**
* Asserts that given node is present and is not null.
*/
@Override
@NotNull
public JsonAssert isNotNull() {
internalMatcher().isNotNull();
return this;
}
private Node assertType(Node.NodeType type) {
return internalMatcher().assertType(type);
}
/**
* JsonAssert that can be configured to prevent mistakes like
*
* <code>
* assertThatJson(...).isEqualsTo(...).when(...);
* </code>
*/
public static class ConfigurableJsonAssert extends JsonAssert {
// Want to pass to inPath to not parse twice.
private final Object originalActual;
ConfigurableJsonAssert(Path path, Configuration configuration, Object actual) {
super(path, configuration, actual);
this.originalActual = actual;
}
ConfigurableJsonAssert(Object actual, Configuration configuration) {
this(Path.create("", getPathPrefix(actual)), configuration, actual);
}
/**
* Adds comparison options.
*/
@NotNull
public ConfigurableJsonAssert when(@NotNull Option first, @NotNull Option... other) {
return withConfiguration(c -> c.when(first, other));
}
/**
* Adds path specific options.
*
* @see Configuration#when(PathsParam, ApplicableForPath...)
*/
@NotNull
public final ConfigurableJsonAssert when(@NotNull PathsParam object, @NotNull ApplicableForPath... actions) {
return withConfiguration(c -> c.when(object, actions));
}
/**
* Adds comparison options.
*/
@NotNull
public ConfigurableJsonAssert withOptions(@NotNull Option first, @NotNull Option... next) {
return withConfiguration(c -> c.withOptions(first, next));
}
/**
* Adds comparison options.
*/
@NotNull
public ConfigurableJsonAssert withOptions(@NotNull Collection<Option> optionsToAdd) {
return withConfiguration(c -> c.withOptions(optionsToAdd));
}
/**
* Allows to configure like this
* <code>
* assertThatJson(...)
* .withConfiguration(c -> c.withMatcher("positive", greaterThan(valueOf(0)))
* ....
* </code>
*/
@NotNull
public ConfigurableJsonAssert withConfiguration(
@NotNull Function<Configuration, Configuration> configurationFunction) {
Configuration newConfiguration = configurationFunction.apply(configuration);
newConfiguration = resolveJsonPaths(originalActual, newConfiguration);
return new ConfigurableJsonAssert(path, newConfiguration, actual);
}
/**
* Sets numerical comparison tolerance.
*
* @param tolerance
* @return
*/
@NotNull
public ConfigurableJsonAssert withTolerance(@Nullable BigDecimal tolerance) {
return withConfiguration(c -> c.withTolerance(tolerance));
}
/**
* Sets numerical comparison tolerance.
*
* @param tolerance
* @return
*/
@NotNull
public ConfigurableJsonAssert withTolerance(double tolerance) {
return withTolerance(BigDecimal.valueOf(tolerance));
}
/**
* Makes JsonUnit ignore the specified paths in the actual value. If the path matches,
* it's completely ignored. It may be missing, null or have any value
*
* @param pathsToBeIgnored
* @return
*/
@NotNull
public ConfigurableJsonAssert whenIgnoringPaths(@NotNull String... pathsToBeIgnored) {
return withConfiguration(c -> c.whenIgnoringPaths(pathsToBeIgnored));
}
/**
* Sets ignore placeholder.
*
* @param ignorePlaceholder
* @return
*/
@NotNull
public ConfigurableJsonAssert withIgnorePlaceholder(@NotNull String ignorePlaceholder) {
return withConfiguration(c -> c.withIgnorePlaceholder(ignorePlaceholder));
}
/**
* Adds a matcher to be used in ${json-unit.matches:matcherName} macro.
*
* @param matcherName
* @param matcher
* @return
*/
@NotNull
public ConfigurableJsonAssert withMatcher(@NotNull String matcherName, @NotNull Matcher<?> matcher) {
return withConfiguration(c -> c.withMatcher(matcherName, matcher));
}
/**
* Sets difference listener
*/
@NotNull
public ConfigurableJsonAssert withDifferenceListener(@NotNull DifferenceListener differenceListener) {
return withConfiguration(c -> c.withDifferenceListener(differenceListener));
}
@NotNull
public JsonAssert inPath(@NotNull String jsonPath) {
return new JsonAssert(JsonPathAdapter.inPath(originalActual, jsonPath), configuration);
}
// Following methods are here just to return ConfigurableJsonAssert instead of JsonAssert
@Override
@NotNull
public ConfigurableJsonAssert describedAs(@NotNull Description description) {
return (ConfigurableJsonAssert) super.describedAs(description);
}
@Override
@NotNull
public ConfigurableJsonAssert describedAs(@NotNull String description, Object... args) {
return (ConfigurableJsonAssert) super.describedAs(description, args);
}
@Override
@NotNull
public ConfigurableJsonAssert as(@NotNull Description description) {
return (ConfigurableJsonAssert) super.as(description);
}
@Override
@NotNull
public ConfigurableJsonAssert as(@NotNull String description, Object... args) {
return (ConfigurableJsonAssert) super.as(description, args);
}
}
}