|
| 1 | +package com.predic8.membrane.core.openapi.validators; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
| 4 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 5 | +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; |
| 6 | +import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; |
| 7 | +import com.predic8.membrane.core.openapi.OpenAPIValidator; |
| 8 | +import com.predic8.membrane.core.openapi.model.Body; |
| 9 | +import com.predic8.membrane.core.openapi.model.Request; |
| 10 | +import com.predic8.membrane.core.openapi.serviceproxy.OpenAPIRecord; |
| 11 | +import com.predic8.membrane.core.openapi.serviceproxy.OpenAPISpec; |
| 12 | +import com.predic8.membrane.core.util.URIFactory; |
| 13 | +import jakarta.mail.internet.ParseException; |
| 14 | +import org.jetbrains.annotations.NotNull; |
| 15 | +import org.jetbrains.annotations.Nullable; |
| 16 | +import org.junit.jupiter.api.Disabled; |
| 17 | +import org.junit.jupiter.api.Test; |
| 18 | +import org.slf4j.Logger; |
| 19 | +import org.slf4j.LoggerFactory; |
| 20 | + |
| 21 | +import java.io.ByteArrayInputStream; |
| 22 | +import java.io.File; |
| 23 | +import java.io.IOException; |
| 24 | +import java.nio.charset.StandardCharsets; |
| 25 | +import java.util.HashMap; |
| 26 | +import java.util.List; |
| 27 | +import java.util.Map; |
| 28 | +import java.util.concurrent.atomic.AtomicReference; |
| 29 | + |
| 30 | +import static com.google.common.collect.ImmutableMap.of; |
| 31 | +import static com.predic8.membrane.core.openapi.model.Request.post; |
| 32 | +import static com.predic8.membrane.core.openapi.util.TestUtils.om; |
| 33 | +import static com.predic8.membrane.core.openapi.util.TestUtils.parseOpenAPI; |
| 34 | +import static java.util.regex.Pattern.quote; |
| 35 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 36 | + |
| 37 | +/** |
| 38 | + * Runs the OpenAPI validator with the official tests from the JSON Schema Test Suite. |
| 39 | + * |
| 40 | + * The test suite needs to be downloaded manually. |
| 41 | + */ |
| 42 | +public class JsonSchemaTestSuiteTests { |
| 43 | + private final static Logger log = LoggerFactory.getLogger(JsonSchemaTestSuiteTests.class); |
| 44 | + public final String TEST_SUITE_BASE_PATH = "git\\JSON-Schema-Test-Suite\\tests\\draft6"; |
| 45 | + |
| 46 | + private final ObjectMapper objectMapper = new ObjectMapper(); |
| 47 | + private final ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory().disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER)); |
| 48 | + |
| 49 | + int correct, incorrect, ignored; |
| 50 | + |
| 51 | + @Disabled("The test requires a manual download. It also fails.") |
| 52 | + @Test |
| 53 | + void jsonSchema() throws IOException, ParseException { |
| 54 | + runTestsFoundInDirectory(TEST_SUITE_BASE_PATH); |
| 55 | + log.info("correct = {}", correct); |
| 56 | + log.info("incorrect = {}", incorrect); |
| 57 | + log.info("ignored = {}", ignored); |
| 58 | + |
| 59 | + assertEquals(0, incorrect); |
| 60 | + } |
| 61 | + |
| 62 | + private void runTestsFoundInDirectory(String baseDir) throws IOException, ParseException { |
| 63 | + File base = new File(baseDir); |
| 64 | + if (!base.exists()) { |
| 65 | + throw new RuntimeException("Please download the tests from https://github.com/json-schema-org/JSON-Schema-Test-Suite/ and adjust the base path here."); |
| 66 | + } |
| 67 | + for (File file : base.listFiles()) { |
| 68 | + if (!file.getName().endsWith(".json")) |
| 69 | + continue; |
| 70 | + runTestsFromFile(file); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + private void runTestsFromFile(File file) throws IOException, ParseException { |
| 75 | + log.info("Testing file: {}", file.getName()); |
| 76 | + |
| 77 | + List<?> tests = objectMapper.readValue(file, List.class); |
| 78 | + for (Object t : tests) { |
| 79 | + Map test = (Map) t; |
| 80 | + String description = test.get("description").toString(); |
| 81 | + Object schema = test.get("schema"); |
| 82 | + List<?> testRuns = (List<?>) test.get("tests"); |
| 83 | + |
| 84 | + log.info("- description = {}", description); |
| 85 | + log.info(" schema = {}", om.writeValueAsString(schema)); |
| 86 | + |
| 87 | + String openapi = generateOpenAPIForSchema(schema); |
| 88 | + |
| 89 | + String ignoredReason = computeIgnoredReason(openapi, description); |
| 90 | + |
| 91 | + OpenAPIValidator validator = null; |
| 92 | + if (ignoredReason == null) |
| 93 | + validator = new OpenAPIValidator(new URIFactory(), new OpenAPIRecord(parseOpenAPI( |
| 94 | + new ByteArrayInputStream(openapi.getBytes(StandardCharsets.UTF_8))),new OpenAPISpec())); |
| 95 | + |
| 96 | + for (Object tr : testRuns) |
| 97 | + runSingleTestRun((Map) tr, ignoredReason, validator); |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + private @NotNull String generateOpenAPIForSchema(Object schema) throws JsonProcessingException { |
| 102 | + Map openapi = new HashMap(of("openapi", "3.1.0", "paths", of("/test", of("post", of( |
| 103 | + "requestBody", of("content", of("application/json", of("schema", schema))), |
| 104 | + "responses", of("200", of("description", "OK"))))))); |
| 105 | + |
| 106 | + moveTypeDefinitions(schema, openapi, "definitions"); |
| 107 | + moveTypeDefinitions(schema, openapi, "$defs"); |
| 108 | + |
| 109 | + return replaceReferences(replaceReferences(yamlMapper.writeValueAsString(openapi), "definitions"), "$defs"); |
| 110 | + } |
| 111 | + |
| 112 | + private String replaceReferences(String openApiString, String rootKey) { |
| 113 | + return openApiString.replaceAll("#/" + quote(rootKey) + "/", "#/components/schemas/"); |
| 114 | + } |
| 115 | + |
| 116 | + private static void moveTypeDefinitions(Object schema, Map openApi, String rootKey) { |
| 117 | + if (schema instanceof Map && ((Map) schema).containsKey(rootKey)) { |
| 118 | + openApi.put("components", of("schemas", ((Map) schema).get(rootKey))); |
| 119 | + log.warn(" warning: The schema contains definitions. They have been moved from #/" + rootKey + "/ to #/components/schemas/ ."); |
| 120 | + } |
| 121 | + } |
| 122 | + |
| 123 | + |
| 124 | + private static @Nullable String computeIgnoredReason(String openapi, String description) { |
| 125 | + if (openapi.contains("http://")) |
| 126 | + return "the official test code seems to start a webserver on localhost:1234, which we do not support (yet)."; |
| 127 | + if (description.equals("Location-independent identifier")) |
| 128 | + return "'$ref':'#foo' is used, which we do not support."; |
| 129 | + if (description.contains("empty tokens in $ref json-pointer")) |
| 130 | + return "the name of a definition is the empty string."; |
| 131 | + if (description.equals("relative pointer ref to array")) |
| 132 | + return "prefix reference migration not implemented"; |
| 133 | + if (description.equals("relative pointer ref to object")) |
| 134 | + return "reference migration not implemented"; |
| 135 | + return null; |
| 136 | + } |
| 137 | + |
| 138 | + private void runSingleTestRun(Map tr, String ignoredReason, OpenAPIValidator validator) throws JsonProcessingException, ParseException { |
| 139 | + Map testRun = tr; |
| 140 | + |
| 141 | + log.info(" - testRun = {}", om.writeValueAsString(testRun)); |
| 142 | + |
| 143 | + String description = testRun.get("description").toString(); |
| 144 | + String body = objectMapper.writeValueAsString(testRun.get("data")); |
| 145 | + Boolean valid = (Boolean)testRun.get("valid"); |
| 146 | + |
| 147 | + log.info(" testRun.description = {}", description); |
| 148 | + log.info(" testRun.body = {}", body); |
| 149 | + log.info(" testRun.shouldBeValid = {}", valid); |
| 150 | + |
| 151 | + if (ignoredReason != null) { |
| 152 | + ignored++; |
| 153 | + log.info(" Test: Ignored. ({})", ignoredReason); |
| 154 | + return; |
| 155 | + } |
| 156 | + |
| 157 | + Request<Body> post = post().path("/test").mediaType("application/json"); |
| 158 | + ValidationErrors errors = null; |
| 159 | + try { |
| 160 | + errors = validator.validate(post.body(body)); |
| 161 | + |
| 162 | + log.info(" validation result = {}", errors); |
| 163 | + } catch (Exception e) { |
| 164 | + e.printStackTrace(); |
| 165 | + } |
| 166 | + |
| 167 | + if (errors != null && errors.isEmpty() == valid) { |
| 168 | + log.info(" Test: OK"); |
| 169 | + correct++; |
| 170 | + } else { |
| 171 | + log.warn(" Test: NOT OK!"); |
| 172 | + incorrect++; |
| 173 | + } |
| 174 | + } |
| 175 | +} |
0 commit comments