下面列出了org.apache.commons.lang3.reflect.TypeLiteral#net.javacrumbs.jsonunit.core.internal.Options 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
public Options convertValue(String value, Type type)
{
Type listOfOption = new TypeLiteral<List<Option>>() { }.getType();
Set options = new HashSet<>(fluentEnumListConverter.convertValue(value, listOfOption));
if (options.isEmpty())
{
return Options.empty();
}
Iterator<Option> iterator = options.iterator();
Options jsonComparisonOptions = new Options(iterator.next());
while (iterator.hasNext())
{
jsonComparisonOptions = jsonComparisonOptions.with(iterator.next());
}
return jsonComparisonOptions;
}
@Test
void testIsDataByJsonPathFromJsonEqualCheckMissmatches()
{
String json = ResourceUtils.loadResource(getClass(), "missmatches-actual-data.json");
String expected = ResourceUtils.loadResource(getClass(), "missmatches-expected-data.json");
jsonResponseValidationSteps.isDataByJsonPathFromJsonEqual(json, "$", expected,
new Options(Option.IGNORING_ARRAY_ORDER));
verify(softAssert).recordFailedAssertion("Different value found when comparing expected array element [0] to"
+ " actual element [0].");
verify(softAssert).recordFailedAssertion("Different keys found in node \"[0]\", missing: \"[0].missing_value\""
+ ", extra: \"[0].extra_value\",\"[0].line_terminator\", expected: <{\"different_value\":\"nf83u\""
+ ",\"missing_value\":\"2k3nf\",\"numbers_array\":[0, 1, 2]}> but was: <{\"different_value\":\"2ince\""
+ ",\"extra_value\":\"4ujeu\",\"line_terminator\":\"jfnse4\n4mn2j\nm38uff\n\",\"numbers_array\":"
+ "[0, -1]}>");
verify(softAssert).recordFailedAssertion("Different value found in node \"[0].different_value\", expected:"
+ " <\"nf83u\"> but was: <\"2ince\">.");
verify(softAssert).recordFailedAssertion("Array \"[0].numbers_array\" has different length, expected: <3>"
+ " but was: <2>.");
verify(softAssert).recordFailedAssertion("Array \"[0].numbers_array\" has different content. Missing values:"
+ " [1, 2], extra values: [-1], expected: <[0,1,2]> but was: <[0,-1]>");
verifyNoMoreInteractions(softAssert);
}
@Test
void getShouldReturnMultipleEmails() {
mailRepository.store(MailsFixutre.MAIL_1);
mailRepository.store(MailsFixutre.MAIL_2);
String response = when()
.get()
.then()
.contentType(ContentType.JSON)
.extract()
.asString();
assertThatJson(response)
.withOptions(new Options(Option.TREATING_NULL_AS_ABSENT, Option.IGNORING_ARRAY_ORDER))
.isEqualTo(JSON_MAILS_LIST);
}
private Function<String, Boolean> match(String jsonPath, String expectedData, Options options)
{
return actualData ->
{
JsonDiffMatcher jsonMatcher = new JsonDiffMatcher(attachmentPublisher, expectedData).withOptions(options)
.withTolerance(BigDecimal.ZERO);
jsonMatcher.matches(actualData);
String differences = jsonMatcher.getDifferences();
if (differences == null)
{
return softAssert.assertThat(format("Data by JSON path: %s is equal to '%s'", jsonPath, expectedData),
actualData, jsonMatcher);
}
StringBuilder matched = new StringBuilder("JSON documents are different:").append(LF);
Matcher matcher = DIFFERENCES_PATTERN.matcher(differences);
while (matcher.find())
{
String assertion = matcher.group().strip();
matched.append(assertion).append(LF);
softAssert.recordFailedAssertion(assertion);
}
String matchedDiff = matched.toString();
Validate.isTrue(matchedDiff.equals(differences),
"Unable to match all JSON diff entries from the diff text."
+ "%nExpected diff to match:%n%s%nActual matched diff:%n%s%n", differences, matchedDiff);
return false;
};
}
@ValueSource(strings = { "ignoring extra fields, ignoring_extra_array_items",
"IGNORING_EXTRA_FIELDS, IGNORING_EXTRA_ARRAY_ITEMS" })
@ParameterizedTest
void testConvertValue(String valueToConvert)
{
JsonComparisonOptionsConverter converter = new JsonComparisonOptionsConverter(
new FluentEnumListConverter(new FluentTrimmedEnumConverter()));
assertTrue(converter.convertValue(valueToConvert, Options.class).contains(Option.IGNORING_EXTRA_FIELDS));
assertTrue(converter.convertValue(valueToConvert, Options.class).contains(Option.IGNORING_EXTRA_ARRAY_ITEMS));
}
@ParameterizedTest
@MethodSource("defaultDataProvider")
void testIsDataByJsonPathEqual(String jsonPath, String expectedData)
{
when(httpTestContext.getJsonContext()).thenReturn(JSON);
testIsDataByJsonPathEqual(jsonPath, expectedData, expectedData, Options.empty());
}
@ParameterizedTest
@MethodSource("defaultDataProvider")
void testIsDataByJsonPathFromJsonEqual(String jsonPath, String expectedData)
{
jsonResponseValidationSteps.isDataByJsonPathFromJsonEqual(JSON, jsonPath, expectedData, Options.empty());
verifyJsonAssertion(jsonPath, expectedData, expectedData);
}
@Test
void testIsDataByJsonPathEqualIgnoringArrayOrder()
{
when(httpTestContext.getJsonContext()).thenReturn(JSON);
testIsDataByJsonPathEqual(ARRAY_PATH, "[2,1]", ARRAY_PATH_RESULT,
new Options(Option.IGNORING_ARRAY_ORDER));
}
@Test
void testIsDataByJsonPathFromJsonEqualCheckEmptyArrayMissmatch()
{
String json = "{ \"arrayKey\": [ { \"idKey\": \"q4jn0f8\", \"randValueKey\": \"i4t8ivC\"} ] }";
String expected = "[ { \"idKey\": \"b54Y8id\", \"randValueKey\": \"i4t8ivC\"} ]";
jsonResponseValidationSteps.isDataByJsonPathFromJsonEqual(json, "$.arrayKey.[?(@.idKey==\"b54Y8id\")]",
expected, Options.empty());
verify(softAssert).recordFailedAssertion("Array \"\" has different length, expected: <1> but was: <0>.");
verify(softAssert).recordFailedAssertion("Array \"\" has different content. Missing values: "
+ "[{\"idKey\":\"b54Y8id\",\"randValueKey\":\"i4t8ivC\"}], expected: <[{\"idKey\":\"b54Y8id\","
+ "\"randValueKey\":\"i4t8ivC\"}]> but was: <[]>");
verifyNoMoreInteractions(softAssert);
}
@Test
void testIsDataByJsonPathEqualIgnoringArrayOrderAndExtraArrayItems()
{
when(httpTestContext.getJsonContext()).thenReturn(JSON);
testIsDataByJsonPathEqual(ARRAY_PATH, "[2]", ARRAY_PATH_RESULT,
new Options(Option.IGNORING_ARRAY_ORDER, Option.IGNORING_EXTRA_ARRAY_ITEMS));
}
@Test
void testIsDataByJsonPathEqualWithPathNotFoundException()
{
when(httpTestContext.getJsonContext()).thenReturn(JSON);
String nonExistingPath = NON_EXISTING_PATH;
jsonResponseValidationSteps.isDataByJsonPathEqual(nonExistingPath, STRING_PATH_RESULT,
Options.empty());
verifyPathNotFoundExceptionRecording(nonExistingPath);
}
@Test
void shouldMatchWithOptions() {
final boolean result = JsonPatchMatcher.jsonEquals("[1,2]")
.withOptions(Options.empty().with(Option.IGNORING_ARRAY_ORDER))
.matches("[2,1]");
assertThat(result).isTrue();
}
@Test
void getShouldReturnPreviouslyStoredData() {
with().body(JSON_BEHAVIORS).put();
String response = when()
.get()
.then()
.contentType(ContentType.JSON)
.extract()
.asString();
assertThatJson(response)
.withOptions(new Options(Option.TREATING_NULL_AS_ABSENT, Option.IGNORING_ARRAY_ORDER))
.isEqualTo(JSON_BEHAVIORS);
}
@Test
void getShouldReturnPreviouslyStoredData() {
mailRepository.store(MailsFixutre.MAIL_1);
String response = when()
.get()
.then()
.contentType(ContentType.JSON)
.extract()
.asString();
assertThatJson(response)
.withOptions(new Options(Option.TREATING_NULL_AS_ABSENT, Option.IGNORING_ARRAY_ORDER))
.isEqualTo(JSON_MAIL);
}
@Test
void jacksonShouldSerializeMockSMTPBehaviorWithAllField() throws Exception {
String json = OBJECT_MAPPER.writeValueAsString(BEHAVIOR_ALL_FIELDS);
assertThatJson(json)
.withOptions(new Options(Option.TREATING_NULL_AS_ABSENT))
.isEqualTo(JSON_BEHAVIOR_ALL_FIELDS);
}
@Test
void jacksonShouldSerializeMockSMTPBehaviorWithCompulsoryField() throws Exception {
String json = OBJECT_MAPPER.writeValueAsString(BEHAVIOR_COMPULSORY_FIELDS);
assertThatJson(json)
.withOptions(new Options(Option.TREATING_NULL_AS_ABSENT))
.isEqualTo(JSON_BEHAVIOR_COMPULSORY_FIELDS);
}
@Test
void jacksonShouldSerializeMails() throws Exception {
String json = OBJECT_MAPPER.writeValueAsString(mails);
assertThatJson(json)
.withOptions(new Options(Option.TREATING_NULL_AS_ABSENT, Option.IGNORING_ARRAY_ORDER))
.isEqualTo(JSON_MAILS_LIST);
}
@Test
void jacksonShouldSerializeBehaviors() throws Exception {
String json = OBJECT_MAPPER.writeValueAsString(BEHAVIORS);
assertThatJson(json)
.withOptions(new Options(Option.TREATING_NULL_AS_ABSENT, Option.IGNORING_ARRAY_ORDER))
.isEqualTo(JSON_BEHAVIORS);
}
private void testIsDataByJsonPathEqual(String jsonPath, String expectedData, String actualData, Options options)
{
jsonResponseValidationSteps.isDataByJsonPathEqual(jsonPath, expectedData, options);
verifyJsonAssertion(jsonPath, expectedData, actualData);
}
public T withOptions(final Options options) {
this.configuration = configuration.withOptions(options);
return (T) this;
}
/**
* Checks if supplied JSON contains the expected data by given JSON path
* @param json JSON data
* @param jsonPath JSON path
* @param expectedData expected value of element by JSON path
* @param options JSON comparison options. Available options: TREATING_NULL_AS_ABSENT, IGNORING_ARRAY_ORDER,
* IGNORING_EXTRA_FIELDS, IGNORING_EXTRA_ARRAY_ITEMS, IGNORING_VALUES
* @return true JSON contains the expected data by given JSON path, otherwise - false
*/
@Then("a JSON element from '$json' by the JSON path '$jsonPath' is equal to '$expectedData'$options")
public boolean isDataByJsonPathFromJsonEqual(String json, String jsonPath, String expectedData, Options options)
{
return getDataByJsonPath(json, jsonPath, expectedData).map(match(jsonPath, expectedData, options))
.orElse(Boolean.FALSE).booleanValue();
}
/**
* Checks if JSON contains the expected data by given JSON path
* @param jsonPath JSON path
* @param expectedData expected value of element by JSON path
* @param options JSON comparison options. Available options: TREATING_NULL_AS_ABSENT, IGNORING_ARRAY_ORDER,
* IGNORING_EXTRA_FIELDS, IGNORING_EXTRA_ARRAY_ITEMS, IGNORING_VALUES
* @return true JSON contains the expected data by given JSON path, otherwise - false
*/
@Then("a JSON element by the JSON path '$jsonPath' is equal to '$expectedData'$options")
public boolean isDataByJsonPathEqual(String jsonPath, String expectedData, Options options)
{
return isDataByJsonPathFromJsonEqual(getActualJson(), jsonPath, expectedData, options);
}
AllureConfigurableJsonMatcher<T> withOptions(Options options);