Repository: victools/jsonschema-generator
Pull request #72 (2020-04-10 21:26:57)

Improve allOf clean-up


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 162b1a3..6d92ffa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,7 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 - Alternative `SchemaGenerationConfigPart.withInstanceAttributeOverride(InstanceAttributeOverrideV2)` with access to `SchemaGenerationContext`
 
 #### Changed
-- Enhance `Option.ALLOF_CLEANUP_AT_THE_END` to also reduce `allOf` if multiple parts have the same attributes but with equal values
+- Enhance `Option.ALLOF_CLEANUP_AT_THE_END` to also reduce `allOf` if multiple parts have the same attributes but with equal values (except for `if` tags)
 - Providing access to the `SchemaGenerationContext` when invoking `TypeAttributeOverrideV2` (potentially BREAKING change in case of lambda usage)
 
 #### Deprecated
diff --git a/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/SchemaGenerator.java b/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/SchemaGenerator.java
index 5db898a..d6ca642 100644
--- a/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/SchemaGenerator.java
+++ b/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/SchemaGenerator.java
@@ -316,24 +316,44 @@ public class SchemaGenerator {
                 .map(part -> (ObjectNode) part)
                 .collect(Collectors.toList());
 
-        final ObjectNode schemaObjectNode = (ObjectNode) schemaNode;
-        final SchemaVersion schemaVersion = this.config.getSchemaVersion();
-        if (schemaVersion == SchemaVersion.DRAFT_7) {
+        // collect all defined attributes from the separate parts and check whether there are incompatible differences
+        Map<String, List<JsonNode>> fieldsFromAllParts = Stream.concat(Stream.of(schemaNode), parts.stream())
+                .flatMap(part -> StreamSupport.stream(((Iterable<Map.Entry<String, JsonNode>>) () -> part.fields()).spliterator(), false))
+                .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
+        if (this.config.getSchemaVersion() == SchemaVersion.DRAFT_7
+                && fieldsFromAllParts.containsKey(this.config.getKeyword(SchemaKeyword.TAG_REF))) {
             // in Draft 7, any other attributes besides the $ref keyword were ignored
-            String refKeyword = SchemaKeyword.TAG_REF.forVersion(schemaVersion);
-            if (schemaObjectNode.has(refKeyword) || parts.stream().anyMatch(part -> part.has(refKeyword))) {
+            return;
+        }
+        String ifTagName = this.config.getKeyword(SchemaKeyword.TAG_IF);
+        for (Map.Entry<String, List<JsonNode>> fieldEntries : fieldsFromAllParts.entrySet()) {
+            if (fieldEntries.getValue().size() == 1) {
+                // no conflicts, no further checks
+                continue;
+            }
+            if (ifTagName.equals(fieldEntries.getKey())) {
+                // "if"/"then"/"else" tags should remain isolated in their sub-schemas
+                return;
+            }
+            int offset;
+            if (!allOfTagName.equals(fieldEntries.getKey())) {
+                offset = 0;
+            } else if (fieldEntries.getValue().size() == 2) {
+                // we can ignore the "allOf" tag in the target node (the one we are trying to remove here)
+                continue;
+            } else {
+                offset = 1;
+            }
+            if (!fieldEntries.getValue().stream().skip(offset + 1).allMatch(fieldEntries.getValue().get(offset)::equals)) {
+                // different values for the same tag: be conservative for now and not merge anything
+                // later, we may want to decide based on the tag how to merge them (e.g. take the highest "minLength" and the lowest "maximum")
                 return;
             }
         }
-        // collect all defined attributes from the separate parts and check whether there are incompatible differences
-        Map<String, List<Map.Entry<String, JsonNode>>> fieldsFromAllParts = Stream.concat(Stream.of(schemaObjectNode), parts.stream())
-                .flatMap(part -> StreamSupport.stream(((Iterable<Map.Entry<String, JsonNode>>) () -> part.fields()).spliterator(), false))
-                .collect(Collectors.groupingBy(Map.Entry::getKey));
-        if (fieldsFromAllParts.values().stream().allMatch(entries -> entries.subList(1, entries.size()).stream().allMatch(entries.get(0)::equals))) {
-            // all attributes are either distinct or have equal values in all occurrences
-            schemaObjectNode.remove(allOfTagName);
-            parts.forEach(schemaObjectNode::setAll);
-        }
+        // all attributes are either distinct or have equal values in all occurrences
+        ObjectNode schemaObjectNode = (ObjectNode) schemaNode;
+        schemaObjectNode.remove(allOfTagName);
+        parts.forEach(schemaObjectNode::setAll);
     }
 
     /**
diff --git a/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/SchemaKeyword.java b/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/SchemaKeyword.java
index ba1ee14..d2950df 100644
--- a/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/SchemaKeyword.java
+++ b/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/SchemaKeyword.java
@@ -72,7 +72,11 @@ public enum SchemaKeyword {
 
     TAG_ITEMS_MIN("minItems"),
     TAG_ITEMS_MAX("maxItems"),
-    TAG_ITEMS_UNIQUE("uniqueItems");
+    TAG_ITEMS_UNIQUE("uniqueItems"),
+
+    TAG_IF("if"),
+    TAG_THEN("then"),
+    TAG_ELSE("else");
 
     private final Function<SchemaVersion, String> valueProvider;
 
diff --git a/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/impl/module/EnumModule.java b/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/impl/module/EnumModule.java
index 9912338..5ccc841 100644
--- a/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/impl/module/EnumModule.java
+++ b/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/impl/module/EnumModule.java
@@ -17,7 +17,6 @@
 package com.github.victools.jsonschema.generator.impl.module;
 
 import com.fasterxml.classmate.ResolvedType;
-import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import com.github.victools.jsonschema.generator.CustomDefinition;
 import com.github.victools.jsonschema.generator.CustomDefinitionProviderV2;
@@ -87,7 +86,7 @@ public class EnumModule implements Module {
             builder.forFields()
                     .withIgnoreCheck(field -> field.getRawMember().isEnumConstant());
         } else {
-            builder.with(new EnumAsStringDefinitionProvider(builder.getObjectMapper(), this.enumConstantToString));
+            builder.forTypesInGeneral().withCustomDefinitionProvider(new EnumAsStringDefinitionProvider(this.enumConstantToString));
         }
     }
 
@@ -131,26 +130,23 @@ public class EnumModule implements Module {
      */
     private static class EnumAsStringDefinitionProvider implements CustomDefinitionProviderV2 {
 
-        private final ObjectMapper objectMapper;
         private final Function<Enum<?>, String> enumConstantToString;
 
         /**
-         * Constructor setting the given object mapper for later use as ObjectNode prodiver.
+         * Constructor.
          *
-         * @param objectMapper object node provider
          * @param enumConstantToString how to derive a plain string representation from an enum constant value
          */
-        EnumAsStringDefinitionProvider(ObjectMapper objectMapper, Function<Enum<?>, String> enumConstantToString) {
-            this.objectMapper = objectMapper;
+        EnumAsStringDefinitionProvider(Function<Enum<?>, String> enumConstantToString) {
             this.enumConstantToString = enumConstantToString;
         }
 
         @Override
         public CustomDefinition provideCustomSchemaDefinition(ResolvedType javaType, SchemaGenerationContext context) {
             if (javaType.isInstanceOf(Enum.class)) {
-                ObjectNode customNode = this.objectMapper.createObjectNode()
+                ObjectNode customNode = context.getGeneratorConfig().createObjectNode()
                         .put(context.getKeyword(SchemaKeyword.TAG_TYPE), context.getKeyword(SchemaKeyword.TAG_TYPE_STRING));
-                new AttributeCollector(this.objectMapper)
+                new AttributeCollector(context.getGeneratorConfig().getObjectMapper())
                         .setEnum(customNode, EnumModule.extractEnumValues(javaType, this.enumConstantToString), context);
                 return new CustomDefinition(customNode);
             }
diff --git a/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/impl/module/SimpleTypeModule.java b/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/impl/module/SimpleTypeModule.java
index 0434c31..6187d40 100644
--- a/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/impl/module/SimpleTypeModule.java
+++ b/jsonschema-generator/src/main/java/com/github/victools/jsonschema/generator/impl/module/SimpleTypeModule.java
@@ -17,7 +17,6 @@
 package com.github.victools.jsonschema.generator.impl.module;
 
 import com.fasterxml.classmate.ResolvedType;
-import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import com.github.victools.jsonschema.generator.CustomDefinition;
 import com.github.victools.jsonschema.generator.CustomDefinitionProviderV2;
@@ -196,9 +195,8 @@ public class SimpleTypeModule implements Module {
                 .withNullableCheck(this::isNullableType);
         builder.forTypesInGeneral()
                 .withAdditionalPropertiesResolver(this::resolveAdditionalProperties)
-                .withPatternPropertiesResolver(this::resolvePatternProperties);
-
-        builder.with(new SimpleTypeDefinitionProvider(builder.getObjectMapper()));
+                .withPatternPropertiesResolver(this::resolvePatternProperties)
+                .withCustomDefinitionProvider(new SimpleTypeDefinitionProvider());
     }
 
     /**
@@ -236,17 +234,6 @@ public class SimpleTypeModule implements Module {
      */
     private class SimpleTypeDefinitionProvider implements CustomDefinitionProviderV2 {
 
-        private final ObjectMapper objectMapper;
-
-        /**
-         * Constructor setting the object mapper to use for creating a custom schema definition for later use.
-         *
-         * @param objectMapper supplier for object and array nodes for the JSON structure being generated
-         */
-        SimpleTypeDefinitionProvider(ObjectMapper objectMapper) {
-            this.objectMapper = objectMapper;
-        }
-
         @Override
         public CustomDefinition provideCustomSchemaDefinition(ResolvedType javaType, SchemaGenerationContext context) {
             if (!javaType.getTypeParameters().isEmpty()) {
@@ -257,7 +244,7 @@ public class SimpleTypeModule implements Module {
                 return null;
             }
             // create fixed JSON schema definition, containing only the corresponding "type" attribute
-            ObjectNode customSchema = this.objectMapper.createObjectNode();
+            ObjectNode customSchema = context.getGeneratorConfig().createObjectNode();
             if (jsonSchemaTypeValue != SchemaKeyword.TAG_TYPE_NULL) {
                 customSchema.put(context.getKeyword(SchemaKeyword.TAG_TYPE), context.getKeyword(jsonSchemaTypeValue));
             }


Test patch:
diff --git a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/AbstractTypeAwareTest.java b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/AbstractTypeAwareTest.java
index 946ab45..b554bd0 100644
--- a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/AbstractTypeAwareTest.java
+++ b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/AbstractTypeAwareTest.java
@@ -20,6 +20,7 @@ import com.fasterxml.classmate.ResolvedType;
 import com.fasterxml.classmate.ResolvedTypeWithMembers;
 import com.fasterxml.classmate.members.ResolvedField;
 import com.fasterxml.classmate.members.ResolvedMethod;
+import com.fasterxml.jackson.databind.ObjectMapper;
 import com.github.victools.jsonschema.generator.impl.TypeContextFactory;
 import java.util.stream.Stream;
 import org.mockito.Mockito;
@@ -49,6 +50,10 @@ public class AbstractTypeAwareTest {
         this.testClassMembers = typeContext.resolveWithMembers(resolvedTestClass);
         this.context = Mockito.mock(SchemaGenerationContext.class, Mockito.RETURNS_DEEP_STUBS);
         Mockito.when(this.context.getTypeContext()).thenReturn(typeContext);
+        ObjectMapper objectMapper = new ObjectMapper();
+        Mockito.when(this.context.getGeneratorConfig().getObjectMapper()).thenReturn(objectMapper);
+        Mockito.when(this.context.getGeneratorConfig().createArrayNode()).thenAnswer(_invocation -> objectMapper.createArrayNode());
+        Mockito.when(this.context.getGeneratorConfig().createObjectNode()).thenAnswer(_invocation -> objectMapper.createObjectNode());
         Mockito.when(this.context.getGeneratorConfig().getSchemaVersion()).thenReturn(schemaVersion);
 
         Answer<String> keywordLookup = invocation -> ((SchemaKeyword) invocation.getArgument(0)).forVersion(schemaVersion);
diff --git a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorAllOfCleanUpTest.java b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorAllOfCleanUpTest.java
new file mode 100644
index 0000000..deea1ff
--- /dev/null
+++ b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorAllOfCleanUpTest.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2020 VicTools.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.github.victools.jsonschema.generator;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import java.util.Arrays;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.stream.Collectors;
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.skyscreamer.jsonassert.JSONAssert;
+import org.skyscreamer.jsonassert.JSONCompareMode;
+
+/**
+ * Test for {@link SchemaGenerator} class.
+ */
+@RunWith(JUnitParamsRunner.class)
+public class SchemaGeneratorAllOfCleanUpTest {
+
+    public Object[] parametersForTestAllOfCleanUp() {
+        String differentValueInMainSchema = "{ \"type\": \"object\", \"title\":\"main schema\", \"allOf\": [{ \"title\": \"different title\" }, {}] }";
+        String differentValueInAllOfPart = "{ \"type\": \"object\", \"allOf\": [{ \"title\": \"title X\" }, { \"title\": \"title Y\" }] }";
+        List<Object[]> testCases = EnumSet.allOf(SchemaVersion.class).stream()
+                .map(schemaVersion -> new Object[][]{
+                    {schemaVersion, differentValueInMainSchema, differentValueInMainSchema},
+                    {schemaVersion, differentValueInAllOfPart, differentValueInAllOfPart},
+                    {schemaVersion,
+                        "{ \"type\": \"object\", \"title\":\"same in all three\", \"allOf\": [{ \"title\":\"same in all three\" }, { \"title\":\"same in all three\" }] }",
+                        "{ \"type\": \"object\", \"title\":\"same in all three\" }"},
+                    {schemaVersion,
+                        "{ \"type\": \"object\",\"allOf\": [{ \"title\":\"from allOf[0]\" }, { \"description\":\"from allOf[1]\" }] }",
+                        "{ \"type\": \"object\", \"title\":\"from allOf[0]\", \"description\":\"from allOf[1]\" }"}
+                })
+                .flatMap(oneVersion -> Arrays.asList(oneVersion).stream())
+                .collect(Collectors.toList());
+
+        // in Draft 7, alongside $ref all other attributes are being ignored and should therefore not be merged
+        String refInAllOfPart = "{ \"type\": \"object\", \"allOf\": [{ \"$ref\": \"#\" }, { \"title\": \"value\" }] }";
+        testCases.add(new Object[]{ SchemaVersion.DRAFT_7, refInAllOfPart, refInAllOfPart });
+        EnumSet.complementOf(EnumSet.of(SchemaVersion.DRAFT_7)).stream()
+                .forEach(schemaVersion ->
+        testCases.add(new Object[]{ schemaVersion, refInAllOfPart, "{ \"type\": \"object\", \"$ref\": \"#\", \"title\": \"value\" }" }));
+        return testCases.toArray();
+    }
+
+    @Test
+    @Parameters
+    public void testAllOfCleanUp(SchemaVersion schemaVersion, String inputSchema, String outputSchema) throws Exception {
+        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion, OptionPreset.PLAIN_JSON)
+                .without(Option.SCHEMA_VERSION_INDICATOR);
+        configBuilder.forTypesInGeneral()
+                .withCustomDefinitionProvider((_type, context) -> {
+                    try {
+                        return new CustomDefinition((ObjectNode) context.getGeneratorConfig().getObjectMapper()
+                                .readTree(inputSchema));
+                    } catch (JsonProcessingException ex) {
+                        throw new IllegalStateException("This should never happen", ex);
+                    }
+                });
+        SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
+
+        JsonNode result = generator.generateSchema(String.class);
+        JSONAssert.assertEquals(outputSchema, result.toString(), JSONCompareMode.STRICT);
+    }
+}
diff --git a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorComplexTypesTest.java b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorComplexTypesTest.java
index 555cd77..6ee2c14 100644
--- a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorComplexTypesTest.java
+++ b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorComplexTypesTest.java
@@ -18,13 +18,10 @@ package com.github.victools.jsonschema.generator;
 
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.node.ObjectNode;
-import java.io.IOException;
-import java.io.InputStream;
 import java.lang.reflect.Type;
 import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.net.URI;
-import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.HashMap;
@@ -32,7 +29,6 @@ import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
-import java.util.Scanner;
 import junitparams.JUnitParamsRunner;
 import junitparams.Parameters;
 import junitparams.naming.TestCaseName;
@@ -101,7 +97,7 @@ public class SchemaGeneratorComplexTypesTest {
     }
 
     Object parametersForTestGenerateSchema() {
-        Module neutralModule = configBuilder -> configBuilder.with((javaType, context) -> {
+        Module neutralModule = configBuilder -> configBuilder.forTypesInGeneral().withCustomDefinitionProvider((javaType, _context) -> {
             if (Integer.class == javaType.getErasedType()) {
                 ObjectNode customNode = configBuilder.getObjectMapper()
                         .createObjectNode()
@@ -154,7 +150,7 @@ public class SchemaGeneratorComplexTypesTest {
             }
         }
         JSONAssert.assertEquals('\n' + result.toString() + '\n',
-                loadResource(caseTitle + ".json"), result.toString(), JSONCompareMode.STRICT);
+                TestUtils.loadResource(this.getClass(), caseTitle + ".json"), result.toString(), JSONCompareMode.STRICT);
     }
 
     @Test(expected = IllegalArgumentException.class)
@@ -166,19 +162,6 @@ public class SchemaGeneratorComplexTypesTest {
         new SchemaGenerator(config).generateSchema(TestClassCircular.class);
     }
 
-    private static String loadResource(String resourcePath) throws IOException {
-        StringBuilder stringBuilder = new StringBuilder();
-        try (InputStream inputStream = SchemaGeneratorComplexTypesTest.class
-                .getResourceAsStream(resourcePath);
-                Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
-            while (scanner.hasNext()) {
-                stringBuilder.append(scanner.nextLine()).append('\n');
-            }
-        }
-        String fileAsString = stringBuilder.toString();
-        return fileAsString;
-    }
-
     private static class TestClass1 extends TestClass2<String> {
 
         public static final Long CONSTANT = 5L;
diff --git a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorCustomDefinitionsTest.java b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorCustomDefinitionsTest.java
index 525f9fc..4deb062 100644
--- a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorCustomDefinitionsTest.java
+++ b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorCustomDefinitionsTest.java
@@ -18,15 +18,10 @@ package com.github.victools.jsonschema.generator;
 
 import com.fasterxml.classmate.ResolvedType;
 import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ObjectNode;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
-import java.util.Scanner;
 import junitparams.JUnitParamsRunner;
 import junitparams.Parameters;
 import org.junit.Assert;
@@ -47,10 +42,9 @@ public class SchemaGeneratorCustomDefinitionsTest {
         CustomDefinitionProviderV2 customDefinitionProvider = (javaType, context) -> javaType.getErasedType() == Integer.class
                 ? new CustomDefinition(context.createDefinition(context.getTypeContext().resolve(String.class)))
                 : null;
-        SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(new ObjectMapper(), schemaVersion)
-                .with(customDefinitionProvider)
-                .build();
-        SchemaGenerator generator = new SchemaGenerator(config);
+        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion);
+        configBuilder.forTypesInGeneral().withCustomDefinitionProvider(customDefinitionProvider);
+        SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
         JsonNode result = generator.generateSchema(Integer.class);
         Assert.assertEquals(1, result.size());
         Assert.assertEquals(SchemaKeyword.TAG_TYPE_STRING.forVersion(schemaVersion),
@@ -72,10 +66,9 @@ public class SchemaGeneratorCustomDefinitionsTest {
                     .set(config.getKeyword(SchemaKeyword.TAG_PROPERTIES), config.createObjectNode()
                             .set(accessProperty, context.makeNullable(context.createDefinition(generic)))));
         };
-        SchemaGeneratorConfig config = new SchemaGeneratorConfigBuilder(new ObjectMapper(), schemaVersion)
-                .with(customDefinitionProvider)
-                .build();
-        SchemaGenerator generator = new SchemaGenerator(config);
+        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion);
+        configBuilder.forTypesInGeneral().withCustomDefinitionProvider(customDefinitionProvider);
+        SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
         JsonNode result = generator.generateSchema(ArrayList.class, String.class);
         Assert.assertEquals(2, result.size());
         Assert.assertEquals(SchemaKeyword.TAG_TYPE_OBJECT.forVersion(schemaVersion),
@@ -105,7 +98,7 @@ public class SchemaGeneratorCustomDefinitionsTest {
                 return null;
             }
         };
-        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(new ObjectMapper(), schemaVersion);
+        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion);
         configBuilder.forTypesInGeneral()
                 .withTitleResolver(_scope -> "type title")
                 .withDescriptionResolver(_scope -> "type description")
@@ -152,7 +145,7 @@ public class SchemaGeneratorCustomDefinitionsTest {
                 return new CustomDefinition(customDefinition);
             }
         };
-        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(new ObjectMapper(), schemaVersion, OptionPreset.PLAIN_JSON)
+        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion, OptionPreset.PLAIN_JSON)
                 .with(Option.DEFINITIONS_FOR_ALL_OBJECTS);
         configBuilder.forTypesInGeneral()
                 .withCustomDefinitionProvider(customDefinitionProviderOne)
@@ -160,7 +153,8 @@ public class SchemaGeneratorCustomDefinitionsTest {
         SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
         JsonNode result = generator.generateSchema(TestDirectCircularClass.class);
         JSONAssert.assertEquals('\n' + result.toString() + '\n',
-                loadResource("multiple-definitions-one-type-" + schemaVersion.name() + ".json"), result.toString(), JSONCompareMode.STRICT);
+                TestUtils.loadResource(this.getClass(), "multiple-definitions-one-type-" + schemaVersion.name() + ".json"),
+                result.toString(), JSONCompareMode.STRICT);
     }
 
     @Test
@@ -178,13 +172,14 @@ public class SchemaGeneratorCustomDefinitionsTest {
                     .set(config.getKeyword(SchemaKeyword.TAG_PROPERTIES), config.createObjectNode()
                             .set(accessProperty, context.createDefinitionReference(generic))));
         };
-        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(new ObjectMapper(), schemaVersion);
+        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion);
         configBuilder.forTypesInGeneral()
                 .withCustomDefinitionProvider(customDefinitionProvider);
         SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
         JsonNode result = generator.generateSchema(TestCircularClass1.class);
         JSONAssert.assertEquals('\n' + result.toString() + '\n',
-                loadResource("circular-custom-definition-" + schemaVersion.name() + ".json"), result.toString(), JSONCompareMode.STRICT);
+                TestUtils.loadResource(this.getClass(), "circular-custom-definition-" + schemaVersion.name() + ".json"),
+                result.toString(), JSONCompareMode.STRICT);
     }
 
     @Test
@@ -211,20 +206,8 @@ public class SchemaGeneratorCustomDefinitionsTest {
         SchemaGenerator generator = new SchemaGenerator(configBuilder.build());
         JsonNode result = generator.generateSchema(TestDirectCircularClass.class);
         JSONAssert.assertEquals('\n' + result.toString() + '\n',
-                loadResource("custom-property-definition-" + schemaVersion.name() + ".json"), result.toString(), JSONCompareMode.STRICT);
-    }
-
-    private static String loadResource(String resourcePath) throws IOException {
-        StringBuilder stringBuilder = new StringBuilder();
-        try (InputStream inputStream = SchemaGeneratorComplexTypesTest.class
-                .getResourceAsStream(resourcePath);
-                Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
-            while (scanner.hasNext()) {
-                stringBuilder.append(scanner.nextLine()).append('\n');
-            }
-        }
-        String fileAsString = stringBuilder.toString();
-        return fileAsString;
+                TestUtils.loadResource(this.getClass(), "custom-property-definition-" + schemaVersion.name() + ".json"),
+                result.toString(), JSONCompareMode.STRICT);
     }
 
     private static class TestDirectCircularClass {
diff --git a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorSubtypesTest.java b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorSubtypesTest.java
index 76807eb..e5c680c 100644
--- a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorSubtypesTest.java
+++ b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorSubtypesTest.java
@@ -19,14 +19,10 @@ package com.github.victools.jsonschema.generator;
 import com.fasterxml.classmate.ResolvedType;
 import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 import java.util.Objects;
-import java.util.Scanner;
 import java.util.stream.Collectors;
 import java.util.stream.Stream;
 import junitparams.JUnitParamsRunner;
@@ -72,7 +68,7 @@ public class SchemaGeneratorSubtypesTest {
 
         JsonNode result = generator.generateSchema(TestClassWithSuperTypeReferences.class);
         JSONAssert.assertEquals('\n' + result.toString() + '\n',
-                loadResource(caseTitle + ".json"), result.toString(), JSONCompareMode.STRICT);
+                TestUtils.loadResource(SchemaGeneratorSubtypesTest.class, caseTitle + ".json"), result.toString(), JSONCompareMode.STRICT);
     }
 
     private List<ResolvedType> determineTargetTypeOverrides(FieldScope field) {
@@ -86,19 +82,6 @@ public class SchemaGeneratorSubtypesTest {
         return null;
     }
 
-    private static String loadResource(String resourcePath) throws IOException {
-        StringBuilder stringBuilder = new StringBuilder();
-        try (InputStream inputStream = SchemaGeneratorSubtypesTest.class
-                .getResourceAsStream(resourcePath);
-                Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
-            while (scanner.hasNext()) {
-                stringBuilder.append(scanner.nextLine()).append('\n');
-            }
-        }
-        String fileAsString = stringBuilder.toString();
-        return fileAsString;
-    }
-
     private static class TestSubtypeResolver implements SubtypeResolver {
 
         private List<Class<?>> subtypes;
diff --git a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorTest.java b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorTest.java
index 1d496b6..26feb39 100644
--- a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorTest.java
+++ b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/SchemaGeneratorTest.java
@@ -27,7 +27,8 @@ import org.junit.runners.Suite;
     SchemaGeneratorSimpleTypesTest.class,
     SchemaGeneratorComplexTypesTest.class,
     SchemaGeneratorSubtypesTest.class,
-    SchemaGeneratorCustomDefinitionsTest.class
+    SchemaGeneratorCustomDefinitionsTest.class,
+    SchemaGeneratorAllOfCleanUpTest.class
 })
 public class SchemaGeneratorTest {
     // suite as collection of separate test classes to avoid one huge test class
diff --git a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/TestUtils.java b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/TestUtils.java
new file mode 100644
index 0000000..c3d375c
--- /dev/null
+++ b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/TestUtils.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2020 VicTools.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.github.victools.jsonschema.generator;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Scanner;
+
+/**
+ * Common helper functions within tests.
+ */
+public abstract class TestUtils {
+
+    private TestUtils() {
+        // not intended for sub-typing
+    }
+
+    /**
+     * Load a local file (e.g. example JSON Schema) from the given resource path, relative to the package of the indicated test class.
+     *
+     * @param testClass test class requesting a file to be loaded
+     * @param resourcePath relative path to the target file
+     * @return file contents
+     * @throws IOException when the file loading failed
+     */
+    public static String loadResource(Class<?> testClass, String resourcePath) throws IOException {
+        StringBuilder stringBuilder = new StringBuilder();
+        try (InputStream inputStream = testClass.getResourceAsStream(resourcePath);
+                Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
+            while (scanner.hasNext()) {
+                stringBuilder.append(scanner.nextLine()).append('\n');
+            }
+        }
+        String fileAsString = stringBuilder.toString();
+        return fileAsString;
+    }
+}
diff --git a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/impl/module/EnumModuleTest.java b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/impl/module/EnumModuleTest.java
index 210e2e4..6ae90f9 100644
--- a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/impl/module/EnumModuleTest.java
+++ b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/impl/module/EnumModuleTest.java
@@ -18,7 +18,6 @@ package com.github.victools.jsonschema.generator.impl.module;
 
 import com.fasterxml.classmate.ResolvedType;
 import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ArrayNode;
 import com.fasterxml.jackson.databind.node.JsonNodeType;
 import com.fasterxml.jackson.databind.node.ObjectNode;
@@ -30,6 +29,7 @@ import com.github.victools.jsonschema.generator.MethodScope;
 import com.github.victools.jsonschema.generator.OptionPreset;
 import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
 import com.github.victools.jsonschema.generator.SchemaGeneratorConfigPart;
+import com.github.victools.jsonschema.generator.SchemaGeneratorGeneralConfigPart;
 import com.github.victools.jsonschema.generator.SchemaKeyword;
 import com.github.victools.jsonschema.generator.SchemaVersion;
 import java.util.stream.Collectors;
@@ -53,6 +53,7 @@ public class EnumModuleTest extends AbstractTypeAwareTest {
     private EnumModule instanceAsStringsFromToString;
     private EnumModule instanceAsObjects;
     private SchemaGeneratorConfigBuilder builder;
+    private SchemaGeneratorGeneralConfigPart typeConfigPart;
     private SchemaGeneratorConfigPart<FieldScope> fieldConfigPart;
     private SchemaGeneratorConfigPart<MethodScope> methodConfigPart;
 
@@ -74,10 +75,12 @@ public class EnumModuleTest extends AbstractTypeAwareTest {
      */
     private void initConfigBuilder(SchemaVersion schemaVersion) {
         this.prepareContextForVersion(schemaVersion);
-        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(new ObjectMapper(), schemaVersion, new OptionPreset());
+        SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(schemaVersion, new OptionPreset());
+        this.typeConfigPart = Mockito.spy(configBuilder.forTypesInGeneral());
         this.fieldConfigPart = Mockito.spy(configBuilder.forFields());
         this.methodConfigPart = Mockito.spy(configBuilder.forMethods());
         this.builder = Mockito.spy(configBuilder);
+        Mockito.when(this.builder.forTypesInGeneral()).thenReturn(this.typeConfigPart);
         Mockito.when(this.builder.forFields()).thenReturn(this.fieldConfigPart);
         Mockito.when(this.builder.forMethods()).thenReturn(this.methodConfigPart);
     }
@@ -88,9 +91,9 @@ public class EnumModuleTest extends AbstractTypeAwareTest {
         this.initConfigBuilder(schemaVersion);
         this.instanceAsStringsFromName.applyToConfigBuilder(this.builder);
 
-        Mockito.verify(this.builder).getObjectMapper();
-        Mockito.verify(this.builder).with(Mockito.any(CustomDefinitionProviderV2.class));
-        Mockito.verifyNoMoreInteractions(this.builder);
+        Mockito.verify(this.typeConfigPart).withCustomDefinitionProvider(Mockito.any(CustomDefinitionProviderV2.class));
+        Mockito.verify(this.builder).forTypesInGeneral();
+        Mockito.verifyNoMoreInteractions(this.typeConfigPart, this.builder);
     }
 
     @Test
@@ -99,9 +102,9 @@ public class EnumModuleTest extends AbstractTypeAwareTest {
         this.initConfigBuilder(schemaVersion);
         this.instanceAsStringsFromToString.applyToConfigBuilder(this.builder);
 
-        Mockito.verify(this.builder).getObjectMapper();
-        Mockito.verify(this.builder).with(Mockito.any(CustomDefinitionProviderV2.class));
-        Mockito.verifyNoMoreInteractions(this.builder);
+        Mockito.verify(this.typeConfigPart).withCustomDefinitionProvider(Mockito.any(CustomDefinitionProviderV2.class));
+        Mockito.verify(this.builder).forTypesInGeneral();
+        Mockito.verifyNoMoreInteractions(this.typeConfigPart, this.builder);
     }
 
     @Test
@@ -138,7 +141,7 @@ public class EnumModuleTest extends AbstractTypeAwareTest {
         this.initConfigBuilder(schemaVersion);
         instance.applyToConfigBuilder(this.builder);
         ArgumentCaptor<CustomDefinitionProviderV2> captor = ArgumentCaptor.forClass(CustomDefinitionProviderV2.class);
-        Mockito.verify(this.builder).with(captor.capture());
+        Mockito.verify(this.typeConfigPart).withCustomDefinitionProvider(captor.capture());
 
         ResolvedType testEnumType = this.getContext().getTypeContext().resolve(TestEnum.class);
         CustomDefinition schemaDefinition = captor.getValue().provideCustomSchemaDefinition(testEnumType, this.getContext());
diff --git a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/impl/module/SimpleTypeModuleTest.java b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/impl/module/SimpleTypeModuleTest.java
index 18f62ea..bc70ea5 100644
--- a/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/impl/module/SimpleTypeModuleTest.java
+++ b/jsonschema-generator/src/test/java/com/github/victools/jsonschema/generator/impl/module/SimpleTypeModuleTest.java
@@ -64,11 +64,10 @@ public class SimpleTypeModuleTest {
 
         Mockito.verify(this.typeConfigPart).withAdditionalPropertiesResolver(Mockito.any());
         Mockito.verify(this.typeConfigPart).withPatternPropertiesResolver(Mockito.any());
+        Mockito.verify(this.typeConfigPart).withCustomDefinitionProvider(Mockito.any(CustomDefinitionProviderV2.class));
         Mockito.verifyNoMoreInteractions(this.typeConfigPart);
         Mockito.verify(this.builder).forTypesInGeneral();
 
-        Mockito.verify(this.builder).getObjectMapper();
-        Mockito.verify(this.builder).with(Mockito.any(CustomDefinitionProviderV2.class));
 
         Mockito.verifyNoMoreInteractions(this.builder);
     }