org.xmlunit.builder.Input Java Examples

The following examples show how to use org.xmlunit.builder.Input. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: staedi   Author: xlate   File: StaEDIXMLStreamReaderTest.java    License: Apache License 2.0 8 votes vote down vote up
@Test
void testReadXml() throws Exception {
    XMLStreamReader xmlReader = getXmlReader("/x12/extraDelimiter997.edi");
    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/extraDelimiter997.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
Example #2
Source Project: timbuctoo   Author: HuygensING   File: RdfDescriptionSaverTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void doesNotDeleteValueWhenWhenSubjectUriDoesNotMatchBaseUri() throws Exception {
  testRdfDescriptionSaver.addValue(BASE_URI, "http://purl.org/dc/terms/title", "DWC Data", null, BASE_URI);
  testRdfDescriptionSaver.delValue("http://example.org/datasets/DUMMY/clusius10",
    "http://purl.org/dc/terms/title", "DWC Data", null, BASE_URI);
  testRdfDescriptionSaver.commit();

  Source expected = Input.fromByteArray(
    (
      "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
        ">\n" +
        "  <rdf:Description rdf:about=\"http://example.org/datasets/DUMMY/clusius2\">\n" +
        "    <title xmlns=\"http://purl.org/dc/terms/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">" +
        "DWC Data</title> \n" +
        "  </rdf:Description>\n" +
        "</rdf:RDF>\n"
    ).getBytes(StandardCharsets.UTF_8)
  ).build();

  Source actual = Input.fromFile(descriptionFile).build();
  assertThat(actual,
    isSimilarTo(expected).ignoreWhitespace().withComparisonFormatter(new DefaultComparisonFormatter())
  );
}
 
Example #3
Source Project: syndesis   Author: syndesisio   File: XmlSchemaTestHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static void compareMatchingElement(List<Element> sourceChildNodes, Element element) {
    final String type = element.getLocalName();
    final String name = element.getAttribute(NAME_ATTRIBUTE);
    boolean matchFound = false;
    for (Element sourceElement : sourceChildNodes) {
        if (type.equals(sourceElement.getLocalName()) &&
            name.equals(sourceElement.getAttribute(NAME_ATTRIBUTE))) {
            // compare matching element
            Diff diff = DiffBuilder.compare(Input.fromNode(sourceElement))
                .withTest(Input.fromNode(sourceElement))
                .ignoreComments()
                .ignoreWhitespace()
                .checkForIdentical()
                .build();
            assertThat(diff.hasDifferences())
                .overridingErrorMessage("Schema differences " + diff.toString())
                .isFalse();
            matchFound = true;
        }
    }

    if (!matchFound) {
        fail(String.format("Missing source element %s[name=%s]", type, name));
    }
}
 
Example #4
Source Project: staedi   Author: xlate   File: StaEDIXMLStreamReaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testTransactionElementWithXmlns() throws Exception {
    EDIInputFactory ediFactory = EDIInputFactory.newFactory();
    ediFactory.setProperty(EDIInputFactory.XML_DECLARE_TRANSACTION_XMLNS, Boolean.TRUE);
    InputStream stream = getClass().getResourceAsStream("/x12/extraDelimiter997.edi");
    ediReader = ediFactory.createEDIStreamReader(stream);
    XMLStreamReader xmlReader = ediFactory.createXMLStreamReader(ediReader);

    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/extraDelimiter997-transaction-xmlns.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
Example #5
Source Project: artifactory-resource   Author: spring-io   File: MavenMetadataGeneratorTests.java    License: Apache License 2.0 6 votes vote down vote up
private Condition<File> xmlContent(URL expected) {
	return new Condition<File>("XML Content") {

		@Override
		public boolean matches(File actual) {
			Diff diff = DiffBuilder.compare(Input.from(expected)).withTest(Input.from(actual)).checkForSimilar()
					.ignoreWhitespace().build();
			if (diff.hasDifferences()) {
				try {
					String content = new String(FileCopyUtils.copyToByteArray(actual));
					throw new AssertionError(diff.toString() + "\n" + content);
				}
				catch (IOException ex) {
					throw new IllegalStateException(ex);
				}
			}
			return true;
		}

	};
}
 
Example #6
Source Project: ehcache3   Author: ehcache   File: XmlMultiConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleConfigurationsFromXml() throws URISyntaxException {
  URL resource = XmlConfigurationTest.class.getResource("/configs/multi/multiple-configs.xml");

  XmlMultiConfiguration xmlMultiConfiguration = XmlMultiConfiguration.from(resource).build();

  assertThat(xmlMultiConfiguration.configuration("foo").getCacheConfigurations(), hasKey("foo"));
  assertThat(xmlMultiConfiguration.configuration("foo", "prod").getCacheConfigurations(), hasKey("foo"));
  assertThat(xmlMultiConfiguration.configuration("bar").getCacheConfigurations(), hasKey("bar"));
  assertThat(xmlMultiConfiguration.configuration("bar", "prod").getCacheConfigurations(), hasKey("bar"));

  assertThat(xmlMultiConfiguration.identities(), containsInAnyOrder("foo", "bar"));
  assertThat(xmlMultiConfiguration.variants("foo"), empty());
  assertThat(xmlMultiConfiguration.variants("bar"), empty());

  assertThat(xmlMultiConfiguration.toString(), isSimilarTo(Input.fromURI(resource.toURI())).ignoreWhitespace().ignoreComments());
}
 
Example #7
Source Project: ehcache3   Author: ehcache   File: XmlMultiConfigurationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleVariantsFromXml() throws URISyntaxException {
  URL resource = XmlConfigurationTest.class.getResource("/configs/multi/multiple-variants.xml");

  XmlMultiConfiguration xmlMultiConfiguration = XmlMultiConfiguration.from(resource).build();

  assertThrows(() -> xmlMultiConfiguration.configuration("foo"), IllegalStateException.class);

  assertThat(xmlMultiConfiguration.configuration("foo", "development").getCacheConfigurations(), hasKey("foo-dev"));
  assertThat(xmlMultiConfiguration.configuration("foo", "production").getCacheConfigurations(), hasKey("foo-prod"));
  assertThat(xmlMultiConfiguration.configuration("bar", "development").getCacheConfigurations(), hasKey("bar-dev"));
  assertThat(xmlMultiConfiguration.configuration("bar", "production").getCacheConfigurations(), hasKey("bar-prod"));

  assertThat(xmlMultiConfiguration.identities(), containsInAnyOrder("foo", "bar"));
  assertThat(xmlMultiConfiguration.variants("foo"), containsInAnyOrder("development", "production"));
  assertThat(xmlMultiConfiguration.variants("bar"), containsInAnyOrder("development", "production"));

  assertThat(xmlMultiConfiguration.toString(), isSimilarTo(Input.fromURI(resource.toURI())).ignoreWhitespace().ignoreComments());
}
 
Example #8
Source Project: timbuctoo   Author: HuygensING   File: RdfDescriptionSaverTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void replacesValue() throws Exception {
  testRdfDescriptionSaver.addValue(BASE_URI, "http://purl.org/dc/terms/title", "DWC Data", null, BASE_URI);
  testRdfDescriptionSaver.delValue(BASE_URI, "http://purl.org/dc/terms/title", "DWC Data", null, BASE_URI);
  testRdfDescriptionSaver.addValue(BASE_URI, "http://purl.org/dc/terms/title", "DWC Data New", null, BASE_URI);
  testRdfDescriptionSaver.commit();

  Source expected = Input.fromByteArray(
    (
      "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
        ">\n" +
        "  <rdf:Description rdf:about=\"http://example.org/datasets/DUMMY/clusius2\">\n" +
        "    <title xmlns=\"http://purl.org/dc/terms/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">" +
        "DWC Data New</title> \n" +
        "  </rdf:Description>\n" +
        "</rdf:RDF>\n"
    ).getBytes(StandardCharsets.UTF_8)
  ).build();

  Source actual = Input.fromFile(descriptionFile).build();
  assertThat(actual,
    isSimilarTo(expected).ignoreWhitespace().withComparisonFormatter(new DefaultComparisonFormatter())
  );
}
 
Example #9
Source Project: xmlunit   Author: xmlunit   File: DefaultComparisonFormatterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testComparisonType_HAS_DOCTYPE_DECLARATION() throws Exception {
    // prepare data
    DocumentBuilderFactory dbf = getDocumentBuilderFactoryWithoutValidation();
    Document controlDoc = Convert.toDocument(Input.fromString("<!DOCTYPE Book><a/>").build(), dbf);

    Diff diff = DiffBuilder.compare(controlDoc).withTest("<a/>")
        .withDifferenceEvaluator(DifferenceEvaluators.downgradeDifferencesToEqual(ComparisonType.CHILD_NODELIST_LENGTH))
        .withNodeFilter(NodeFilters.AcceptAll).build();
    assertPreRequirements(diff, ComparisonType.HAS_DOCTYPE_DECLARATION);
    Comparison firstDiff = diff.getDifferences().iterator().next().getComparison();

    // run test
    String description = compFormatter.getDescription(firstDiff);
    String controlDetails =  getDetails(firstDiff.getControlDetails(), firstDiff.getType());
    String testDetails =  getDetails(firstDiff.getTestDetails(), firstDiff.getType());

    // validate result
    Assert.assertEquals("Expected has doctype declaration 'true' but was 'false' - "
            + "comparing <!DOCTYPE Book><a...> at / to <a...> at /", description);

    assertEquals("<!DOCTYPE Book>\n<a/>", controlDetails);
    assertEquals("<a/>", testDetails);
}
 
Example #10
Source Project: xmlunit   Author: xmlunit   File: DefaultComparisonFormatterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testComparisonType_DOCTYPE_NAME() throws Exception {
    // prepare data
    DocumentBuilderFactory dbf = getDocumentBuilderFactoryWithoutValidation();
    Document controlDoc = Convert.toDocument(Input.fromString("<!DOCTYPE Book ><a/>").build(), dbf);
    Document testDoc = Convert.toDocument(Input.fromString("<!DOCTYPE XY ><a/>").build(), dbf);

    Diff diff = DiffBuilder.compare(controlDoc).withTest(testDoc)
        .withDifferenceEvaluator(DifferenceEvaluators.downgradeDifferencesToEqual(ComparisonType.CHILD_NODELIST_LENGTH))
        .withNodeFilter(NodeFilters.AcceptAll).build();
    assertPreRequirements(diff, ComparisonType.DOCTYPE_NAME);
    Comparison firstDiff = diff.getDifferences().iterator().next().getComparison();

    // run test
    String description = compFormatter.getDescription(firstDiff);
    String controlDetails =  getDetails(firstDiff.getControlDetails(), firstDiff.getType());
    String testDetails =  getDetails(firstDiff.getTestDetails(), firstDiff.getType());

    // validate result
    Assert.assertEquals("Expected doctype name 'Book' but was 'XY' - "
            + "comparing <!DOCTYPE Book><a...> at / to <!DOCTYPE XY><a...> at /", description);

    assertEquals("<!DOCTYPE Book>\n<a/>", controlDetails);
    assertEquals("<!DOCTYPE XY>\n<a/>", testDetails);
}
 
Example #11
Source Project: xmlunit   Author: xmlunit   File: DOMDifferenceEngineTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void nodeFilterAppliesToDocTypes() {
    DOMDifferenceEngine d = new DOMDifferenceEngine();
    DiffExpecter ex = new DiffExpecter(ComparisonType.HAS_DOCTYPE_DECLARATION);
    d.addDifferenceListener(ex);
    d.setComparisonController(ComparisonControllers.StopWhenDifferent);
    Document d1 = Convert.toDocument(Input.fromString("<Book/>").build());
    Document d2 =
        Convert.toDocument(Input.fromString("<!DOCTYPE Book PUBLIC "
                + "\"XMLUNIT/TEST/PUB\" "
                + "\"" + TestResources.BOOK_DTD
                + "\">"
                + "<Book/>")
                           .build());
    assertEquals(wrap(ComparisonResult.EQUAL),
                 d.compareNodes(d1, new XPathContext(),
                                d2, new XPathContext()));
    assertEquals(0, ex.invoked);
}
 
Example #12
Source Project: xmlunit   Author: xmlunit   File: DOMDifferenceEngineTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDetectCommentInPrelude() {
    DOMDifferenceEngine d = new DOMDifferenceEngine();
    Document d1 = Convert.toDocument(Input.fromFile(TestResources.TEST_RESOURCE_DIR
                                                    + "BookXsdGenerated.xml")
                                     .build());
    Document d2 = Convert.toDocument(Input.fromFile(TestResources.TEST_RESOURCE_DIR
                                                    + "BookXsdGeneratedWithComment.xml")
                                     .build());
    DiffExpecter ex = new DiffExpecter(ComparisonType.CHILD_NODELIST_LENGTH,
                                       "/", "/");
    d.addDifferenceListener(ex);
    d.setComparisonController(ComparisonControllers.StopWhenDifferent);
    assertEquals(wrapAndStop(ComparisonResult.DIFFERENT),
                 d.compareNodes(d1, new XPathContext(),
                                d2, new XPathContext()));
}
 
Example #13
Source Project: xmlunit   Author: xmlunit   File: DOMDifferenceEngineTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDetectMissingXsiType() {
    DOMDifferenceEngine d = new DOMDifferenceEngine();
    Document d1 = Convert.toDocument(Input.fromString("<doc xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
                                                      + "<effectiveTime xsi:type=\"IVL_TS\"></effectiveTime></doc>")
                                     .build());
    Document d2 = Convert.toDocument(Input.fromString("<doc xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
                                                      + "<effectiveTime></effectiveTime></doc>")
                                     .build());

    DiffExpecter ex = new DiffExpecter(ComparisonType.ATTR_NAME_LOOKUP,
                                       "/doc[1]/effectiveTime[1]/@type",
                                       "/doc[1]/effectiveTime[1]");
    d.addDifferenceListener(ex);
    d.setComparisonController(ComparisonControllers.StopWhenDifferent);
    assertEquals(wrapAndStop(ComparisonResult.DIFFERENT),
                 d.compareNodes(d1, new XPathContext(),
                                d2, new XPathContext()));
}
 
Example #14
Source Project: timbuctoo   Author: HuygensING   File: RdfDescriptionSaverTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void addsRelation() throws Exception {
  testRdfDescriptionSaver.addRelation(BASE_URI,
    "http://purl.org/dc/terms/rightsHolder", "http://example.com/rightsHolder", BASE_URI);
  testRdfDescriptionSaver.commit();

  Source expected = Input.fromByteArray(
    (
      "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" +
        "  <rdf:Description rdf:about=\"http://example.org/datasets/DUMMY/clusius2\">\n" +
        "    <rightsHolder xmlns=\"http://purl.org/dc/terms/\" " +
        "       rdf:resource=\"http://example.com/rightsHolder\" /> \n" +
        "  </rdf:Description>\n" +
        "</rdf:RDF>\n"
    ).getBytes(StandardCharsets.UTF_8)
  ).build();


  Source actual = Input.fromFile(descriptionFile).build();
  assertThat(actual,
    isSimilarTo(expected).ignoreWhitespace().withComparisonFormatter(new DefaultComparisonFormatter())
  );
}
 
Example #15
Source Project: timbuctoo   Author: HuygensING   File: RdfDescriptionSaverTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void doesNotAddDuplicateValuesToSamePredicate() throws Exception {
  testRdfDescriptionSaver.addValue(BASE_URI, "http://purl.org/dc/terms/title", "DWC Data", null, BASE_URI);
  testRdfDescriptionSaver.addValue(BASE_URI,
    "http://purl.org/dc/terms/title", "DWC Data",
    null, BASE_URI);
  testRdfDescriptionSaver.commit();

  Source expected = Input.fromByteArray(
    (
      "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
        ">\n" +
        "  <rdf:Description rdf:about=\"http://example.org/datasets/DUMMY/clusius2\">\n" +
        "    <title xmlns=\"http://purl.org/dc/terms/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">" +
        "DWC Data</title> \n" +
        "  </rdf:Description>\n" +
        "</rdf:RDF>\n"
    ).getBytes(StandardCharsets.UTF_8)
  ).build();

  Source actual = Input.fromFile(descriptionFile).build();
  assertThat(actual,
    isSimilarTo(expected).ignoreWhitespace().withComparisonFormatter(new DefaultComparisonFormatter())
  );
}
 
Example #16
Source Project: xmlunit   Author: xmlunit   File: MultipleNodeAssert.java    License: Apache License 2.0 6 votes vote down vote up
static MultipleNodeAssert create(Object xmlSource, Map<String, String> prefix2Uri, DocumentBuilderFactory dbf,
                                 XPathFactory xpf, String xPath) {

    AssertionsAdapter.assertThat(xPath).isNotBlank();

    final JAXPXPathEngine engine = xpf == null ? new JAXPXPathEngine() : new JAXPXPathEngine(xpf);
    if (prefix2Uri != null) {
        engine.setNamespaceContext(prefix2Uri);
    }

    Source s = Input.from(xmlSource).build();
    Node root = dbf != null ? Convert.toNode(s, dbf) : Convert.toNode(s);
    Iterable<Node> nodes = engine.selectNodes(xPath, root);

    return new MultipleNodeAssert(nodes, engine)
            .describedAs("XPath \"%s\" evaluated to node set", xPath);
}
 
Example #17
Source Project: timbuctoo   Author: HuygensING   File: RdfDescriptionSaverTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void doesNotDeleteRelationWhenSubjectUriDoesNotMatchBaseUri() throws Exception {
  testRdfDescriptionSaver.addRelation(BASE_URI,
    "http://purl.org/dc/terms/rightsHolder", "http://example.com/rightsHolder", BASE_URI);
  testRdfDescriptionSaver.delRelation("http://example.org/datasets/DUMMY/test",
    "http://purl.org/dc/terms/title", "http://purl.org/dc/terms/rightsHolder", BASE_URI);
  testRdfDescriptionSaver.commit();

  Source expected = Input.fromByteArray(
    (
      "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" +
        "  <rdf:Description rdf:about=\"http://example.org/datasets/DUMMY/clusius2\">\n" +
        "    <rightsHolder xmlns=\"http://purl.org/dc/terms/\" " +
        "       rdf:resource=\"http://example.com/rightsHolder\" /> \n" +
        "  </rdf:Description>\n" +
        "</rdf:RDF>\n"
    ).getBytes(StandardCharsets.UTF_8)
  ).build();

  Source actual = Input.fromFile(descriptionFile).build();
  assertThat(actual,
    isSimilarTo(expected).ignoreWhitespace().withComparisonFormatter(new DefaultComparisonFormatter())
  );

}
 
Example #18
Source Project: xmlunit   Author: xmlunit   File: ValueAssert.java    License: Apache License 2.0 6 votes vote down vote up
static ValueAssert create(Object xmlSource, Map<String, String> prefix2Uri, DocumentBuilderFactory dbf,
                          XPathFactory xpf, String xPath) {
    AssertionsAdapter.assertThat(xPath).isNotBlank();

    final JAXPXPathEngine engine = xpf == null ? new JAXPXPathEngine() : new JAXPXPathEngine(xpf);
    if (prefix2Uri != null) {
        engine.setNamespaceContext(prefix2Uri);
    }

    Source s = Input.from(xmlSource).build();
    Node root = dbf != null ? Convert.toNode(s, dbf) : Convert.toNode(s);
    String value = engine.evaluate(xPath, root);

    return new ValueAssert(value)
            .describedAs("XPath \"%s\" evaluated to value", xPath);
}
 
Example #19
Source Project: timbuctoo   Author: HuygensING   File: RdfDescriptionSaverTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void addsMultipleValues() throws Exception {
  testRdfDescriptionSaver.addValue(BASE_URI, "http://purl.org/dc/terms/title", "DWC Data", null, BASE_URI);
  testRdfDescriptionSaver.addValue(BASE_URI,
    "http://purl.org/dc/terms/description", "Biographical data of the Digital Web Centre for " +
      "the History of Science (DWC)", null, BASE_URI);
  testRdfDescriptionSaver.commit();

  Source expected = Input.fromByteArray(
    (
      "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" +
        "  <rdf:Description rdf:about=\"http://example.org/datasets/DUMMY/clusius2\">\n" +
        "    <description xmlns=\"http://purl.org/dc/terms/\">" +
        "Biographical data of the Digital Web Centre for the History of Science (DWC)</description> \n" +
        "    <title xmlns=\"http://purl.org/dc/terms/\">DWC Data</title> \n" +
        "  </rdf:Description>\n" +
        "</rdf:RDF>\n"
    ).getBytes(StandardCharsets.UTF_8)
  ).build();

  Source actual = Input.fromFile(descriptionFile).build();
  assertThat(actual,
    isSimilarTo(expected).ignoreWhitespace().withComparisonFormatter(new DefaultComparisonFormatter())
  );
}
 
Example #20
Source Project: timbuctoo   Author: HuygensING   File: RdfDescriptionSaverTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void doesNotDeleteRelationWhenSubjectNull() throws Exception {
  testRdfDescriptionSaver.addRelation(BASE_URI,
    "http://purl.org/dc/terms/rightsHolder", "http://example.com/rightsHolder", BASE_URI);
  testRdfDescriptionSaver.delRelation(null,
    "http://purl.org/dc/terms/title", "http://purl.org/dc/terms/rightsHolder", BASE_URI);
  testRdfDescriptionSaver.commit();

  Source expected = Input.fromByteArray(
    (
      "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" +
        "  <rdf:Description rdf:about=\"http://example.org/datasets/DUMMY/clusius2\">\n" +
        "    <rightsHolder xmlns=\"http://purl.org/dc/terms/\" " +
        "       rdf:resource=\"http://example.com/rightsHolder\" /> \n" +
        "  </rdf:Description>\n" +
        "</rdf:RDF>\n"
    ).getBytes(StandardCharsets.UTF_8)
  ).build();

  Source actual = Input.fromFile(descriptionFile).build();
  assertThat(actual,
    isSimilarTo(expected).ignoreWhitespace().withComparisonFormatter(new DefaultComparisonFormatter())
  );

}
 
Example #21
Source Project: timbuctoo   Author: HuygensING   File: RdfDescriptionSaverTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void deletesRelation() throws Exception {
  testRdfDescriptionSaver.addRelation(BASE_URI,
    "http://purl.org/dc/terms/rightsHolder", "http://example.com/rightsHolder", BASE_URI);
  testRdfDescriptionSaver.commit();
  testRdfDescriptionSaver.delRelation(BASE_URI,
    "http://purl.org/dc/terms/rightsHolder", "http://example.com/rightsHolder", BASE_URI);
  testRdfDescriptionSaver.commit();

  Source expected = Input.fromByteArray(
    ("<rdf:RDF xmlns=\"http://purl.org/dc/terms/\"\n xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" +
      "</rdf:RDF>\n"
    ).getBytes(StandardCharsets.UTF_8)
  ).build();

  Source actual = Input.fromFile(descriptionFile).build();

  assertThat(actual,
    isSimilarTo(expected).ignoreWhitespace().withComparisonFormatter(new DefaultComparisonFormatter())
  );

}
 
Example #22
Source Project: timbuctoo   Author: HuygensING   File: RdfDescriptionSaverTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void doesNotDeleteValueWhenSubjectNull() throws Exception {
  testRdfDescriptionSaver.addValue(BASE_URI, "http://purl.org/dc/terms/title", "DWC Data", null, BASE_URI);
  testRdfDescriptionSaver.delValue(null, "http://purl.org/dc/terms/title", "DWC Data", null, BASE_URI);
  testRdfDescriptionSaver.commit();

  Source expected = Input.fromByteArray(
    (
      "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n" +
        ">\n" +
        "  <rdf:Description rdf:about=\"http://example.org/datasets/DUMMY/clusius2\">\n" +
        "    <title xmlns=\"http://purl.org/dc/terms/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">" +
        "DWC Data</title> \n" +
        "  </rdf:Description>\n" +
        "</rdf:RDF>\n"
    ).getBytes(StandardCharsets.UTF_8)
  ).build();

  Source actual = Input.fromFile(descriptionFile).build();
  assertThat(actual,
    isSimilarTo(expected).ignoreWhitespace().withComparisonFormatter(new DefaultComparisonFormatter())
  );
}
 
Example #23
Source Project: timbuctoo   Author: HuygensING   File: RdfDescriptionSaverTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Test
public void doesNotAddDuplicateRelationToSamePredicate() throws Exception {
  testRdfDescriptionSaver.addRelation(BASE_URI,
    "http://purl.org/dc/terms/rightsHolder", "http://example.com/rightsHolder", BASE_URI);
  testRdfDescriptionSaver.addRelation(BASE_URI,
    "http://purl.org/dc/terms/rightsHolder", "http://example.com/rightsHolder", BASE_URI);
  testRdfDescriptionSaver.commit();

  Source expected = Input.fromByteArray(
    (
      "<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" +
        "  <rdf:Description rdf:about=\"http://example.org/datasets/DUMMY/clusius2\">\n" +
        "    <rightsHolder xmlns=\"http://purl.org/dc/terms/\" " +
        "       rdf:resource=\"http://example.com/rightsHolder\" /> \n" +
        "  </rdf:Description>\n" +
        "</rdf:RDF>\n"
    ).getBytes(StandardCharsets.UTF_8)
  ).build();


  Source actual = Input.fromFile(descriptionFile).build();
  assertThat(actual,
    isSimilarTo(expected).ignoreWhitespace().withComparisonFormatter(new DefaultComparisonFormatter())
  );
}
 
Example #24
Source Project: airsonic-advanced   Author: airsonic-advanced   File: PingIT.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void pingMissingAuthTest() {
    ResponseEntity<String> response = Scanner.rest.getForEntity(
            UriComponentsBuilder.fromHttpUrl(Scanner.SERVER + "/rest/ping").toUriString(),
            String.class);

    assertThat(response.getStatusCode(), Matchers.equalTo(HttpStatus.OK));
    assertThat(response.getBody(),
            isIdenticalTo(Input.fromStream(getClass().getResourceAsStream("/blobs/ping/missing-auth.xml")))
                    .ignoreWhitespace());
}
 
Example #25
Source Project: java-technology-stack   Author: codeEngraver   File: CastorMarshallerTests.java    License: MIT License 5 votes vote down vote up
/**
 * Assert the values of xpath expression evaluation is exactly the same as expected value.
 * <p>The xpath may contain the xml namespace prefixes, since namespaces from flight example
 * are being registered.
 * @param msg the error message that will be used in case of test failure
 * @param expected the expected value
 * @param xpath the xpath to evaluate
 * @param xmlDoc the xml to use
 * @throws Exception if any error occurs during xpath evaluation
 */
private void assertXpathEvaluatesTo(String msg, String expected, String xpath, String xmlDoc) throws Exception {
	Map<String, String> namespaces = new HashMap<>();
	namespaces.put("tns", "http://samples.springframework.org/flight");
	namespaces.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");

	JAXPXPathEngine engine = new JAXPXPathEngine();
	engine.setNamespaceContext(namespaces);

	Source source = Input.fromString(xmlDoc).build();
	Iterable<Node> nodeList = engine.selectNodes(xpath, source);
	assertEquals(msg, expected, nodeList.iterator().next().getNodeValue());
}
 
Example #26
Source Project: warnings-ng-plugin   Author: jenkinsci   File: RemoteApiITest.java    License: MIT License 5 votes vote down vote up
private void assertThatRemoteApiEquals(final Run<?, ?> build, final String url, final String expectedXml) {
    assertThat(callXmlRemoteApi(build.getUrl() + url))
            .and(Input.from(readAllBytes(FOLDER_PREFIX + expectedXml)))
            .ignoreChildNodesOrder()
            .normalizeWhitespace()
            .areIdentical();
}
 
Example #27
Source Project: powsybl-core   Author: powsybl   File: AbstractConverterTest.java    License: Mozilla Public License 2.0 5 votes vote down vote up
protected static void compareXml(InputStream expected, InputStream actual) {
    Source control = Input.fromStream(expected).build();
    Source test = Input.fromStream(actual).build();
    Diff myDiff = DiffBuilder.compare(control).withTest(test).ignoreWhitespace().ignoreComments().build();
    boolean hasDiff = myDiff.hasDifferences();
    if (hasDiff) {
        System.err.println(myDiff.toString());
    }
    assertFalse(hasDiff);
}
 
Example #28
Source Project: airsonic   Author: airsonic   File: PingIT.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Test
public void pingMissingAuthTest() {
    ResponseEntity<String> response = Scanner.rest.getForEntity(
            UriComponentsBuilder.fromHttpUrl(Scanner.SERVER + "/rest/ping").toUriString(),
            String.class);

    assertThat(response.getStatusCode(), Matchers.equalTo(HttpStatus.OK));
    assertThat(response.getBody(),
            isIdenticalTo(Input.fromStream(getClass().getResourceAsStream("/blobs/ping/missing-auth.xml")))
                    .ignoreWhitespace());
}
 
Example #29
Source Project: staedi   Author: xlate   File: StaEDIXMLStreamReaderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testReadXml_WithOptionalInterchangeServiceRequests_TransactionOnly() throws Exception {
    EDIInputFactory ediFactory = EDIInputFactory.newFactory();
    XMLInputFactory xmlFactory = XMLInputFactory.newInstance();
    InputStream stream = getClass().getResourceAsStream("/x12/optionalInterchangeServices.edi");
    ediFactory.setProperty(EDIInputFactory.XML_DECLARE_TRANSACTION_XMLNS, Boolean.TRUE);
    EDIStreamReader reader = ediFactory.createEDIStreamReader(stream);
    EDIStreamReader filtered = ediFactory.createFilteredReader(reader, r -> true);
    XMLStreamReader xmlReader = ediFactory.createXMLStreamReader(filtered);
    xmlReader.next(); // Per StAXSource JavaDoc, put in START_DOCUMENT state
    XMLStreamReader xmlCursor = xmlFactory.createFilteredReader(xmlReader, r -> {
        boolean startTx = (r.getEventType() == XMLStreamConstants.START_ELEMENT && r.getName().getLocalPart().equals("TRANSACTION"));

        if (!startTx) {
            Logger.getGlobal().info("Skipping event: " + r.getEventType() + "; "
                    + (r.getEventType() == XMLStreamConstants.START_ELEMENT || r.getEventType() == XMLStreamConstants.END_ELEMENT
                            ? r.getName()
                            : ""));
        }

        return startTx;
    });

    xmlCursor.hasNext();

    TransformerFactory factory = TransformerFactory.newInstance();
    Transformer transformer = factory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
    StringWriter result = new StringWriter();
    transformer.transform(new StAXSource(xmlReader), new StreamResult(result));
    String resultString = result.toString();
    System.out.println(resultString);
    Diff d = DiffBuilder.compare(Input.fromFile("src/test/resources/x12/optionalInterchangeServices_transactionOnly.xml"))
                        .withTest(resultString).build();
    assertTrue(!d.hasDifferences(), () -> "XML unexpectedly different:\n" + d.toString(new DefaultComparisonFormatter()));
}
 
Example #30
Source Project: thorntail   Author: thorntail   File: MavenPluginMigrationTest.java    License: Apache License 2.0 5 votes vote down vote up
private void verifyMigratedPomXml() {
    Path projectDir = Paths.get(verifier.getBasedir());
    Diff diff = DiffBuilder.compare(Input.fromFile(projectDir.resolve("expected-pom.xml").toFile()))
            .withTest(Input.fromFile(projectDir.resolve("pom.xml").toFile()))
            .checkForIdentical()
            .build();
    assertThat(diff.hasDifferences())
            .as(diff.getDifferences().toString())
            .isFalse();
}