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;
}
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);
}
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;
}
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);
}
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);
}
Aggregations