Java Code Examples for org.xmlunit.xpath.JAXPXPathEngine

The following examples show how to use org.xmlunit.xpath.JAXPXPathEngine. These examples are extracted from open source projects. 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: xmlunit   Author: xmlunit   File: ElementSelectors.java    License: 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 #2
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 #3
Source Project: xmlunit   Author: xmlunit   File: AssertFactoryProvider.java    License: 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 #4
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 #5
Source Project: pom-manipulation-ext   Author: release-engineering   File: XMLManipulatorTest.java    License: 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 #6
Source Project: tutorials   Author: eugenp   File: XMLUnitTest.java    License: 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 #7
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 #8
Source Project: james-project   Author: apache   File: SmtpConfigurationTest.java    License: 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 #9
Source Project: xmlunit   Author: xmlunit   File: InputTest.java    License: 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 #10
Source Project: xmlunit   Author: xmlunit   File: AssertFactoryProvider.java    License: 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 #11
Source Project: xmlunit   Author: xmlunit   File: EvaluateXPathMatcher.java    License: 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 Project: xmlunit   Author: xmlunit   File: HasXPathMatcher.java    License: 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 #13
Source Project: spring-analysis-note   Author: Vip-Augus   File: XStreamMarshallerTests.java    License: 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 #14
Source Project: spring-analysis-note   Author: Vip-Augus   File: XStreamMarshallerTests.java    License: 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 #15
Source Project: java-technology-stack   Author: codeEngraver   File: XStreamMarshallerTests.java    License: 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 #16
Source Project: java-technology-stack   Author: codeEngraver   File: XStreamMarshallerTests.java    License: 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 #17
Source Project: xmlunit   Author: xmlunit   File: MultipleNodeAssert.java    License: 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 Project: xmlunit   Author: xmlunit   File: SingleNodeAssert.java    License: Apache License 2.0 4 votes vote down vote up
SingleNodeAssert(Node node, JAXPXPathEngine engine) {
    super(node, SingleNodeAssert.class);
    this.engine = engine;
}
 
Example #19
Source Project: xmlunit   Author: xmlunit   File: AssertFactoryProvider.java    License: Apache License 2.0 4 votes vote down vote up
private NodeAssertFactory createDefaultInstance(JAXPXPathEngine engine) {
    return new NodeAssertFactory(engine);
}
 
Example #20
Source Project: xmlunit   Author: xmlunit   File: NodeAssertFactory.java    License: Apache License 2.0 4 votes vote down vote up
public NodeAssertFactory(JAXPXPathEngine engine) {
    this.engine = engine;
}