How to use JsonSchemaValidation method of com.consol.citrus.validation.json.schema.JsonSchemaValidation class

Best Citrus code snippet using com.consol.citrus.validation.json.schema.JsonSchemaValidation.JsonSchemaValidation

Source:JsonTextMessageValidator.java Github

copy

Full Screen

...28import com.consol.citrus.message.MessageType;29import com.consol.citrus.util.MessageUtils;30import com.consol.citrus.validation.AbstractMessageValidator;31import com.consol.citrus.validation.ValidationUtils;32import com.consol.citrus.validation.json.schema.JsonSchemaValidation;33import com.consol.citrus.validation.matcher.ValidationMatcherUtils;34import com.github.fge.jsonschema.core.report.ProcessingReport;35import com.jayway.jsonpath.JsonPath;36import com.jayway.jsonpath.ReadContext;37import net.minidev.json.JSONArray;38import net.minidev.json.JSONObject;39import net.minidev.json.parser.JSONParser;40import net.minidev.json.parser.ParseException;41import org.springframework.util.Assert;42import org.springframework.util.StringUtils;43/**44 * This message validator implementation is able to validate two JSON text objects. The order of JSON entries can differ45 * as specified in JSON protocol. Tester defines an expected control JSON text with optional ignored entries.46 *47 * JSONArray as well as nested JSONObjects are supported, too.48 *49 * Validator offers two different modes to operate. By default strict mode is set and the validator will also check the exact amount of50 * control object fields to match. No additional fields in received JSON data structure will be accepted. In soft mode validator51 * allows additional fields in received JSON data structure so the control JSON object can be a partial subset.52 *53 * @author Christoph Deppisch54 */55public class JsonTextMessageValidator extends AbstractMessageValidator<JsonMessageValidationContext> {56 /** Should also check exact amount of object fields */57 private boolean strict = JsonSettings.isStrict();58 /** Permissive mode to use on the Json parser */59 private int permissiveMode = JsonSettings.getPermissiveMoe();60 /** Schema validator */61 private JsonSchemaValidation jsonSchemaValidation = new JsonSchemaValidation();62 @Override63 @SuppressWarnings("unchecked")64 public void validateMessage(Message receivedMessage, Message controlMessage,65 TestContext context, JsonMessageValidationContext validationContext) {66 if (controlMessage == null || controlMessage.getPayload() == null) {67 log.debug("Skip message payload validation as no control message was defined");68 return;69 }70 log.debug("Start JSON message validation ...");71 if (validationContext.isSchemaValidationEnabled()) {72 jsonSchemaValidation.validate(receivedMessage, context, validationContext);73 }74 if (log.isDebugEnabled()) {75 log.debug("Received message:\n" + receivedMessage.print(context));76 log.debug("Control message:\n" + controlMessage.print(context));77 }78 String receivedJsonText = receivedMessage.getPayload(String.class);79 String controlJsonText = context.replaceDynamicContentInString(controlMessage.getPayload(String.class));80 try {81 if (!StringUtils.hasText(controlJsonText)) {82 log.debug("Skip message payload validation as no control message was defined");83 return;84 } else {85 Assert.isTrue(StringUtils.hasText(receivedJsonText), "Validation failed - " +86 "expected message contents, but received empty message!");87 }88 JSONParser parser = new JSONParser(permissiveMode);89 Object receivedJson = parser.parse(receivedJsonText);90 ReadContext readContext = JsonPath.parse(receivedJson);91 Object controlJson = parser.parse(controlJsonText);92 if (receivedJson instanceof JSONObject) {93 validateJson("$.", (JSONObject) receivedJson, (JSONObject) controlJson, validationContext, context, readContext);94 } else if (receivedJson instanceof JSONArray) {95 JSONObject tempReceived = new JSONObject();96 tempReceived.put("array", receivedJson);97 JSONObject tempControl = new JSONObject();98 tempControl.put("array", controlJson);99 validateJson("$.", tempReceived, tempControl, validationContext, context, readContext);100 } else {101 throw new CitrusRuntimeException("Unsupported json type " + receivedJson.getClass());102 }103 } catch (IllegalArgumentException e) {104 throw new ValidationException(String.format("Failed to validate JSON text:%n%s", receivedJsonText), e);105 } catch (ParseException e) {106 throw new CitrusRuntimeException("Failed to parse JSON text", e);107 }108 log.info("JSON message validation successful: All values OK");109 }110 /**111 * Find json schema repositories in test context.112 * @param context113 * @return114 */115 private List<JsonSchemaRepository> findSchemaRepositories(TestContext context) {116 return new ArrayList<>(context.getReferenceResolver().resolveAll(JsonSchemaRepository.class).values());117 }118 /**119 * Validates JSON text with comparison to expected control JSON object.120 * JSON entries can be ignored with ignore placeholder.121 *122 * @param elementName the current element name that is under verification in this method123 * @param receivedJson the received JSON text object.124 * @param controlJson the expected control JSON text.125 * @param validationContext the JSON message validation context.126 * @param context the current test context.127 * @param readContext the JSONPath read context.128 */129 @SuppressWarnings("rawtypes")130 public void validateJson(String elementName, JSONObject receivedJson, JSONObject controlJson, JsonMessageValidationContext validationContext, TestContext context, ReadContext readContext) {131 if (strict) {132 Assert.isTrue(controlJson.size() == receivedJson.size(),133 ValidationUtils.buildValueMismatchErrorMessage("Number of JSON entries not equal for element: '" + elementName + "'", controlJson.size(), receivedJson.size()));134 }135 for (Map.Entry<String, Object> controlJsonEntry : controlJson.entrySet()) {136 String controlKey = controlJsonEntry.getKey();137 Assert.isTrue(receivedJson.containsKey(controlKey),138 "Missing JSON entry: + '" + controlKey + "'");139 Object controlValue = controlJsonEntry.getValue();140 Object receivedValue = receivedJson.get(controlKey);141 // check if entry is ignored by placeholder142 if (isIgnored(controlKey, controlValue, receivedValue, validationContext.getIgnoreExpressions(), readContext)) {143 continue;144 }145 if (controlValue == null) {146 Assert.isTrue(receivedValue == null,147 ValidationUtils.buildValueMismatchErrorMessage("Values not equal for entry: '" + controlKey + "'",148 null, receivedValue));149 } else if (receivedValue != null) {150 if (ValidationMatcherUtils.isValidationMatcherExpression(controlValue.toString())) {151 ValidationMatcherUtils.resolveValidationMatcher(controlKey,152 receivedValue.toString(),153 controlValue.toString(), context);154 } else if (controlValue instanceof JSONObject) {155 Assert.isTrue(receivedValue instanceof JSONObject,156 ValidationUtils.buildValueMismatchErrorMessage("Type mismatch for JSON entry '" + controlKey + "'",157 JSONObject.class.getSimpleName(), receivedValue.getClass().getSimpleName()));158 validateJson(controlKey, (JSONObject) receivedValue,159 (JSONObject) controlValue, validationContext, context, readContext);160 } else if (controlValue instanceof JSONArray) {161 Assert.isTrue(receivedValue instanceof JSONArray,162 ValidationUtils.buildValueMismatchErrorMessage("Type mismatch for JSON entry '" + controlKey + "'",163 JSONArray.class.getSimpleName(), receivedValue.getClass().getSimpleName()));164 JSONArray jsonArrayControl = (JSONArray) controlValue;165 JSONArray jsonArrayReceived = (JSONArray) receivedValue;166 if (log.isDebugEnabled()) {167 log.debug("Validating JSONArray containing " + jsonArrayControl.size() + " entries");168 }169 if (strict) {170 Assert.isTrue(jsonArrayControl.size() == jsonArrayReceived.size(),171 ValidationUtils.buildValueMismatchErrorMessage("JSONArray size mismatch for JSON entry '" + controlKey + "'",172 jsonArrayControl.size(), jsonArrayReceived.size()));173 }174 for (int i = 0; i < jsonArrayControl.size(); i++) {175 if (jsonArrayControl.get(i).getClass().isAssignableFrom(JSONObject.class)) {176 Assert.isTrue(jsonArrayReceived.get(i).getClass().isAssignableFrom(JSONObject.class),177 ValidationUtils.buildValueMismatchErrorMessage("Value types not equal for entry: '" + jsonArrayControl.get(i) + "'",178 JSONObject.class.getName(), jsonArrayReceived.get(i).getClass().getName()));179 validateJson(controlKey, (JSONObject) jsonArrayReceived.get(i),180 (JSONObject) jsonArrayControl.get(i), validationContext, context, readContext);181 } else {182 Assert.isTrue(jsonArrayControl.get(i).equals(jsonArrayReceived.get(i)),183 ValidationUtils.buildValueMismatchErrorMessage("Values not equal for entry: '" + jsonArrayControl.get(i) + "'",184 jsonArrayControl.get(i), jsonArrayReceived.get(i)));185 }186 }187 } else {188 Assert.isTrue(controlValue.equals(receivedValue),189 ValidationUtils.buildValueMismatchErrorMessage("Values not equal for entry: '" + controlKey + "'",190 controlValue, receivedValue));191 }192 } else if (ValidationMatcherUtils.isValidationMatcherExpression(controlValue.toString())) {193 ValidationMatcherUtils.resolveValidationMatcher(controlKey,194 null,195 controlValue.toString(), context);196 } else {197 Assert.isTrue(!StringUtils.hasText(controlValue.toString()),198 ValidationUtils.buildValueMismatchErrorMessage(199 "Values not equal for entry '" + controlKey + "'", controlValue.toString(), null));200 }201 if (log.isDebugEnabled()) {202 log.debug("Validation successful for JSON entry '" + controlKey + "' (" + controlValue + ")");203 }204 }205 }206 /**207 * Checks if given element node is either on ignore list or208 * contains @ignore@ tag inside control message209 * @param controlKey210 * @param controlValue211 * @param receivedJson212 * @param ignoreExpressions213 * @param readContext214 * @return215 */216 public boolean isIgnored(String controlKey, Object controlValue, Object receivedJson, Set<String> ignoreExpressions, ReadContext readContext) {217 if (controlValue != null && controlValue.toString().trim().equals(CitrusSettings.IGNORE_PLACEHOLDER)) {218 if (log.isDebugEnabled()) {219 log.debug("JSON entry: '" + controlKey + "' is ignored by placeholder '" +220 CitrusSettings.IGNORE_PLACEHOLDER + "'");221 }222 return true;223 }224 for (String jsonPathExpression : ignoreExpressions) {225 Object foundEntry = readContext.read(jsonPathExpression);226 if (foundEntry instanceof JSONArray && ((JSONArray) foundEntry).contains(receivedJson)) {227 if (log.isDebugEnabled()) {228 log.debug("JSON entry: '" + controlKey + "' is ignored - skip value validation");229 }230 return true;231 }232 if (foundEntry != null && foundEntry.equals(receivedJson)) {233 if (log.isDebugEnabled()) {234 log.debug("JSON entry: '" + controlKey + "' is ignored - skip value validation");235 }236 return true;237 }238 }239 return false;240 }241 @Override242 protected Class<JsonMessageValidationContext> getRequiredValidationContextType() {243 return JsonMessageValidationContext.class;244 }245 @Override246 public boolean supportsMessageType(String messageType, Message message) {247 return messageType.equalsIgnoreCase(MessageType.JSON.name()) && MessageUtils.hasJsonPayload(message);248 }249 /**250 * Set the validator strict mode.251 * @param strict252 */253 public void setStrict(boolean strict) {254 this.strict = strict;255 }256 /**257 * Set the validator strict mode.258 * @param strict259 * @return this object for chaining260 */261 public JsonTextMessageValidator strict(boolean strict) {262 setStrict(strict);263 return this;264 }265 /**266 * Sets the json schema validation.267 * @param jsonSchemaValidation268 */269 void setJsonSchemaValidation(JsonSchemaValidation jsonSchemaValidation) {270 this.jsonSchemaValidation = jsonSchemaValidation;271 }272 /**273 * Sets the json schema validation.274 * @param jsonSchemaValidation275 * @return this object for chaining276 */277 public JsonTextMessageValidator jsonSchemaValidation(JsonSchemaValidation jsonSchemaValidation) {278 setJsonSchemaValidation(jsonSchemaValidation);279 return this;280 }281 /**282 * Sets the permissive mode.283 * @param permissiveMode284 */285 public void setPermissiveMode(int permissiveMode) {286 this.permissiveMode = permissiveMode;287 }288 /**289 * Sets the permissive mode290 * @param permissiveMode291 * @return this object for chaining292 */...

Full Screen

Full Screen

Source:JsonSchemaValidation.java Github

copy

Full Screen

...31/**32 * This class is responsible for the validation of json messages against json schemas / json schema repositories.33 * @since 2.7.334 */35public class JsonSchemaValidation {36 private final JsonSchemaFilter jsonSchemaFilter;37 /** Object Mapper to convert the message for validation*/38 private ObjectMapper objectMapper = new ObjectMapper();39 /**40 * Default constructor using default filter.41 */42 public JsonSchemaValidation() {43 this(new JsonSchemaFilter());44 }45 /**46 * Constructor using filter implementation.47 * @param jsonSchemaFilter48 */49 public JsonSchemaValidation(JsonSchemaFilter jsonSchemaFilter) {50 this.jsonSchemaFilter = jsonSchemaFilter;51 }52 /**53 * Validates the given message against a list of JsonSchemaRepositories under consideration of the actual context54 * @param message The message to be validated55 * @param schemaRepositories The schema repositories to be used for validation56 * @param validationContext The context of the validation to be used for the validation57 * @param applicationContext The application context to be used for the validation58 * @return A report holding the results of the validation59 */60 public ProcessingReport validate(Message message,61 List<JsonSchemaRepository> schemaRepositories,62 JsonMessageValidationContext validationContext,63 ApplicationContext applicationContext) {...

Full Screen

Full Screen

JsonSchemaValidation

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus;2import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;3import com.consol.citrus.validation.json.JsonSchemaValidation;4import org.testng.annotations.Test;5public class JsonSchemaValidationTest extends TestNGCitrusTestDesigner {6 public void configure() {7 variable("schema", "classpath:com/consol/citrus/validation/json/schema/person-schema.json");8 variable("payload", "classpath:com/consol/citrus/validation/json/schema/person.json");9 variable("invalidPayload", "classpath:com/consol/citrus/validation/json/schema/person-invalid.json");10 echo("Validating valid JSON payload");11 .jsonSchemaValidation()12 .schemaResource("${schema}")13 .ignoreUnknownFields(true)14 .ignoreMissingFields(true);15 validate(builder.build()).message().body("${payload}");16 echo("Validating invalid JSON payload");17 validate(builder.build()).message().body("${invalidPayload}");18 }19}20package com.consol.citrus;21import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;22import com.consol.citrus.validation.json.JsonSchemaValidation;23import org.testng.annotations.Test;24public class JsonSchemaValidationTest extends TestNGCitrusTestDesigner {25 public void configure() {26 variable("schema", "classpath:com/consol/citrus/validation/json/schema/person-schema.json");27 variable("payload", "classpath:com/consol/citrus/validation/json/schema/person.json");28 variable("invalidPayload", "classpath:com/consol/citrus/validation/json/schema/person-invalid.json");29 echo("Validating valid JSON payload");30 .jsonSchemaValidation()31 .schemaResource("${schema}")32 .ignoreUnknownFields(true)33 .ignoreMissingFields(true);34 validate(builder.build()).message().body("${payload}");35 echo("Validating invalid JSON payload");36 validate(builder.build()).message().body("${invalidPayload}");37 }38}

Full Screen

Full Screen

JsonSchemaValidation

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus.samples;2import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;3import org.springframework.core.io.ClassPathResource;4import org.testng.annotations.Test;5public class JsonSchemaValidation extends TestNGCitrusTestDesigner {6public void JsonSchemaValidation() {7http()8.client("httpClient")9.send()10.post()11.payload(new ClassPathResource("request.json"));12http()13.client("httpClient")14.receive()15.response(HttpStatus.OK)16.messageType(MessageType.JSON)17.validate(jsonSchema(new ClassPathResource("schema.json")));18}19}20package com.consol.citrus.samples;21import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;22import org.springframework.core.io.ClassPathResource;23import org.testng.annotations.Test;24public class JsonSchemaValidation extends TestNGCitrusTestDesigner {25public void JsonSchemaValidation() {26http()27.client("httpClient")28.send()29.post()30.payload(new ClassPathResource("request.json"));31http()32.client("httpClient")33.receive()34.response(HttpStatus.OK)35.messageType(MessageType.JSON)36.validate(jsonSchema(new ClassPathResource("schema.json")));37}38}39package com.consol.citrus.samples;40import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner;41import org.springframework.core.io.ClassPathResource;42import org.testng.annotations.Test;43public class JsonSchemaValidation extends TestNGCitrusTestDesigner {44public void JsonSchemaValidation() {45http()46.client("httpClient")47.send()48.post()49.payload(new ClassPathResource("request.json"));50http()51.client("httpClient")52.receive()53.response(HttpStatus.OK)54.messageType(MessageType.JSON)55.validate(jsonSchema(new

Full Screen

Full Screen

JsonSchemaValidation

Using AI Code Generation

copy

Full Screen

1package com.consol.citrus;2import com.consol.citrus.dsl.runner.TestRunner;3import com.consol.citrus.dsl.testng.TestNGCitrusTest;4import com.consol.citrus.http.client.HttpClient;5import com.consol.citrus.message.MessageType;6import com.consol.citrus.validation.json.schema.JsonSchemaValidation;7import org.springframework.beans.factory.annotation.Autowired;8import org.springframework.core.io.ClassPathResource;9import org.testng.annotations.Test;10public class JsonSchemaValidationIT extends TestNGCitrusTest {11 private HttpClient restClient;12 public void testJsonSchemaValidation() {13 description("Use JsonSchemaValidation to validate the response of the REST service");14 variable("path", "citrus:concat('api/', citrus:randomNumber(4))");15 variable("id", "citrus:randomNumber(4)");16 runner.run(http(httpActionBuilder -> httpActionBuilder17 .client(restClient)18 .send()19 .post("${path}")20 .contentType("application/json")21 .payload("{ \"id\": \"${id}\", \"message\": \"Hello World!\"}")));22 runner.run(http(httpActionBuilder -> httpActionBuilder23 .client(restClient)24 .receive()25 .response(HttpStatus.OK)26 .messageType(MessageType.JSON)27 .schemaValidation(true)28 .schema(new ClassPathResource("schema.json"))));29 }30}31package com.consol.citrus;32import com.consol.citrus.dsl.runner.TestRunner;33import com.consol.citrus.dsl.testng.TestNGCitrusTest;34import com.consol.citrus.http.client.HttpClient;35import com.consol.citrus.message.MessageType;36import com.consol.citrus.validation.json.schema.JsonSchemaValidation;37import org.springframework.beans.factory.annotation.Autowired;38import org.springframework.core.io.ClassPathResource;39import org.testng.annotations.Test;40public class JsonSchemaValidationIT extends TestNGCitrusTest {41 private HttpClient restClient;42 public void testJsonSchemaValidation() {43 description("Use JsonSchemaValidation to validate the response of the REST service");44 variable("path",

Full Screen

Full Screen

JsonSchemaValidation

Using AI Code Generation

copy

Full Screen

1public class JsonSchemaValidationTest extends TestNGCitrusTestDesigner {2 public void jsonSchemaValidationTest() {3 variable("jsonSchema", "${readFile('classpath:com/consol/citrus/validation/json/schema/JsonSchemaValidationTest.json')}");4 http(httpActionBuilder -> httpActionBuilder.client("httpClient")5 .send()6 .get("/test"));7 http(httpActionBuilder -> httpActionBuilder.client("httpClient")8 .receive()9 .response(HttpStatus.OK)10 .payload("{\"name\":\"Citrus\",\"version\":\"2.7.4\"}")11 .validate("$.name", "Citrus")12 .validate("$.version", "2.7.4")13 .validate("$.description", "Citrus is an open source test automation framework for testing SOA services and business processes.")14 .validate("$.license.name", "Apache License, Version 2.0")15 .validate("$.author.name", "Christian Schaefer")16 .validate("$.author.email", "

Full Screen

Full Screen

JsonSchemaValidation

Using AI Code Generation

copy

Full Screen

1public class 4 extends TestNGCitrusTestDesigner {2public void 4() {3variable("jsonSchema", "classpath:com/consol/citrus/validation/json/schema/4.json");4jsonSchemaValidator()5.schemaResource("${jsonSchema}");6jsonSchemaValidator()7.schemaResource("${jsonSchema}")8.reportValidationErrors(true);9jsonSchemaValidator()10.schemaResource("${jsonSchema}")11.reportValidationErrors(true)12.reportValidationErrors(true);13jsonSchemaValidator()14.schemaResource("${jsonSchema}")15.reportValidationErrors(true)16.reportValidationErrors(true)17.reportValidationErrors(true);18jsonSchemaValidator()19.schemaResource("${jsonSchema}")20.reportValidationErrors(true)21.reportValidationErrors(true)22.reportValidationErrors(true)23.reportValidationErrors(true);24}25}26public class 5 extends TestNGCitrusTestDesigner {27public void 5() {28variable("jsonSchema", "classpath:com/consol/citrus/validation/json/schema/5.json");29jsonSchemaValidator()30.schemaResource("${jsonSchema}");31jsonSchemaValidator()32.schemaResource("${jsonSchema}")33.reportValidationErrors(true);34jsonSchemaValidator()35.schemaResource("${jsonSchema}")36.reportValidationErrors(true)37.reportValidationErrors(true);38jsonSchemaValidator()39.schemaResource("${jsonSchema}")40.reportValidationErrors(true)41.reportValidationErrors(true)42.reportValidationErrors(true);43jsonSchemaValidator()44.schemaResource("${jsonSchema}")45.reportValidationErrors(true)46.reportValidationErrors(true)47.reportValidationErrors(true)48.reportValidationErrors(true);49}50}51public class 6 extends TestNGCitrusTestDesigner {52public void 6() {53variable("jsonSchema", "classpath:com/consol/citrus/validation/json/schema/6.json");54jsonSchemaValidator()55.schemaResource("${jsonSchema}");56jsonSchemaValidator()

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Citrus automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in JsonSchemaValidation

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful