org.xmlunit.xpath.JAXPXPathEngine Java Examples

The following examples show how to use org.xmlunit.xpath.JAXPXPathEngine. 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 File: XMLUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenXPath_whenAbleToRetrieveNodes_thenCorrect() {
    ClassLoader classLoader = getClass().getClassLoader();

    Iterable<Node> i = new JAXPXPathEngine().selectNodes("//teacher", Input.fromFile(new File(classLoader.getResource("teachers.xml").getFile())).build());
    assertNotNull(i);
    int count = 0;
    for (Iterator<Node> it = i.iterator(); it.hasNext();) {
        count++;
        Node node = it.next();
        assertEquals("teacher", node.getNodeName());
        NamedNodeMap map = node.getAttributes();
        assertEquals("department", map.item(0).getNodeName());
        assertEquals("id", map.item(1).getNodeName());
        assertEquals("teacher", node.getNodeName());
    }
    assertEquals(2, count);
}
 
Example #2
Source File: XMLManipulatorTest.java    From pom-manipulation-ext with Apache License 2.0 6 votes vote down vote up
@Test
public void alterFile() throws Exception
{
    String replacementGA = "com.rebuild:servlet-api";
    String tomcatPath = "//include[starts-with(.,'org.apache.tomcat')]";

    File target = tf.newFile();
    FileUtils.copyFile( xmlFile, target );
    Project project = new Project( target, TestUtils.getDummyModel() );

    xmlManipulator.internalApplyChanges( project, new XMLState.XMLOperation( target.getName(), tomcatPath, replacementGA) );

    Diff diff = DiffBuilder.compare( fromFile( xmlFile ) ).withTest( fromFile( target ) ).build();
    assertTrue (diff.toString(), diff.hasDifferences());

    String xpathForHamcrest = "/*/*/*/*/*[starts-with(.,'com.rebuild') and local-name() = 'include']";
    Iterable<Node> i = new JAXPXPathEngine( ).selectNodes( xpathForHamcrest, fromFile( target ).build() );
    int count = 0;
    for ( Node anI : i )
    {
        count++;
        assertTrue( anI.getTextContent().startsWith( "com.rebuild:servlet-api" ) );
    }
    assertEquals(1, count);

}
 
Example #3
Source File: ElementSelectors.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Selects two elements as matching if the child elements selected
 * via XPath match using the given childSelector.
 *
 * <p>The xpath expression should yield elements.  Two elements
 * match if a DefaultNodeMatcher applied to the selected children
 * finds matching pairs for all children.</p>
 *
 * @param xpath XPath expression applied in the context of the
 * elements to chose from that selects the children to compare.
 * @param prefix2Uri maps from prefix to namespace URI.
 * @param childSelector ElementSelector to apply to the selected children.
 */
public static ElementSelector byXPath(final String xpath,
                                      Map<String, String> prefix2Uri,
                                      ElementSelector childSelector) {
    final XPathEngine engine = new JAXPXPathEngine();
    if (prefix2Uri != null) {
        engine.setNamespaceContext(prefix2Uri);
    }
    final NodeMatcher nm = new DefaultNodeMatcher(childSelector);
    return new ElementSelector() {
        @Override
        public boolean canBeCompared(Element controlElement,
                                     Element testElement) {
            Iterable<Node> controlChildren = engine.selectNodes(xpath, controlElement);
            int expected = Linqy.count(controlChildren);
            int matched =
                Linqy.count(nm.match(controlChildren,
                                     engine.selectNodes(xpath, testElement)));
            return expected == matched;
        }
    };
}
 
Example #4
Source File: MultipleNodeAssert.java    From xmlunit with 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 #5
Source File: ValueAssert.java    From xmlunit with 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 #6
Source File: AssertFactoryProvider.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
private AssertFactory<Node, SingleNodeAssert> createProxyInstance(JAXPXPathEngine engine) {

        try {
            synchronized (AssertFactoryProvider.class) {
                if (assertFactoryClass == null) {
                    assertFactoryClass = new ByteBuddy()
                            .subclass(AssertFactory.class)
                            .name(NodeAssertFactoryDelegate.class.getPackage().getName() + ".XmlUnit$AssertFactory$" + RandomString.make())
                            .method(ElementMatchers.named("createAssert"))
                            .intercept(MethodDelegation.to(new NodeAssertFactoryDelegate(createDefaultInstance(engine))))
                            .make()
                            .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
                            .getLoaded();
                }
            }

            @SuppressWarnings("unchecked")
            AssertFactory<Node, SingleNodeAssert> instance = (AssertFactory<Node, SingleNodeAssert>) assertFactoryClass.newInstance();
            return instance;

        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }

        return createDefaultInstance(engine);
    }
 
Example #7
Source File: CastorMarshallerTests.java    From java-technology-stack with 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 #8
Source File: HasXPathMatcher.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(Object object) {
    JAXPXPathEngine engine = xpf == null ? new JAXPXPathEngine() : new JAXPXPathEngine(xpf);
    if (prefix2Uri != null) {
        engine.setNamespaceContext(prefix2Uri);
    }

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

    return nodes.iterator().hasNext();
}
 
Example #9
Source File: SmtpConfigurationTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void defaultSmtpConfigurationShouldNotHaveAuthorizedNetwork() throws IOException {
    String xmlFile = SmtpConfiguration.DEFAULT.serializeAsXml();
    Source source = Input.fromString(xmlFile).build();
    XPathEngine xpath = new JAXPXPathEngine();
    Iterable<Node> allMatches = xpath.selectNodes("/smtpservers/smtpserver/authorizedAddresses", source);

    Assertions.assertThat(allMatches).isEmpty();
}
 
Example #10
Source File: InputTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @see "https://github.com/xmlunit/xmlunit/issues/84"
 */
@Test
public void testStringSourceCanBeUsedMoreThanOnce() {
    Source xml = Input.fromString("<a><b>bvalue</b><c>cvalue</c></a>").build();

    JAXPXPathEngine xpath = new JAXPXPathEngine();

    assertEquals(xpath.evaluate("//a/b", xml), "bvalue");
    assertEquals(xpath.evaluate("//a/c", xml), "cvalue");
}
 
Example #11
Source File: EvaluateXPathMatcher.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the provided XML input to the configured <code>xPath</code> field XPath expression.
 * @param input an XML input
 * @return the result of the XPath evaluation
 */
private String xPathEvaluate(Object input) {
    JAXPXPathEngine engine = xpf == null ? new JAXPXPathEngine() : new JAXPXPathEngine(xpf);
    if (prefix2Uri != null) {
        engine.setNamespaceContext(prefix2Uri);
    }

    Source s = Input.from(input).build();
    Node n = dbf != null ? Convert.toNode(s, dbf) : Convert.toNode(s);
    return engine.evaluate(xPath, n);
}
 
Example #12
Source File: AssertFactoryProvider.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
AssertFactory<Node, SingleNodeAssert> create(JAXPXPathEngine engine) {

        if (hasAssertFactoryUpperBoundOnAssertType()) {
            return createProxyInstance(engine);
        }

        return createDefaultInstance(engine);
    }
 
Example #13
Source File: SingleNodeAssert.java    From xmlunit with Apache License 2.0 4 votes vote down vote up
SingleNodeAssert(Node node, JAXPXPathEngine engine) {
    super(node, SingleNodeAssert.class);
    this.engine = engine;
}
 
Example #14
Source File: NodeAssertFactory.java    From xmlunit with Apache License 2.0 4 votes vote down vote up
public NodeAssertFactory(JAXPXPathEngine engine) {
    this.engine = engine;
}
 
Example #15
Source File: AssertFactoryProvider.java    From xmlunit with Apache License 2.0 4 votes vote down vote up
private NodeAssertFactory createDefaultInstance(JAXPXPathEngine engine) {
    return new NodeAssertFactory(engine);
}
 
Example #16
Source File: XStreamMarshallerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private static void assertXpathExists(String xPathExpression, String inXMLString){
	Source source = Input.fromString(inXMLString).build();
	Iterable<Node> nodes = new JAXPXPathEngine().selectNodes(xPathExpression, source);
	assertTrue("Expecting to find matches for Xpath " + xPathExpression, count(nodes) > 0);
}
 
Example #17
Source File: MultipleNodeAssert.java    From xmlunit with Apache License 2.0 4 votes vote down vote up
private MultipleNodeAssert(Iterable<Node> nodes, JAXPXPathEngine engine) {
    super(nodes, MultipleNodeAssert.class, ASSERT_FACTORY_PROVIDER.create(engine));
}
 
Example #18
Source File: XStreamMarshallerTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
private static void assertXpathNotExists(String xPathExpression, String inXMLString){
	Source source = Input.fromString(inXMLString).build();
	Iterable<Node> nodes = new JAXPXPathEngine().selectNodes(xPathExpression, source);
	assertEquals("Should be zero matches for Xpath " + xPathExpression, 0, count(nodes));
}
 
Example #19
Source File: XStreamMarshallerTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
private static void assertXpathExists(String xPathExpression, String inXMLString){
	Source source = Input.fromString(inXMLString).build();
	Iterable<Node> nodes = new JAXPXPathEngine().selectNodes(xPathExpression, source);
	assertTrue("Expecting to find matches for Xpath " + xPathExpression, count(nodes) > 0);
}
 
Example #20
Source File: XStreamMarshallerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private static void assertXpathNotExists(String xPathExpression, String inXMLString){
	Source source = Input.fromString(inXMLString).build();
	Iterable<Node> nodes = new JAXPXPathEngine().selectNodes(xPathExpression, source);
	assertEquals("Should be zero matches for Xpath " + xPathExpression, 0, count(nodes));
}