Skip to content

Commit 9446439

Browse files
chore: add more schema generation tests
1 parent 70fd1aa commit 9446439

10 files changed

+919
-345
lines changed
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
/*
2+
* Copyright 2019 VicTools.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.github.victools.jsonschema.generator;
18+
19+
import com.fasterxml.jackson.databind.JsonNode;
20+
import com.fasterxml.jackson.databind.ObjectMapper;
21+
import com.fasterxml.jackson.databind.node.ObjectNode;
22+
import java.io.IOException;
23+
import java.io.InputStream;
24+
import java.lang.reflect.Type;
25+
import java.math.BigDecimal;
26+
import java.math.RoundingMode;
27+
import java.net.URI;
28+
import java.nio.charset.StandardCharsets;
29+
import java.util.Arrays;
30+
import java.util.Collections;
31+
import java.util.HashMap;
32+
import java.util.Iterator;
33+
import java.util.List;
34+
import java.util.Map;
35+
import java.util.Optional;
36+
import java.util.Scanner;
37+
import junitparams.JUnitParamsRunner;
38+
import junitparams.Parameters;
39+
import junitparams.naming.TestCaseName;
40+
import org.junit.Assert;
41+
import org.junit.Test;
42+
import org.junit.runner.RunWith;
43+
import org.skyscreamer.jsonassert.JSONAssert;
44+
import org.skyscreamer.jsonassert.JSONCompareMode;
45+
46+
/**
47+
* Test for {@link SchemaGenerator} class.
48+
*/
49+
@RunWith(JUnitParamsRunner.class)
50+
public class SchemaGeneratorComplexTypesTest {
51+
52+
private static void populateTypeConfigPart(SchemaGeneratorTypeConfigPart<?> configPart, String descriptionPrefix) {
53+
configPart
54+
.withArrayMinItemsResolver(scope -> scope.isContainerType() ? 2 : null)
55+
.withArrayMaxItemsResolver(scope -> scope.isContainerType() ? 100 : null)
56+
.withArrayUniqueItemsResolver(scope -> scope.isContainerType() ? false : null)
57+
.withDefaultResolver(scope -> scope.getType().isInstanceOf(Number.class) ? 1 : null)
58+
.withDescriptionResolver(scope -> descriptionPrefix + scope.getSimpleTypeDescription())
59+
.withEnumResolver(scope -> scope.getType().isInstanceOf(Number.class) ? Arrays.asList(1, 2, 3, 4, 5) : null)
60+
.withEnumResolver(scope -> scope.getType().isInstanceOf(String.class) ? Arrays.asList("constant string value") : null)
61+
.withAdditionalPropertiesResolver(SchemaGeneratorComplexTypesTest::resolveAdditionalProperties)
62+
.withPatternPropertiesResolver(SchemaGeneratorComplexTypesTest::resolvePatternProperties)
63+
.withNumberExclusiveMaximumResolver(scope -> scope.getType().isInstanceOf(Number.class) ? BigDecimal.TEN.add(BigDecimal.ONE) : null)
64+
.withNumberExclusiveMinimumResolver(scope -> scope.getType().isInstanceOf(Number.class) ? BigDecimal.ZERO : null)
65+
.withNumberInclusiveMaximumResolver(scope -> scope.getType().isInstanceOf(Number.class) ? BigDecimal.TEN : null)
66+
.withNumberInclusiveMinimumResolver(scope -> scope.getType().isInstanceOf(Number.class) ? BigDecimal.ONE : null)
67+
.withNumberMultipleOfResolver(scope -> scope.getType().isInstanceOf(Number.class) ? BigDecimal.ONE : null)
68+
.withStringFormatResolver(scope -> scope.getType().isInstanceOf(String.class) ? "date" : null)
69+
.withStringMaxLengthResolver(scope -> scope.getType().isInstanceOf(String.class) ? 256 : null)
70+
.withStringMinLengthResolver(scope -> scope.getType().isInstanceOf(String.class) ? 1 : null)
71+
.withStringPatternResolver(scope -> scope.getType().isInstanceOf(String.class) ? "^.{1,256}$" : null)
72+
.withTitleResolver(scope -> scope.getSimpleTypeDescription());
73+
}
74+
75+
private static Type resolveAdditionalProperties(TypeScope scope) {
76+
if (scope.getType().isInstanceOf(TestClass2.class)) {
77+
return Void.class;
78+
}
79+
if (scope.getType().isInstanceOf(TestClass4.class)) {
80+
return scope.getTypeParameterFor(TestClass4.class, 1);
81+
}
82+
return null;
83+
}
84+
85+
private static Map<String, Type> resolvePatternProperties(TypeScope scope) {
86+
if (scope.getType().isInstanceOf(TestClass2.class)) {
87+
Map<String, Type> patternProperties = new HashMap<>();
88+
patternProperties.put("^generic.+$", scope.getTypeParameterFor(TestClass2.class, 0));
89+
return patternProperties;
90+
}
91+
if (scope.getType().isInstanceOf(TestClass4.class)) {
92+
return Collections.emptyMap();
93+
}
94+
return null;
95+
}
96+
97+
private static void populateConfigPart(SchemaGeneratorConfigPart<? extends MemberScope<?, ?>> configPart, String descriptionPrefix) {
98+
populateTypeConfigPart(configPart, descriptionPrefix);
99+
configPart
100+
.withNullableCheck(member -> !member.getName().startsWith("nested"))
101+
.withRequiredCheck(member -> member.getName().startsWith("nested"));
102+
}
103+
104+
Object parametersForTestGenerateSchema() {
105+
Module neutralModule = configBuilder -> configBuilder.with((javaType, context) -> {
106+
if (Integer.class == javaType.getErasedType()) {
107+
ObjectNode customNode = configBuilder.getObjectMapper()
108+
.createObjectNode()
109+
.put("$comment", "custom definition for Integer.class");
110+
return new CustomDefinition(customNode, false);
111+
}
112+
return null;
113+
});
114+
Module typeInGeneralModule = configBuilder -> populateTypeConfigPart(
115+
configBuilder.with(Option.FORBIDDEN_ADDITIONAL_PROPERTIES_BY_DEFAULT).forTypesInGeneral(), "for type in general: ");
116+
Module methodModule = configBuilder -> populateConfigPart(configBuilder.forMethods(), "looked-up from method: ");
117+
Module fieldModule = configBuilder -> populateConfigPart(configBuilder.forFields(), "looked-up from field: ");
118+
Module enumToStringModule = configBuilder -> configBuilder.with(Option.FLATTENED_ENUMS_FROM_TOSTRING);
119+
return new Object[][]{
120+
{"testclass1-FULL_DOCUMENTATION", OptionPreset.FULL_DOCUMENTATION, TestClass1.class, neutralModule},
121+
{"testclass1-FULL_DOCUMENTATION-typeattributes", OptionPreset.FULL_DOCUMENTATION, TestClass1.class, typeInGeneralModule},
122+
{"testclass1-JAVA_OBJECT-methodattributes", OptionPreset.JAVA_OBJECT, TestClass1.class, methodModule},
123+
{"testclass1-PLAIN_JSON-fieldattributes", OptionPreset.PLAIN_JSON, TestClass1.class, fieldModule},
124+
{"testclass2-array", OptionPreset.FULL_DOCUMENTATION, TestClass2[].class, neutralModule},
125+
{"testclass3-FULL_DOCUMENTATION", OptionPreset.FULL_DOCUMENTATION, TestClass3.class, neutralModule},
126+
{"testclass3-FULL_DOCUMENTATION-typeattributes", OptionPreset.FULL_DOCUMENTATION, TestClass3.class, typeInGeneralModule},
127+
{"testclass3-JAVA_OBJECT-methodattributes", OptionPreset.JAVA_OBJECT, TestClass3.class, methodModule},
128+
{"testclass3-PLAIN_JSON-fieldattributes", OptionPreset.PLAIN_JSON, TestClass3.class, fieldModule},
129+
{"testenum-PLAIN_JSON-default", OptionPreset.PLAIN_JSON, TestEnum.class, neutralModule},
130+
{"testenum-FULL_DOCUMENTATION-default", OptionPreset.FULL_DOCUMENTATION, TestEnum.class, neutralModule},
131+
{"testenum-PLAIN_JSON-viaToString", OptionPreset.PLAIN_JSON, TestEnum.class, enumToStringModule}
132+
};
133+
}
134+
135+
@Test
136+
@Parameters
137+
@TestCaseName(value = "{method}({0}) [{index}]")
138+
public void testGenerateSchema(String caseTitle, OptionPreset preset, Class<?> targetType, Module testModule) throws Exception {
139+
SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(new ObjectMapper(), preset);
140+
configBuilder.with(testModule);
141+
SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
142+
143+
JsonNode result = generator.generateSchema(targetType);
144+
// ensure that the generated definition keys are valid URIs without any characters requiring encoding
145+
JsonNode definitions = result.get(SchemaConstants.TAG_DEFINITIONS);
146+
if (definitions instanceof ObjectNode) {
147+
Iterator<String> definitionKeys = ((ObjectNode) definitions).fieldNames();
148+
while (definitionKeys.hasNext()) {
149+
String key = definitionKeys.next();
150+
Assert.assertEquals(key, new URI(key).toASCIIString());
151+
}
152+
}
153+
JSONAssert.assertEquals('\n' + result.toString() + '\n',
154+
loadResource(caseTitle + ".json"), result.toString(), JSONCompareMode.STRICT);
155+
}
156+
157+
private static String loadResource(String resourcePath) throws IOException {
158+
StringBuilder stringBuilder = new StringBuilder();
159+
try (InputStream inputStream = SchemaGeneratorComplexTypesTest.class
160+
.getResourceAsStream(resourcePath);
161+
Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
162+
while (scanner.hasNext()) {
163+
stringBuilder.append(scanner.nextLine()).append('\n');
164+
}
165+
}
166+
String fileAsString = stringBuilder.toString();
167+
return fileAsString;
168+
169+
}
170+
171+
private static class TestClass1 extends TestClass2<String> {
172+
173+
public static final Long CONSTANT = 5L;
174+
175+
private int primitiveValue;
176+
private Integer ignoredInternalValue;
177+
178+
public int getPrimitiveValue() {
179+
return this.primitiveValue;
180+
}
181+
182+
public <A extends B, B extends Number> void calculateSomething(A param0, B param1) {
183+
// nothing to do
184+
}
185+
186+
public boolean isSimpleTestClass() {
187+
return true;
188+
}
189+
}
190+
191+
private static class TestClass2<T> {
192+
193+
private T genericValue;
194+
public T[] genericArray;
195+
196+
public T getGenericValue() {
197+
return this.genericValue;
198+
}
199+
}
200+
201+
private static class TestClass3 {
202+
203+
private TestClass2<Long> nestedLong;
204+
private TestClass2<TestClass1[]> nestedClass1Array;
205+
private List<? extends TestClass2<Long>> nestedLongList;
206+
private TestClass4<Integer, String> class4;
207+
208+
public TestClass2<Long> getNestedLong() {
209+
return this.nestedLong;
210+
}
211+
212+
public TestClass2<TestClass1[]> getNestedClass1Array() {
213+
return this.nestedClass1Array;
214+
}
215+
216+
public List<? extends TestClass2<Long>> getNestedLongList() {
217+
return this.nestedLongList;
218+
}
219+
220+
public TestClass4<Integer, String> getClass4() {
221+
return this.class4;
222+
}
223+
}
224+
225+
private static class TestClass4<S, T> {
226+
227+
private TestClass2<TestClass2<T>> class2OfClass2OfT;
228+
public Optional<S> optionalS;
229+
public static final RoundingMode DEFAULT_ROUNDING_MODE = RoundingMode.HALF_UP;
230+
231+
public TestClass2<TestClass2<T>> getClass2OfClass2OfT() {
232+
return this.class2OfClass2OfT;
233+
}
234+
}
235+
236+
private static enum TestEnum {
237+
VALUE1, VALUE2, VALUE3;
238+
239+
@Override
240+
public String toString() {
241+
return "toString_" + this.name();
242+
}
243+
}
244+
}
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
/*
2+
* Copyright 2019 VicTools.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package com.github.victools.jsonschema.generator;
18+
19+
import com.fasterxml.classmate.ResolvedType;
20+
import com.fasterxml.jackson.databind.JsonNode;
21+
import com.fasterxml.jackson.databind.ObjectMapper;
22+
import com.fasterxml.jackson.databind.node.ObjectNode;
23+
import java.util.ArrayList;
24+
import java.util.Collection;
25+
import org.junit.Assert;
26+
import org.junit.Test;
27+
28+
/**
29+
* Test for {@link SchemaGenerator} class.
30+
*/
31+
public class SchemaGeneratorCustomDefinitionsTest {
32+
33+
@Test
34+
public void testGenerateSchema_CustomDefinition() throws Exception {
35+
CustomDefinitionProviderV2 customDefinitionProvider = (javaType, context) -> javaType.getErasedType() == Integer.class
36+
? new CustomDefinition(context.createDefinition(context.getTypeContext().resolve(String.class)))
37+
: null;
38+
SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(new ObjectMapper())
39+
.with(customDefinitionProvider)
40+
.build();
41+
SchemaGenerator generator = new SchemaGenerator(config);
42+
JsonNode result = generator.generateSchema(Integer.class);
43+
Assert.assertEquals(1, result.size());
44+
Assert.assertEquals(SchemaConstants.TAG_TYPE_STRING, result.get(SchemaConstants.TAG_TYPE).asText());
45+
}
46+
47+
@Test
48+
public void testGenerateSchema_CustomCollectionDefinition() throws Exception {
49+
final ObjectMapper objectMapper = new ObjectMapper();
50+
String accessProperty = "stream().findFirst().orElse(null)";
51+
CustomDefinitionProviderV2 customDefinitionProvider = (javaType, context) -> {
52+
if (!javaType.isInstanceOf(Collection.class)) {
53+
return null;
54+
}
55+
ResolvedType generic = context.getTypeContext().getContainerItemType(javaType);
56+
return new CustomDefinition(objectMapper.createObjectNode()
57+
.put(SchemaConstants.TAG_TYPE, SchemaConstants.TAG_TYPE_OBJECT)
58+
.set(SchemaConstants.TAG_PROPERTIES, objectMapper.createObjectNode()
59+
.set(accessProperty, context.makeNullable(context.createDefinition(generic)))));
60+
};
61+
SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(objectMapper)
62+
.with(customDefinitionProvider)
63+
.build();
64+
SchemaGenerator generator = new SchemaGenerator(config);
65+
JsonNode result = generator.generateSchema(ArrayList.class, String.class);
66+
Assert.assertEquals(2, result.size());
67+
Assert.assertEquals(SchemaConstants.TAG_TYPE_OBJECT, result.get(SchemaConstants.TAG_TYPE).asText());
68+
Assert.assertNotNull(result.get(SchemaConstants.TAG_PROPERTIES));
69+
Assert.assertNotNull(result.get(SchemaConstants.TAG_PROPERTIES).get(accessProperty));
70+
JsonNode accessPropertyType = result.get(SchemaConstants.TAG_PROPERTIES).get(accessProperty).get(SchemaConstants.TAG_TYPE);
71+
Assert.assertNotNull(accessPropertyType);
72+
Assert.assertEquals(SchemaConstants.TAG_TYPE_STRING, accessPropertyType.get(0).asText());
73+
Assert.assertEquals(SchemaConstants.TAG_TYPE_NULL, accessPropertyType.get(1).asText());
74+
}
75+
76+
@Test
77+
public void testGenerateSchema_CustomStandardDefinition() throws Exception {
78+
CustomDefinitionProviderV2 customDefinitionProvider = new CustomDefinitionProviderV2() {
79+
@Override
80+
public CustomDefinition provideCustomSchemaDefinition(ResolvedType javaType, SchemaGenerationContext context) {
81+
if (javaType.getErasedType() == Integer.class) {
82+
// using SchemaGenerationContext.createStandardDefinition() to avoid endless loop with this custom definition
83+
ObjectNode standardDefinition = context.createStandardDefinition(context.getTypeContext().resolve(Integer.class), this);
84+
standardDefinition.put("$comment", "custom override of Integer");
85+
return new CustomDefinition(standardDefinition);
86+
}
87+
return null;
88+
}
89+
};
90+
SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(new ObjectMapper())
91+
.with(customDefinitionProvider)
92+
.build();
93+
SchemaGenerator generator = new SchemaGenerator(config);
94+
JsonNode result = generator.generateSchema(Integer.class);
95+
Assert.assertEquals(2, result.size());
96+
Assert.assertEquals(SchemaConstants.TAG_TYPE_INTEGER, result.get(SchemaConstants.TAG_TYPE).asText());
97+
Assert.assertEquals("custom override of Integer", result.get("$comment").asText());
98+
}
99+
}

0 commit comments

Comments
 (0)