Search in sources :

Example 6 with ValidationResult

use of com.linkedin.data.schema.validation.ValidationResult in project rest.li by linkedin.

the class TestValidator method testValidator.

public void testValidator(String schemaText, Object[][] input, Map<String, Class<? extends Validator>> validatorClassMap, String[] validatorCheckStrings, int tests) throws IOException, InstantiationException {
    DataSchema schema = dataSchemaFromString(schemaText);
    DataSchemaAnnotationValidator annotationValidator = new DataSchemaAnnotationValidator();
    annotationValidator.init(schema, validatorClassMap);
    if (debug)
        annotationValidator.setDebugMode(true);
    String annotationValidatorString = annotationValidator.toString();
    if (debug)
        out.println(annotationValidator);
    for (String checkString : validatorCheckStrings) {
        assertTrue(annotationValidatorString.contains(checkString));
    }
    for (Object[] row : input) {
        DataMap value = (DataMap) row[0];
        try {
            if ((tests & SCHEMA_VALIDATOR) != 0) {
                VisitedTrackingValidator visitedValidator = new VisitedTrackingValidator(annotationValidator);
                ValidationOptions validationOptions = new ValidationOptions(RequiredMode.CAN_BE_ABSENT_IF_HAS_DEFAULT, CoercionMode.NORMAL);
                ValidationResult result = ValidateDataAgainstSchema.validate(value.copy(), schema, validationOptions, visitedValidator);
                checkValidationResult(value, result, row, visitedValidator);
            }
            if ((tests & OBJECT_VALIDATOR) != 0) {
                VisitedTrackingValidator visitedValidator = new VisitedTrackingValidator(annotationValidator);
                ValidationOptions validationOptions = new ValidationOptions();
                ValidationResult result = ValidateDataAgainstSchema.validate(value.copy(), schema, validationOptions, visitedValidator);
                checkValidationResult(value, result, row, visitedValidator);
            }
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("unexpected exception", e);
        }
    }
}
Also used : DataSchema(com.linkedin.data.schema.DataSchema) TestUtil.dataMapFromString(com.linkedin.data.TestUtil.dataMapFromString) TestUtil.dataSchemaFromString(com.linkedin.data.TestUtil.dataSchemaFromString) ValidationOptions(com.linkedin.data.schema.validation.ValidationOptions) ValidationResult(com.linkedin.data.schema.validation.ValidationResult) DataMap(com.linkedin.data.DataMap)

Example 7 with ValidationResult

use of com.linkedin.data.schema.validation.ValidationResult in project rest.li by linkedin.

the class TestEmptyRecord method testEmpty.

@Test
public void testEmpty() {
    final EmptyRecord record = new EmptyRecord();
    final DataSchemaAnnotationValidator validator = new DataSchemaAnnotationValidator(record.schema());
    final ValidationResult result = ValidateDataAgainstSchema.validate(record.data(), record.schema(), new ValidationOptions(), validator);
    Assert.assertTrue(result.isValid());
}
Also used : DataSchemaAnnotationValidator(com.linkedin.data.schema.validator.DataSchemaAnnotationValidator) ValidationResult(com.linkedin.data.schema.validation.ValidationResult) ValidationOptions(com.linkedin.data.schema.validation.ValidationOptions) Test(org.testng.annotations.Test)

Example 8 with ValidationResult

use of com.linkedin.data.schema.validation.ValidationResult in project rest.li by linkedin.

the class TestExamplesGenerator method validateCollectionResponse.

private <T extends RecordTemplate> ValidationResult validateCollectionResponse(RestResponse response, Class<T> recordClass, ValidationOptions options) throws IOException {
    final DataMap respData = _codec.bytesToMap(response.getEntity().copyBytes());
    final CollectionResponse<T> collResp = new CollectionResponse<T>(respData, recordClass);
    final DataSchema recordSchema = DataTemplateUtil.getSchema(recordClass);
    for (T record : collResp.getElements()) {
        final ValidationResult valRet = ValidateDataAgainstSchema.validate(record.data(), recordSchema, options);
        if (!valRet.isValid()) {
            return valRet;
        }
    }
    return null;
}
Also used : RecordDataSchema(com.linkedin.data.schema.RecordDataSchema) DataSchema(com.linkedin.data.schema.DataSchema) CollectionResponse(com.linkedin.restli.common.CollectionResponse) ValidationResult(com.linkedin.data.schema.validation.ValidationResult) DataMap(com.linkedin.data.DataMap)

Example 9 with ValidationResult

use of com.linkedin.data.schema.validation.ValidationResult in project rest.li by linkedin.

the class TestExamplesGenerator method testExamples.

@Test
public void testExamples() throws IOException {
    final Map<String, ResourceModel> resources = buildResourceModels(ActionsResource.class, GreetingsResource.class, GroupsResource2.class, GroupContactsResource2.class, GroupMembershipsResource2.class, RootSimpleResource.class, CollectionUnderSimpleResource.class, SimpleResourceUnderCollectionResource.class, CustomTypesResource.class);
    final ResourceSchemaCollection resourceSchemas = ResourceSchemaCollection.loadOrCreateResourceSchema(resources);
    final DataSchemaResolver schemaResolver = new ClasspathResourceDataSchemaResolver(SchemaParserFactory.instance());
    final ValidationOptions valOptions = new ValidationOptions(RequiredMode.MUST_BE_PRESENT);
    ExampleRequestResponse capture;
    ValidationResult valRet;
    final ResourceSchema greetings = resourceSchemas.getResource("greetings");
    ExampleRequestResponseGenerator greetingsGenerator = new ExampleRequestResponseGenerator(greetings, schemaResolver);
    final ResourceSchema groups = resourceSchemas.getResource("groups");
    ExampleRequestResponseGenerator groupsGenerator = new ExampleRequestResponseGenerator(groups, schemaResolver);
    final ResourceSchema groupsContacts = resourceSchemas.getResource("groups.contacts");
    ExampleRequestResponseGenerator groupsContactsGenerator = new ExampleRequestResponseGenerator(Collections.singletonList(groups), groupsContacts, schemaResolver);
    final ResourceSchema greeting = resourceSchemas.getResource("greeting");
    ExampleRequestResponseGenerator greetingGenerator = new ExampleRequestResponseGenerator(greeting, schemaResolver);
    final ResourceSchema actions = resourceSchemas.getResource("actions");
    ExampleRequestResponseGenerator actionsGenerator = new ExampleRequestResponseGenerator(actions, schemaResolver);
    final ResourceSchema customTypes = resourceSchemas.getResource("customTypes");
    ExampleRequestResponseGenerator customTypesGenerator = new ExampleRequestResponseGenerator(customTypes, schemaResolver);
    List<ResourceSchema> subResources = resourceSchemas.getSubResources(greeting);
    final ResourceSchema subgreetings = subResources.get(0);
    ExampleRequestResponseGenerator subgreetingsGenerator = new ExampleRequestResponseGenerator(Collections.singletonList(greeting), subgreetings, schemaResolver);
    subResources = resourceSchemas.getSubResources(subgreetings);
    final ResourceSchema subsubgreeting = subResources.get(0);
    ExampleRequestResponseGenerator subsubgreetingGenerator = new ExampleRequestResponseGenerator(Arrays.asList(greeting, subgreetings), subsubgreeting, schemaResolver);
    capture = greetingsGenerator.method(ResourceMethod.GET);
    valRet = validateSingleResponse(capture.getResponse(), Greeting.class, valOptions);
    Assert.assertTrue(valRet.isValid(), valRet.getMessages().toString());
    capture = greetingsGenerator.method(ResourceMethod.CREATE);
    Assert.assertSame(capture.getResponse().getEntity().length(), 0);
    capture = greetingsGenerator.finder("search");
    valRet = validateCollectionResponse(capture.getResponse(), Greeting.class, valOptions);
    Assert.assertNull(valRet, (valRet == null ? null : valRet.getMessages().toString()));
    capture = groupsContactsGenerator.method(ResourceMethod.GET);
    valRet = validateSingleResponse(capture.getResponse(), GroupContact.class, valOptions);
    Assert.assertTrue(valRet.isValid(), valRet.getMessages().toString());
    capture = groupsGenerator.finder("search");
    String queryString = capture.getRequest().getURI().getQuery();
    Assert.assertTrue(queryString.contains("q=search"));
    Assert.assertTrue(queryString.contains("keywords="));
    Assert.assertTrue(queryString.contains("nameKeywords="));
    Assert.assertTrue(queryString.contains("groupID="));
    valRet = validateCollectionResponse(capture.getResponse(), Group.class, valOptions);
    Assert.assertNull(valRet, (valRet == null ? null : valRet.getMessages().toString()));
    capture = greetingsGenerator.action("purge", ResourceLevel.COLLECTION);
    final DataMap purgeResponse = DataMapUtils.readMap(capture.getResponse());
    Assert.assertTrue(purgeResponse.containsKey("value"));
    capture = greetingsGenerator.action("updateTone", ResourceLevel.ENTITY);
    valRet = validateCollectionResponse(capture.getResponse(), Greeting.class, valOptions);
    Assert.assertNull(valRet, (valRet == null ? null : valRet.getMessages().toString()));
    capture = groupsGenerator.action("sendTestAnnouncement", ResourceLevel.ENTITY);
    Assert.assertSame(capture.getResponse().getEntity().length(), 0);
    capture = greetingGenerator.method(ResourceMethod.GET);
    valRet = validateSingleResponse(capture.getResponse(), Greeting.class, valOptions);
    Assert.assertTrue(valRet.isValid(), valRet.getMessages().toString());
    RestRequest request = capture.getRequest();
    Assert.assertEquals(request.getURI(), URI.create("/greeting"));
    capture = greetingGenerator.method(ResourceMethod.UPDATE);
    Assert.assertSame(capture.getResponse().getEntity().length(), 0);
    request = capture.getRequest();
    Assert.assertEquals(request.getURI(), URI.create("/greeting"));
    valRet = validateSingleRequest(capture.getRequest(), Greeting.class, valOptions);
    Assert.assertTrue(valRet.isValid(), valRet.getMessages().toString());
    capture = greetingGenerator.method(ResourceMethod.PARTIAL_UPDATE);
    Assert.assertSame(capture.getResponse().getEntity().length(), 0);
    request = capture.getRequest();
    Assert.assertEquals(request.getURI(), URI.create("/greeting"));
    DataMap patchMap = _codec.bytesToMap(capture.getRequest().getEntity().copyBytes());
    checkPatchMap(patchMap);
    capture = greetingGenerator.method(ResourceMethod.DELETE);
    Assert.assertSame(capture.getResponse().getEntity().length(), 0);
    request = capture.getRequest();
    Assert.assertEquals(request.getURI(), URI.create("/greeting"));
    capture = greetingGenerator.action("exampleAction", ResourceLevel.ENTITY);
    DataMap exampleActionResponse = DataMapUtils.readMap(capture.getResponse());
    Assert.assertTrue(exampleActionResponse.containsKey("value"));
    request = capture.getRequest();
    Assert.assertTrue(validateUrlPath(request.getURI(), new String[] { "greeting" }));
    capture = subgreetingsGenerator.method(ResourceMethod.CREATE);
    Assert.assertSame(capture.getResponse().getEntity().length(), 0);
    request = capture.getRequest();
    Assert.assertEquals(request.getURI(), URI.create("/greeting/subgreetings"));
    valRet = validateSingleRequest(capture.getRequest(), Greeting.class, valOptions);
    Assert.assertTrue(valRet.isValid(), valRet.getMessages().toString());
    capture = subsubgreetingGenerator.method(ResourceMethod.GET);
    valRet = validateSingleResponse(capture.getResponse(), Greeting.class, valOptions);
    Assert.assertTrue(valRet.isValid(), valRet.getMessages().toString());
    request = capture.getRequest();
    Assert.assertTrue(validateUrlPath(request.getURI(), new String[] { "greeting", "subgreetings", null, "subsubgreeting" }));
    capture = subsubgreetingGenerator.method(ResourceMethod.UPDATE);
    Assert.assertSame(capture.getResponse().getEntity().length(), 0);
    request = capture.getRequest();
    Assert.assertTrue(validateUrlPath(request.getURI(), new String[] { "greeting", "subgreetings", null, "subsubgreeting" }));
    valRet = validateSingleRequest(capture.getRequest(), Greeting.class, valOptions);
    Assert.assertTrue(valRet.isValid(), valRet.getMessages().toString());
    capture = subsubgreetingGenerator.method(ResourceMethod.PARTIAL_UPDATE);
    Assert.assertSame(capture.getResponse().getEntity().length(), 0);
    request = capture.getRequest();
    Assert.assertTrue(validateUrlPath(request.getURI(), new String[] { "greeting", "subgreetings", null, "subsubgreeting" }));
    patchMap = _codec.bytesToMap(capture.getRequest().getEntity().copyBytes());
    checkPatchMap(patchMap);
    capture = subsubgreetingGenerator.method(ResourceMethod.DELETE);
    Assert.assertSame(capture.getResponse().getEntity().length(), 0);
    request = capture.getRequest();
    Assert.assertTrue(validateUrlPath(request.getURI(), new String[] { "greeting", "subgreetings", null, "subsubgreeting" }));
    capture = subsubgreetingGenerator.action("exampleAction", ResourceLevel.ENTITY);
    exampleActionResponse = DataMapUtils.readMap(capture.getResponse());
    Assert.assertTrue(exampleActionResponse.containsKey("value"));
    request = capture.getRequest();
    Assert.assertTrue(validateUrlPath(request.getURI(), new String[] { "greeting", "subgreetings", null, "subsubgreeting" }));
    capture = subgreetingsGenerator.finder("search");
    queryString = capture.getRequest().getURI().getQuery();
    Assert.assertTrue(queryString.contains("q=search"), queryString);
    Assert.assertTrue(queryString.contains("id:"), queryString);
    Assert.assertTrue(queryString.contains("message:"), queryString);
    Assert.assertTrue(queryString.contains("tone:"), queryString);
    capture = actionsGenerator.action("echoMessageArray", ResourceLevel.COLLECTION);
    final DataMap echoMessageArrayResponse = DataMapUtils.readMap(capture.getResponse());
    Assert.assertTrue(echoMessageArrayResponse.containsKey("value"));
    capture = actionsGenerator.action("echoToneArray", ResourceLevel.COLLECTION);
    final DataMap echoToneArrayResponse = DataMapUtils.readMap(capture.getResponse());
    Assert.assertTrue(echoToneArrayResponse.containsKey("value"));
    capture = actionsGenerator.action("echoStringArray", ResourceLevel.COLLECTION);
    final DataMap echoStringArrayResponse = DataMapUtils.readMap(capture.getResponse());
    Assert.assertTrue(echoStringArrayResponse.containsKey("value"));
    capture = customTypesGenerator.action("action", ResourceLevel.COLLECTION);
    DataMap requestMap = _codec.bytesToMap(capture.getRequest().getEntity().copyBytes());
    Assert.assertTrue(requestMap.containsKey("l"));
    Assert.assertEquals(requestMap.size(), 1);
    final DataMap customTypesActionResponse = DataMapUtils.readMap(capture.getResponse());
    Assert.assertTrue(customTypesActionResponse.containsKey("value"));
    Assert.assertEquals(customTypesActionResponse.size(), 1);
}
Also used : Greeting(com.linkedin.restli.examples.greetings.api.Greeting) Group(com.linkedin.restli.examples.groups.api.Group) ResourceSchema(com.linkedin.restli.restspec.ResourceSchema) ExampleRequestResponse(com.linkedin.restli.docgen.examplegen.ExampleRequestResponse) ByteString(com.linkedin.data.ByteString) ValidationOptions(com.linkedin.data.schema.validation.ValidationOptions) ValidationResult(com.linkedin.data.schema.validation.ValidationResult) GroupContact(com.linkedin.restli.examples.groups.api.GroupContact) DataMap(com.linkedin.data.DataMap) ExampleRequestResponseGenerator(com.linkedin.restli.docgen.examplegen.ExampleRequestResponseGenerator) RestRequest(com.linkedin.r2.message.rest.RestRequest) ClasspathResourceDataSchemaResolver(com.linkedin.data.schema.resolver.ClasspathResourceDataSchemaResolver) DataSchemaResolver(com.linkedin.data.schema.DataSchemaResolver) ResourceModel(com.linkedin.restli.internal.server.model.ResourceModel) ClasspathResourceDataSchemaResolver(com.linkedin.data.schema.resolver.ClasspathResourceDataSchemaResolver) Test(org.testng.annotations.Test)

Example 10 with ValidationResult

use of com.linkedin.data.schema.validation.ValidationResult in project rest.li by linkedin.

the class ValidationDemoResource method getAll.

@RestMethod.GetAll
public List<ValidationDemo> getAll(@ValidatorParam RestLiDataValidator validator) {
    List<ValidationDemo> validationDemos = new ArrayList<ValidationDemo>();
    // Generate entities with stringA fields that are too long
    for (int i = 0; i < 10; i++) {
        ValidationDemo.UnionFieldWithInlineRecord union = new ValidationDemo.UnionFieldWithInlineRecord();
        union.setMyEnum(myEnum.FOOFOO);
        validationDemos.add(new ValidationDemo().setStringA("This string is too long to pass validation.").setStringB("stringB").setUnionFieldWithInlineRecord(union));
    }
    // Validate outgoing data
    for (ValidationDemo entity : validationDemos) {
        ValidationResult result = validator.validateOutput(entity);
        check(!result.isValid());
        check(result.getMessages().toString().contains("/stringA :: length of \"This string is too long to pass validation.\" is out of range 1...10"));
    }
    // Fix entities
    for (ValidationDemo validationDemo : validationDemos) {
        validationDemo.setStringA("short str");
    }
    // Validate again
    for (ValidationDemo entity : validationDemos) {
        ValidationResult result = validator.validateOutput(entity);
        check(result.isValid());
    }
    return validationDemos;
}
Also used : ArrayList(java.util.ArrayList) ValidationResult(com.linkedin.data.schema.validation.ValidationResult) ValidationDemo(com.linkedin.restli.examples.greetings.api.ValidationDemo)

Aggregations

ValidationResult (com.linkedin.data.schema.validation.ValidationResult)38 Test (org.testng.annotations.Test)17 ValidationOptions (com.linkedin.data.schema.validation.ValidationOptions)16 DataMap (com.linkedin.data.DataMap)12 ValidationDemo (com.linkedin.restli.examples.greetings.api.ValidationDemo)11 RootBuilderWrapper (com.linkedin.restli.test.util.RootBuilderWrapper)8 DataSchema (com.linkedin.data.schema.DataSchema)7 ArrayList (java.util.ArrayList)7 RecordDataSchema (com.linkedin.data.schema.RecordDataSchema)6 HashMap (java.util.HashMap)6 Message (com.linkedin.data.message.Message)5 RestLiServiceException (com.linkedin.restli.server.RestLiServiceException)5 Map (java.util.Map)5 PatchRequest (com.linkedin.restli.common.PatchRequest)4 TestUtil.dataMapFromString (com.linkedin.data.TestUtil.dataMapFromString)3 TestUtil.dataSchemaFromString (com.linkedin.data.TestUtil.dataSchemaFromString)3 DataElement (com.linkedin.data.element.DataElement)3 SimpleDataElement (com.linkedin.data.element.SimpleDataElement)3 NamedDataSchema (com.linkedin.data.schema.NamedDataSchema)3 ResourceMethod (com.linkedin.restli.common.ResourceMethod)3