EvaluateXPathMatcherTest.java

/*
  This file is licensed to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */

package org.xmlunit.matchers;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mockito;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xmlunit.XMLUnitException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;

import static org.hamcrest.CoreMatchers.both;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.Matchers.isEmptyString;
import static org.junit.Assert.assertThat;
import static org.xmlunit.matchers.EvaluateXPathMatcher.hasXPath;

public class EvaluateXPathMatcherTest {

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testXPathCountInXmlString() throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<fruits>" +
                    "<fruit name=\"apple\"/>" +
                    "<fruit name=\"orange\"/>" +
                    "<fruit name=\"banana\"/>" +
                "</fruits>";
        assertThat(xml, hasXPath("count(//fruits/fruit)", equalTo("3")));
        assertThat(xml, hasXPath("//fruits/fruit/@name", equalTo("apple")));
        assertThat(xml, hasXPath("count(//fruits/fruit[@name=\"orange\"])", equalTo("1")));
        assertThat(xml, hasXPath("count(//fruits/fruit[@name=\"apricot\"])", equalTo("0")));
    }

    @Test
    public void testXPathAttributeValueMatchingInXmlString() throws Exception {
        String xml = "<a><b attr=\"abc\"></b></a>";
        assertThat(xml, hasXPath("//a/b/@attr", equalTo("abc")));
        assertThat(xml, hasXPath("count(//a/b/c)", equalTo("0")));


        try {
            assertThat(xml, hasXPath("//a/b/@attr", equalTo("something")));
            Assert.fail("Should throw AssertionError");
        } catch(AssertionError e) {
            assertThat(e.getMessage(), containsString("was \"abc\""));
        }

    }

    @Test
    public void testXPathAttributeValueMatchingInXmlElement() throws Exception {
        String xml = "<a><b attr=\"abc\"></b></a>";
        DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
        f.setNamespaceAware(true);
        DocumentBuilder db = f.newDocumentBuilder();
        Element xmlRootElement = db.parse(
                new InputSource(new ByteArrayInputStream(xml.getBytes("utf-8")))).getDocumentElement();
        assertThat(xmlRootElement, hasXPath("//a/b/@attr", equalTo("abc")));
    }

    @Test
    public void testXPathEvaluationWithNamespaceContext() throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<feed xmlns=\"http://www.w3.org/2005/Atom\">" +
                "   <title>Search Engine Feed</title>" +
                "   <link href=\"https://en.wikipedia.org/wiki/Web_search_engine\"/>" +
                "   <entry>" +
                "       <title>Google</title>" +
                "       <id>goog</id>" +
                "   </entry>" +
                "   <entry>" +
                "       <title>Bing</title>" +
                "       <id>msft</id>" +
                "   </entry>" +
                "</feed>";

        HashMap<String, String> prefix2Uri = new HashMap<String, String>();
        prefix2Uri.put("atom", "http://www.w3.org/2005/Atom");

        assertThat(xml, hasXPath("count(//atom:feed/atom:entry)", equalTo("2")).withNamespaceContext(prefix2Uri));
        assertThat(xml, hasXPath("//atom:feed/atom:entry/atom:title/text()",
                equalTo("Google")).withNamespaceContext(prefix2Uri));
        assertThat(xml, hasXPath("//atom:feed/atom:entry[2]/atom:title/text()",
                equalTo("Bing")).withNamespaceContext(prefix2Uri));
    }

    /**
     * Really only tests there is no NPE.
     * @see "https://github.com/xmlunit/xmlunit/issues/81"
     */
    @Test(expected = AssertionError.class)
    public void canBeCombinedWithFailingMatcher() {
        assertThat("not empty", both(isEmptyString())
                   .and(hasXPath("count(//atom:feed/atom:entry)", equalTo("2"))));
    }

    @Test
    public void canBeCombinedWithPassingMatcher() {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<fruits>" +
                    "<fruit name=\"apple\"/>" +
                    "<fruit name=\"orange\"/>" +
                    "<fruit name=\"banana\"/>" +
                "</fruits>";
        assertThat(xml, both(not(isEmptyString()))
                   .and(hasXPath("count(//fruits/fruit)", equalTo("3"))));
    }

    @Test
    public void usesDocumentBuilderFactory() throws Exception {
        DocumentBuilderFactory dFac = Mockito.mock(DocumentBuilderFactory.class);
        DocumentBuilder b = Mockito.mock(DocumentBuilder.class);
        Mockito.when(dFac.newDocumentBuilder()).thenReturn(b);
        Mockito.doThrow(new IOException())
            .when(b).parse(Mockito.any(InputSource.class));

        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<fruits>" +
                    "<fruit name=\"apple\"/>" +
                    "<fruit name=\"orange\"/>" +
                    "<fruit name=\"banana\"/>" +
                "</fruits>";
        try {
            assertThat(xml, hasXPath("count(//fruits/fruit)", equalTo("3"))
                       .withDocumentBuilderFactory(dFac));
            Assert.fail("Expected exception");
        } catch (XMLUnitException ex) {
            Mockito.verify(b).parse(Mockito.any(InputSource.class));
        }
    }

    @Test
    public void createsAUsefulMessageWhenFailingCombinedWithNotOnTheOutside() throws Exception {
        thrown.expect(AssertionError.class);
        thrown.expectMessage("not XML with XPath count(//fruits/fruit) evaluated to \"3\"");
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<fruits>" +
                    "<fruit name=\"apple\"/>" +
                    "<fruit name=\"orange\"/>" +
                    "<fruit name=\"banana\"/>" +
                "</fruits>";
        assertThat(xml, not(hasXPath("count(//fruits/fruit)", equalTo("3"))));
    }

    @Test
    public void createsAUsefulMessageWhenFailingCombinedWithNotOnTheInside() throws Exception {
        thrown.expect(AssertionError.class);
        thrown.expectMessage("XML with XPath count(//fruits/fruit) evaluated to not \"3\"");
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                "<fruits>" +
                    "<fruit name=\"apple\"/>" +
                    "<fruit name=\"orange\"/>" +
                    "<fruit name=\"banana\"/>" +
                "</fruits>";
        assertThat(xml, hasXPath("count(//fruits/fruit)", not(equalTo("3"))));
    }

    @Test
    public void usesXPathFactory() throws Exception {
        XPathFactory xFac = Mockito.mock(XPathFactory.class);
        Mockito.when(xFac.newXPath()).thenReturn(XPathFactory.newInstance().newXPath());
        assertThat("<foo/>", not(hasXPath("//bar", equalTo("a")).withXPathFactory(xFac)));
        Mockito.verify(xFac).newXPath();
    }

}