Search in sources :

Example 6 with Document

use of io.apicurio.datamodels.core.models.Document in project apicurio-data-models by Apicurio.

the class Oas20IReferenceManipulationStrategy method getExistingLocalComponents.

@Override
public Map<String, Node> getExistingLocalComponents(Document document) {
    if (!(document instanceof Oas20Document))
        throw new IllegalArgumentException("Oas20Document expected.");
    Oas20Document model = (Oas20Document) document;
    // We could use a local resolver here theoretically, but the reverse approach should be easier and faster
    Map<String, io.apicurio.datamodels.core.models.Node> res = new LinkedHashMap<>();
    if (model.definitions != null)
        transform(model.definitions.items, name -> PREFIX + "definitions/" + name, res);
    if (model.parameters != null)
        transform(model.parameters.items, name -> PREFIX + "parameters/" + name, res);
    if (model.responses != null)
        transform(model.responses.items, name -> PREFIX + "responses/" + name, res);
    return res;
}
Also used : Oas20Parameter(io.apicurio.datamodels.openapi.v2.models.Oas20Parameter) Oas20Response(io.apicurio.datamodels.openapi.v2.models.Oas20Response) Oas20SchemaDefinition(io.apicurio.datamodels.openapi.v2.models.Oas20SchemaDefinition) Node(io.apicurio.datamodels.core.models.Node) DocumentType(io.apicurio.datamodels.core.models.DocumentType) Oas20ResponseDefinition(io.apicurio.datamodels.openapi.v2.models.Oas20ResponseDefinition) Oas20Schema(io.apicurio.datamodels.openapi.v2.models.Oas20Schema) LinkedHashMap(java.util.LinkedHashMap) IDefinition(io.apicurio.datamodels.core.models.common.IDefinition) Map(java.util.Map) Oas20ParameterDefinition(io.apicurio.datamodels.openapi.v2.models.Oas20ParameterDefinition) Document(io.apicurio.datamodels.core.models.Document) Oas20Document(io.apicurio.datamodels.openapi.v2.models.Oas20Document) Oas20Document(io.apicurio.datamodels.openapi.v2.models.Oas20Document) Node(io.apicurio.datamodels.core.models.Node) LinkedHashMap(java.util.LinkedHashMap)

Example 7 with Document

use of io.apicurio.datamodels.core.models.Document in project apicurio-data-models by Apicurio.

the class IoTestRunner method runChild.

/**
 * @see org.junit.runners.ParentRunner#runChild(java.lang.Object, org.junit.runner.notification.RunNotifier)
 */
@Override
protected void runChild(IoTestCase child, RunNotifier notifier) {
    Description description = this.describeChild(child);
    Statement statement = new Statement() {

        @Override
        public void evaluate() throws Throwable {
            String testCP = "fixtures/io/" + child.getTest();
            URL testUrl = Thread.currentThread().getContextClassLoader().getResource(testCP);
            Assert.assertNotNull("Test file not found on classpath: " + testCP, testUrl);
            // Read the test source
            String original = loadResource(testUrl);
            Assert.assertNotNull(original);
            // Parse into a Json object
            Object originalParsed = mapper.readTree(original);
            // Parse into a data model
            Document doc = Library.readDocument(originalParsed);
            Assert.assertNotNull("Document was null.", doc);
            // Make sure we read the appropriate number of "extra" properties
            ExtraPropertyDetectionVisitor epv = new ExtraPropertyDetectionVisitor();
            Library.visitTree(doc, epv, TraverserDirection.down);
            int actualExtraProps = epv.getExtraPropertyCount();
            int expectedExtraProps = child.getExtraProperties();
            Assert.assertEquals("Wrong number of extra properties found.", expectedExtraProps, actualExtraProps);
            // Write the data model back to JSON
            Object roundTripJs = Library.writeNode(doc);
            Assert.assertNotNull(roundTripJs);
            // Stringify the round trip object
            String roundTrip = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(roundTripJs);
            Assert.assertNotNull(roundTrip);
            assertJsonEquals(original, roundTrip);
            // Now test that we can create a Node Path to **every** node in the document!!
            List<Node> allNodes = getAllNodes(doc);
            for (Node node : allNodes) {
                try {
                    NodePath nodePath = Library.createNodePath(node);
                    Assert.assertNotNull(nodePath);
                    String path = nodePath.toString();
                    Assert.assertNotNull(nodePath);
                    nodePath = new NodePath(path);
                    Node resolvedNode = nodePath.resolve(doc);
                    Assert.assertNotNull("Failed to resolve node: " + nodePath.toString(), resolvedNode);
                    Assert.assertTrue("Path failed to resolve [" + node.getClass().getSimpleName() + "] to the proper node: " + path, node == resolvedNode);
                } catch (Throwable t) {
                    System.err.println("Failure/error testing node path: " + Library.createNodePath(node).toString());
                    throw t;
                }
            }
            // assert the results.  But at least it runs everything through the reader dispatchers.
            for (Node node : allNodes) {
                // Skip extensions and expressions.
                if (node instanceof Extension || node instanceof IOas30Expression) {
                    continue;
                }
                // TODO :: check the extra-property counts when doing partial i/o testing
                try {
                    Object partialNodeJson = Library.writeNode(node);
                    String partialNodeJsonStr = JsonCompat.stringify(partialNodeJson);
                    Node clonedNode = cloneNode(node);
                    // Skip any node that we can't clone.
                    if (clonedNode == null) {
                        continue;
                    }
                    Library.readNode(partialNodeJson, clonedNode);
                    Object finalJson = Library.writeNode(clonedNode);
                    String finalJsonStr = JsonCompat.stringify(finalJson);
                    // LoggerCompat.info("PARTIAL: %s", partialNodeJson);
                    // LoggerCompat.info("FINAL:   %s", finalJsonStr);
                    assertJsonEquals(partialNodeJsonStr, finalJsonStr);
                } catch (Throwable t) {
                    System.err.println("Failure/error testing partial I/O for node: " + Library.createNodePath(node).toString());
                    throw t;
                }
            }
        }
    };
    runLeaf(statement, description, notifier);
}
Also used : Description(org.junit.runner.Description) Statement(org.junit.runners.model.Statement) Node(io.apicurio.datamodels.core.models.Node) IOas30Expression(io.apicurio.datamodels.openapi.v3.models.IOas30Expression) Document(io.apicurio.datamodels.core.models.Document) URL(java.net.URL) NodePath(io.apicurio.datamodels.core.models.NodePath) Extension(io.apicurio.datamodels.core.models.Extension)

Example 8 with Document

use of io.apicurio.datamodels.core.models.Document in project apicurio-data-models by Apicurio.

the class IoTestRunner method cloneNode.

static Node cloneNode(Node node) {
    Constructor<? extends Node> constructor;
    Node clonedNode = null;
    try {
        if (node instanceof INamed) {
            constructor = node.getClass().getConstructor(String.class);
            clonedNode = constructor.newInstance(((INamed) node).getName());
        } else if (node instanceof OasPathItem) {
            constructor = node.getClass().getConstructor(String.class);
            clonedNode = constructor.newInstance(((OasPathItem) node).getPath());
        } else if (node instanceof Operation) {
            constructor = node.getClass().getConstructor(String.class);
            clonedNode = constructor.newInstance(((Operation) node).getType());
        } else if (node instanceof Oas20PropertySchema) {
            constructor = node.getClass().getConstructor(String.class);
            clonedNode = constructor.newInstance(((Oas20PropertySchema) node).getPropertyName());
        } else if (node instanceof Oas30PropertySchema) {
            constructor = node.getClass().getConstructor(String.class);
            clonedNode = constructor.newInstance(((Oas30PropertySchema) node).getPropertyName());
        } else if (node instanceof ServerVariable) {
            constructor = node.getClass().getConstructor(String.class);
            clonedNode = constructor.newInstance(((ServerVariable) node).getName());
        } else {
            constructor = node.getClass().getConstructor();
            clonedNode = constructor.newInstance();
        }
    } catch (SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        System.err.println("Skipping partial I/O for: " + node.getClass().getSimpleName());
    }
    if (clonedNode != null) {
        clonedNode._parent = node._parent;
        clonedNode._ownerDocument = node.ownerDocument();
        if (clonedNode instanceof Document) {
            clonedNode._ownerDocument = (Document) clonedNode;
        }
    }
    return clonedNode;
}
Also used : Node(io.apicurio.datamodels.core.models.Node) Operation(io.apicurio.datamodels.core.models.common.Operation) Document(io.apicurio.datamodels.core.models.Document) ServerVariable(io.apicurio.datamodels.core.models.common.ServerVariable) Oas20PropertySchema(io.apicurio.datamodels.openapi.v2.models.Oas20Schema.Oas20PropertySchema) InvocationTargetException(java.lang.reflect.InvocationTargetException) OasPathItem(io.apicurio.datamodels.openapi.models.OasPathItem) Oas30PropertySchema(io.apicurio.datamodels.openapi.v3.models.Oas30Schema.Oas30PropertySchema) INamed(io.apicurio.datamodels.core.models.common.INamed)

Example 9 with Document

use of io.apicurio.datamodels.core.models.Document in project apicurio-data-models by Apicurio.

the class TransformTestRunner method runChild.

/**
 * @see org.junit.runners.ParentRunner#runChild(java.lang.Object, org.junit.runner.notification.RunNotifier)
 */
@Override
protected void runChild(TransformTestCase child, RunNotifier notifier) {
    Description description = this.describeChild(child);
    Statement statement = new Statement() {

        @Override
        public void evaluate() throws Throwable {
            String testCP = "fixtures/transformation/" + child.getInput();
            URL testUrl = Thread.currentThread().getContextClassLoader().getResource(testCP);
            Assert.assertNotNull("Could not load test resource: " + testCP, testUrl);
            // Read the test source
            String original = loadResource(testUrl);
            Assert.assertNotNull(original);
            // Parse into a Json object
            Object originalParsed = mapper.readTree(original);
            // Read into a data model
            Document doc20 = Library.readDocument(originalParsed);
            Assert.assertEquals(DocumentType.openapi2, doc20.getDocumentType());
            // Transform the document
            Oas30Document doc30 = Library.transformDocument((Oas20Document) doc20);
            Assert.assertNotNull(doc30);
            // Now compare with expected
            String actual = Library.writeDocumentToJSONString(doc30);
            String expectedCP = "fixtures/transformation/" + child.getExpected();
            URL expectedUrl = Thread.currentThread().getContextClassLoader().getResource(expectedCP);
            Assert.assertNotNull("Could not load test resource: " + expectedCP, expectedUrl);
            String expected = loadResource(expectedUrl);
            assertJsonEquals(expected, actual);
        }
    };
    runLeaf(statement, description, notifier);
}
Also used : Oas30Document(io.apicurio.datamodels.openapi.v3.models.Oas30Document) Description(org.junit.runner.Description) Statement(org.junit.runners.model.Statement) Oas30Document(io.apicurio.datamodels.openapi.v3.models.Oas30Document) Document(io.apicurio.datamodels.core.models.Document) Oas20Document(io.apicurio.datamodels.openapi.v2.models.Oas20Document) URL(java.net.URL)

Example 10 with Document

use of io.apicurio.datamodels.core.models.Document in project apicurio-data-models by Apicurio.

the class CommandTestRunner method runChild.

/**
 * @see org.junit.runners.ParentRunner#runChild(java.lang.Object, org.junit.runner.notification.RunNotifier)
 */
@Override
protected void runChild(CommandTestCase child, RunNotifier notifier) {
    Description description = this.describeChild(child);
    Statement statement = new Statement() {

        @Override
        public void evaluate() throws Throwable {
            LoggerCompat.info("------------------------");
            LoggerCompat.info("[CommandTestRunner] Running Test: %s", child.getName());
            String beforeCP = "fixtures/cmd/" + child.getTest() + ".before.json";
            String afterCP = "fixtures/cmd/" + child.getTest() + ".after.json";
            String commandsCP = "fixtures/cmd/" + child.getTest() + ".commands.json";
            if (child.getCommands() != null) {
                commandsCP = "fixtures/cmd/" + child.getTest() + child.getCommands();
            }
            URL beforeUrl = Thread.currentThread().getContextClassLoader().getResource(beforeCP);
            URL afterUrl = Thread.currentThread().getContextClassLoader().getResource(afterCP);
            URL commandsUrl = Thread.currentThread().getContextClassLoader().getResource(commandsCP);
            Assert.assertNotNull("Test file not found on classpath: " + beforeCP, beforeUrl);
            Assert.assertNotNull("Test file not found on classpath: " + afterCP, afterUrl);
            Assert.assertNotNull("Test file not found on classpath: " + commandsCP, commandsUrl);
            // Read the test source
            String beforeJson = loadResource(beforeUrl);
            String afterJson = loadResource(afterUrl);
            String commandsJson = loadResource(commandsUrl);
            Assert.assertNotNull(beforeJson);
            Assert.assertNotNull(afterJson);
            Assert.assertNotNull(commandsJson);
            // Parse into a Json object
            Object beforeJs = JsonCompat.parseJSON(beforeJson);
            Object commandsJs = JsonCompat.parseJSON(commandsJson);
            Assert.assertNotNull(beforeJs);
            Assert.assertNotNull(commandsJs);
            // Read the before doc into a Document
            Document document = Library.readDocument(beforeJs);
            Assert.assertNotNull(document);
            // Load all the commands to apply.
            List<TestDirective> directives = new ArrayList<>();
            ArrayNode allCommands = (ArrayNode) commandsJs;
            for (int cidx = 0; cidx < allCommands.size(); cidx++) {
                JsonNode directiveNode = allCommands.get(cidx);
                String type = JsonCompat.getPropertyString(directiveNode, Constants.PROP___TYPE);
                if ("_FINALIZE_".equals(type)) {
                    TestDirectiveFinalize directive = new TestDirectiveFinalize();
                    directive.contentVersion = JsonCompat.consumePropertyNumber(directiveNode, "__contentVersion").longValue();
                    directive.pendingVersion = JsonCompat.consumePropertyNumber(directiveNode, "__pendingVersion").longValue();
                    directives.add(directive);
                } else if ("_UNDO_".equals(type)) {
                    TestDirectiveUndoRedo directive = new TestDirectiveUndoRedo();
                    directive.dtype = TestDirectiveType.undo;
                    directive.contentVersion = JsonCompat.consumePropertyNumber(directiveNode, "__contentVersion").longValue();
                    directives.add(directive);
                } else if ("_REDO_".equals(type)) {
                    TestDirectiveUndoRedo directive = new TestDirectiveUndoRedo();
                    directive.dtype = TestDirectiveType.redo;
                    directive.contentVersion = JsonCompat.consumePropertyNumber(directiveNode, "__contentVersion").longValue();
                    directives.add(directive);
                } else if ("_UNDO_LAST_".equals(type)) {
                    TestDirectiveUndoRedo directive = new TestDirectiveUndoRedo();
                    directive.dtype = TestDirectiveType.undoLast;
                    directives.add(directive);
                } else if ("_REDO_LAST_".equals(type)) {
                    TestDirectiveUndoRedo directive = new TestDirectiveUndoRedo();
                    directive.dtype = TestDirectiveType.redoLast;
                    directives.add(directive);
                } else {
                    TestDirectiveCommand directive = new TestDirectiveCommand();
                    directive.contentVersion = cidx;
                    if (directiveNode.has("__contentVersion")) {
                        directive.contentVersion = JsonCompat.consumePropertyNumber(directiveNode, "__contentVersion").longValue();
                    }
                    if (directiveNode.has("__pending")) {
                        directive.pending = JsonCompat.consumePropertyBoolean(directiveNode, "__pending");
                    }
                    directive.command = MarshallCompat.unmarshallCommand(directiveNode);
                    directives.add(directive);
                    // Make sure we can marshall/unmarshall the command
                    Object marshalledCommand = MarshallCompat.marshallCommand(directive.command);
                    String mcs = JsonCompat.stringify(marshalledCommand);
                    ICommand unmarshalledCommand = MarshallCompat.unmarshallCommand(JsonCompat.parseJSON(mcs));
                    Assert.assertEquals("Failed to marshall/unmarshall command: " + directive.command.getClass(), directive.command.getClass(), unmarshalledCommand.getClass());
                    // Actually use the one that's been marshalled/unmarshalled.
                    directive.command = unmarshalledCommand;
                }
            }
            // Apply all the commands to the Document (modifying the document).
            OtEngine engine = new OtEngine(document);
            directives.forEach(directive -> {
                if (directive.dtype == TestDirectiveType.command) {
                    TestDirectiveCommand dcmd = (TestDirectiveCommand) directive;
                    OtCommand cmd = new OtCommand();
                    cmd.author = "user";
                    cmd.command = dcmd.command;
                    cmd.contentVersion = dcmd.contentVersion;
                    // Command is local if it's pending, or if there is only 1
                    cmd.local = dcmd.pending || directives.size() == 1;
                    cmd.reverted = false;
                    engine.executeCommand(cmd, dcmd.pending);
                } else if (directive.dtype == TestDirectiveType.finalize) {
                    TestDirectiveFinalize dcmd = (TestDirectiveFinalize) directive;
                    engine.finalizeCommand(dcmd.pendingVersion, dcmd.contentVersion);
                } else if (directive.dtype == TestDirectiveType.undo) {
                    TestDirectiveUndoRedo dcmd = (TestDirectiveUndoRedo) directive;
                    engine.undo(dcmd.contentVersion);
                } else if (directive.dtype == TestDirectiveType.redo) {
                    TestDirectiveUndoRedo dcmd = (TestDirectiveUndoRedo) directive;
                    engine.redo(dcmd.contentVersion);
                } else if (directive.dtype == TestDirectiveType.undoLast) {
                    engine.undoLastLocalCommand();
                } else if (directive.dtype == TestDirectiveType.redoLast) {
                    engine.redoLastLocalCommand();
                }
            });
            // Check that the resulting (modified) document is what we expected.
            Document actualDoc = engine.getCurrentDocument();
            String actual = Library.writeDocumentToJSONString(actualDoc);
            String expected = afterJson;
            assertJsonEquals(expected, actual);
            // that results in the original document.
            if (directives.size() == 1) {
                engine.undoLastLocalCommand();
                actualDoc = engine.getCurrentDocument();
                actual = Library.writeDocumentToJSONString(actualDoc);
                expected = beforeJson;
                assertJsonEquals(expected, actual);
            }
        }
    };
    runLeaf(statement, description, notifier);
}
Also used : Description(org.junit.runner.Description) OtCommand(io.apicurio.datamodels.cmd.ot.OtCommand) Statement(org.junit.runners.model.Statement) ArrayList(java.util.ArrayList) JsonNode(com.fasterxml.jackson.databind.JsonNode) OtEngine(io.apicurio.datamodels.cmd.ot.OtEngine) Document(io.apicurio.datamodels.core.models.Document) URL(java.net.URL) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode)

Aggregations

Document (io.apicurio.datamodels.core.models.Document)21 Node (io.apicurio.datamodels.core.models.Node)7 Oas30Document (io.apicurio.datamodels.openapi.v3.models.Oas30Document)7 URL (java.net.URL)7 Description (org.junit.runner.Description)6 Statement (org.junit.runners.model.Statement)6 DocumentType (io.apicurio.datamodels.core.models.DocumentType)5 NodePath (io.apicurio.datamodels.core.models.NodePath)4 ValidationProblem (io.apicurio.datamodels.core.models.ValidationProblem)4 OasDocument (io.apicurio.datamodels.openapi.models.OasDocument)4 Oas20Document (io.apicurio.datamodels.openapi.v2.models.Oas20Document)4 Test (org.junit.Test)4 JsonNode (com.fasterxml.jackson.databind.JsonNode)3 Aai20Document (io.apicurio.datamodels.asyncapi.v2.models.Aai20Document)2 DataModelReader (io.apicurio.datamodels.core.io.DataModelReader)2 ValidationProblemSeverity (io.apicurio.datamodels.core.models.ValidationProblemSeverity)2 IDocumentValidatorExtension (io.apicurio.datamodels.core.validation.IDocumentValidatorExtension)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 CompletableFuture (java.util.concurrent.CompletableFuture)2