1
+ package com .networknt .schema ;
2
+
3
+ import com .fasterxml .jackson .core .JsonProcessingException ;
4
+ import com .fasterxml .jackson .databind .ObjectMapper ;
5
+ import org .junit .jupiter .api .Test ;
6
+
7
+ import java .io .IOException ;
8
+ import java .util .Set ;
9
+ import java .util .stream .Collectors ;
10
+
11
+ import static org .hamcrest .MatcherAssert .assertThat ;
12
+ import static org .hamcrest .Matchers .contains ;
13
+ import static org .hamcrest .Matchers .empty ;
14
+
15
+ class DependentRequiredTest {
16
+
17
+ public static final String SCHEMA =
18
+ "{ " +
19
+ " \" $schema\" :\" http://json-schema.org/draft/2019-09/schema\" ," +
20
+ " \" type\" : \" object\" ," +
21
+ " \" properties\" : {" +
22
+ " \" optional\" : \" string\" ," +
23
+ " \" requiredWhenOptionalPresent\" : \" string\" " +
24
+ " }," +
25
+ " \" dependentRequired\" : {" +
26
+ " \" optional\" : [ \" requiredWhenOptionalPresent\" ]," +
27
+ " \" otherOptional\" : [ \" otherDependentRequired\" ]" +
28
+ " }" +
29
+ "}" ;
30
+
31
+ private static final JsonSchemaFactory factory = JsonSchemaFactory .getInstance (SpecVersion .VersionFlag .V201909 );
32
+ private static final JsonSchema schema = factory .getSchema (SCHEMA );
33
+ private static final ObjectMapper mapper = new ObjectMapper ();
34
+
35
+ @ Test
36
+ void shouldReturnNoErrorMessagesForObjectWithoutOptionalField () throws IOException {
37
+
38
+ Set <ValidationMessage > messages = whenValidate ("{}" );
39
+
40
+ assertThat (messages , empty ());
41
+ }
42
+
43
+ @ Test
44
+ void shouldReturnErrorMessageForObjectWithoutDependentRequiredField () throws IOException {
45
+
46
+ Set <ValidationMessage > messages = whenValidate ("{ \" optional\" : \" present\" }" );
47
+
48
+ assertThat (
49
+ messages .stream ().map (ValidationMessage ::getMessage ).collect (Collectors .toList ()),
50
+ contains ("$: has a missing property \" requiredWhenOptionalPresent\" which is dependent required because \" optional\" is present" ));
51
+ }
52
+
53
+ @ Test
54
+ void shouldReturnNoErrorMessagesForObjectWithOptionalAndDependentRequiredFieldSet () throws JsonProcessingException {
55
+
56
+ Set <ValidationMessage > messages =
57
+ whenValidate ("{ \" optional\" : \" present\" , \" requiredWhenOptionalPresent\" : \" present\" }" );
58
+
59
+ assertThat (messages , empty ());
60
+ }
61
+
62
+ private static Set <ValidationMessage > whenValidate (String content ) throws JsonProcessingException {
63
+ return schema .validate (mapper .readTree (content ));
64
+ }
65
+
66
+ }
0 commit comments