summaryrefslogtreecommitdiff
path: root/src/test/java/com/networknt/schema/DependentRequiredTest.java
blob: bbc3a95ab245266e9770d0ccd99eb09d880608a5 (plain)
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
package com.networknt.schema;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.empty;

class DependentRequiredTest {

    public static final String SCHEMA =
        "{ " +
            "   \"$schema\":\"https://json-schema.org/draft/2019-09/schema\"," +
            "   \"type\": \"object\"," +
            "   \"properties\": {" +
            "       \"optional\": \"string\"," +
            "       \"requiredWhenOptionalPresent\": \"string\"" +
            "   }," +
            "   \"dependentRequired\": {" +
            "       \"optional\": [ \"requiredWhenOptionalPresent\" ]," +
            "       \"otherOptional\": [ \"otherDependentRequired\" ]" +
            "   }" +
            "}";

    private static final JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V201909);
    private static final JsonSchema schema = factory.getSchema(SCHEMA);
    private static final ObjectMapper mapper = new ObjectMapper();

    @Test
    void shouldReturnNoErrorMessagesForObjectWithoutOptionalField() throws IOException {

        Set<ValidationMessage> messages = whenValidate("{}");

        assertThat(messages, empty());
    }

    @Test
    void shouldReturnErrorMessageForObjectWithoutDependentRequiredField() throws IOException {

        Set<ValidationMessage> messages = whenValidate("{ \"optional\": \"present\" }");

        assertThat(
            messages.stream().map(ValidationMessage::getMessage).collect(Collectors.toList()),
            contains("$: has a missing property 'requiredWhenOptionalPresent' which is dependent required because 'optional' is present"));
    }

    @Test
    void shouldReturnNoErrorMessagesForObjectWithOptionalAndDependentRequiredFieldSet() throws JsonProcessingException {

        Set<ValidationMessage> messages =
            whenValidate("{ \"optional\": \"present\", \"requiredWhenOptionalPresent\": \"present\" }");

        assertThat(messages, empty());
    }

    private static Set<ValidationMessage> whenValidate(String content) throws JsonProcessingException {
        return schema.validate(mapper.readTree(content));
    }

}