forked from spring-projects/spring-framework
/
JsonPathExpectationsHelper.java
341 lines (311 loc) · 12 KB
/
JsonPathExpectationsHelper.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
/*
* Copyright 2002-2018 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
*
* 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 org.springframework.test.util;
import java.util.List;
import java.util.Map;
import com.jayway.jsonpath.JsonPath;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matcher;
import org.hamcrest.MatcherAssert;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* A helper class for applying assertions via JSON path expressions.
*
* <p>Based on the <a href="https://github.com/jayway/JsonPath">JsonPath</a>
* project: requiring version 0.9+, with 1.1+ strongly recommended.
*
* @author Rossen Stoyanchev
* @author Juergen Hoeller
* @author Craig Andrews
* @author Sam Brannen
* @since 3.2
*/
public class JsonPathExpectationsHelper {
private final String expression;
private final JsonPath jsonPath;
/**
* Construct a new {@code JsonPathExpectationsHelper}.
* @param expression the {@link JsonPath} expression; never {@code null} or empty
* @param args arguments to parameterize the {@code JsonPath} expression with,
* using formatting specifiers defined in {@link String#format(String, Object...)}
*/
public JsonPathExpectationsHelper(String expression, Object... args) {
Assert.hasText(expression, "expression must not be null or empty");
this.expression = String.format(expression, args);
this.jsonPath = JsonPath.compile(this.expression);
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert the resulting value with the given {@code Matcher}.
* @param content the JSON content
* @param matcher the matcher with which to assert the result
*/
@SuppressWarnings("unchecked")
public <T> void assertValue(String content, Matcher<T> matcher) {
T value = (T) evaluateJsonPath(content);
MatcherAssert.assertThat("JSON path \"" + this.expression + "\"", value, matcher);
}
/**
* An overloaded variant of {@link #assertValue(String, Matcher)} that also
* accepts a target type for the resulting value. This can be useful for
* matching numbers reliably for example coercing an integer into a double.
* @param content the JSON content
* @param matcher the matcher with which to assert the result
* @param targetType the expected type of the resulting value
* @since 4.3.3
*/
@SuppressWarnings("unchecked")
public <T> void assertValue(String content, Matcher<T> matcher, Class<T> targetType) {
T value = (T) evaluateJsonPath(content, targetType);
MatcherAssert.assertThat("JSON path \"" + this.expression + "\"", value, matcher);
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that the result is equal to the expected value.
* @param content the JSON content
* @param expectedValue the expected value
*/
public void assertValue(String content, @Nullable Object expectedValue) {
Object actualValue = evaluateJsonPath(content);
if ((actualValue instanceof List) && !(expectedValue instanceof List)) {
@SuppressWarnings("rawtypes")
List actualValueList = (List) actualValue;
if (actualValueList.isEmpty()) {
AssertionErrors.fail("No matching value at JSON path \"" + this.expression + "\"");
}
if (actualValueList.size() != 1) {
AssertionErrors.fail("Got a list of values " + actualValue +
" instead of the expected single value " + expectedValue);
}
actualValue = actualValueList.get(0);
}
else if (actualValue != null && expectedValue != null &&
!actualValue.getClass().equals(expectedValue.getClass())) {
try {
actualValue = evaluateJsonPath(content, expectedValue.getClass());
}
catch (AssertionError error) {
String message = String.format(
"At JSON path \"%s\", value <%s> of type <%s> cannot be converted to type <%s>",
this.expression, actualValue, ClassUtils.getDescriptiveType(actualValue),
ClassUtils.getDescriptiveType(expectedValue));
throw new AssertionError(message, error.getCause());
}
}
AssertionErrors.assertEquals("JSON path \"" + this.expression + "\"", expectedValue, actualValue);
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that the resulting value is a {@link String}.
* @param content the JSON content
* @since 4.2.1
*/
public void assertValueIsString(String content) {
Object value = assertExistsAndReturn(content);
MatcherAssert.assertThat(failureReason("a string", value), value, CoreMatchers.instanceOf(String.class));
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that the resulting value is a {@link Boolean}.
* @param content the JSON content
* @since 4.2.1
*/
public void assertValueIsBoolean(String content) {
Object value = assertExistsAndReturn(content);
MatcherAssert.assertThat(failureReason("a boolean", value), value, CoreMatchers.instanceOf(Boolean.class));
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that the resulting value is a {@link Number}.
* @param content the JSON content
* @since 4.2.1
*/
public void assertValueIsNumber(String content) {
Object value = assertExistsAndReturn(content);
MatcherAssert.assertThat(failureReason("a number", value), value, CoreMatchers.instanceOf(Number.class));
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that the resulting value is an array.
* @param content the JSON content
*/
public void assertValueIsArray(String content) {
Object value = assertExistsAndReturn(content);
MatcherAssert.assertThat(failureReason("an array", value), value, CoreMatchers.instanceOf(List.class));
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that the resulting value is a {@link Map}.
* @param content the JSON content
* @since 4.2.1
*/
public void assertValueIsMap(String content) {
Object value = assertExistsAndReturn(content);
MatcherAssert.assertThat(failureReason("a map", value), value, CoreMatchers.instanceOf(Map.class));
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that a non-null value, possibly an empty array or map, exists
* at the given path.
* <p>Note that if the JSON path expression is not
* {@linkplain JsonPath#isDefinite() definite}, this method asserts
* that the list of values at the given path is not <em>empty</em>.
* @param content the JSON content
*/
public void exists(String content) {
assertExistsAndReturn(content);
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that a non-null value does not exist at the given path.
* <p>Note that if the JSON path expression is not
* {@linkplain JsonPath#isDefinite() definite}, this method asserts
* that the list of values at the given path is <em>empty</em>.
* @param content the JSON content
*/
public void doesNotExist(String content) {
Object value;
try {
value = evaluateJsonPath(content);
}
catch (AssertionError ex) {
return;
}
String reason = failureReason("no value", value);
if (pathIsIndefinite() && value instanceof List) {
AssertionErrors.assertTrue(reason, ((List<?>) value).isEmpty());
}
else {
AssertionErrors.assertTrue(reason, (value == null));
}
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that an empty value exists at the given path.
* <p>For the semantics of <em>empty</em>, consult the Javadoc for
* {@link ObjectUtils#isEmpty(Object)}.
* @param content the JSON content
*/
public void assertValueIsEmpty(String content) {
Object value = evaluateJsonPath(content);
AssertionErrors.assertTrue(failureReason("an empty value", value), ObjectUtils.isEmpty(value));
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that a non-empty value exists at the given path.
* <p>For the semantics of <em>empty</em>, consult the Javadoc for
* {@link ObjectUtils#isEmpty(Object)}.
* @param content the JSON content
*/
public void assertValueIsNotEmpty(String content) {
Object value = evaluateJsonPath(content);
AssertionErrors.assertTrue(failureReason("a non-empty value", value), !ObjectUtils.isEmpty(value));
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that a value, possibly {@code null}, exists.
* <p>If the JSON path expression is not
* {@linkplain JsonPath#isDefinite() definite}, this method asserts
* that the list of values at the given path is not <em>empty</em>.
* @param content the JSON content
* @since 5.0.3
*/
public void hasJsonPath(String content) {
Object value = evaluateJsonPath(content);
if (pathIsIndefinite() && value instanceof List) {
String message = "No values for JSON path \"" + this.expression + "\"";
AssertionErrors.assertTrue(message, !((List<?>) value).isEmpty());
}
}
/**
* Evaluate the JSON path expression against the supplied {@code content}
* and assert that a value, including {@code null} values, does not exist
* at the given path.
* <p>If the JSON path expression is not
* {@linkplain JsonPath#isDefinite() definite}, this method asserts
* that the list of values at the given path is <em>empty</em>.
* @param content the JSON content
* @since 5.0.3
*/
public void doesNotHaveJsonPath(String content) {
Object value;
try {
value = evaluateJsonPath(content);
}
catch (AssertionError ex) {
return;
}
if (pathIsIndefinite() && value instanceof List) {
AssertionErrors.assertTrue(failureReason("no values", value), ((List<?>) value).isEmpty());
}
else {
AssertionErrors.fail(failureReason("no value", value));
}
}
private String failureReason(String expectedDescription, @Nullable Object value) {
return String.format("Expected %s at JSON path \"%s\" but found: %s", expectedDescription, this.expression,
ObjectUtils.nullSafeToString(StringUtils.quoteIfString(value)));
}
/**
* Evaluate the JSON path and return the resulting value.
* @param content the content to evaluate against
* @return the result of the evaluation
* @throws AssertionError if the evaluation fails
*/
@Nullable
public Object evaluateJsonPath(String content) {
try {
return this.jsonPath.read(content);
}
catch (Throwable ex) {
throw new AssertionError("No value at JSON path \"" + this.expression + "\"", ex);
}
}
/**
* Variant of {@link #evaluateJsonPath(String)} with a target type.
* <p>This can be useful for matching numbers reliably for example coercing an
* integer into a double.
* @param content the content to evaluate against
* @return the result of the evaluation
* @throws AssertionError if the evaluation fails
*/
public Object evaluateJsonPath(String content, Class<?> targetType) {
try {
return JsonPath.parse(content).read(this.expression, targetType);
}
catch (Throwable ex) {
String message = "No value at JSON path \"" + this.expression + "\"";
throw new AssertionError(message, ex);
}
}
@Nullable
private Object assertExistsAndReturn(String content) {
Object value = evaluateJsonPath(content);
String reason = "No value at JSON path \"" + this.expression + "\"";
AssertionErrors.assertTrue(reason, value != null);
if (pathIsIndefinite() && value instanceof List) {
AssertionErrors.assertTrue(reason, !((List<?>) value).isEmpty());
}
return value;
}
private boolean pathIsIndefinite() {
return !this.jsonPath.isDefinite();
}
}