org.xmlunit.XMLUnitException Java Examples

The following examples show how to use org.xmlunit.XMLUnitException. 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: ServiceRequestsComparatorHelper.java    From AuTe-Framework with Apache License 2.0 6 votes vote down vote up
/**
 * Fallback behaviour, in case of 'Content-Type' header is not present.
 */
private void compareWSRequestFallback(String expectedRequest, String actualRequest, Set<String> ignoredTags, String jsonCompareMode) throws ComparisonException {
    try {
        compareWSRequestAsXml(expectedRequest, actualRequest, ignoredTags);
    } catch (XMLUnitException uException) {
        // определяем, что упало при парсинге XML, пытаемся сравнить как JSON
        try {
            compareWSRequestAsJson(expectedRequest, actualRequest, ignoredTags, jsonCompareMode);
        } catch (JsonParsingException ex) {
            // определяем, что упало при парсинге JSON, далее сравниваем как строку
            if (uException.getCause() instanceof SAXParseException) {
                compareWSRequestAsString(defaultString(expectedRequest), actualRequest);
            }
        }
    }
}
 
Example #2
Source File: PlaceholderDifferenceEvaluatorTest.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
@Test
public void hasMatchesRegexPlaceholder_Element_Exception_MalformedRegex() {
    String control = "<elem1>${xmlunit.matchesRegex[^(\\d+$]}</elem1>";
    String test = "<elem1>23abc</elem1>";
    DiffBuilder diffBuilder = DiffBuilder.compare(control).withTest(test)
            .withDifferenceEvaluator(new PlaceholderDifferenceEvaluator(null, null, Pattern.quote("["), Pattern.quote("]"), null));

    try {
        diffBuilder.build();
        fail();
    } catch (XMLUnitException e) {
        assertThat(e.getCause().getMessage(), containsString("Unclosed group near index"));
    }
}
 
Example #3
Source File: CompareMatcherTest.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
@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 control = "<a><b></b><c/></a>";
    String test = "<a><b></b><c/><d/></a>";

    try {
        assertThat("<a><b></b><c/></a>",
                   not(isSimilarTo("<a><b></b><c/><d/></a>")
                       .withDocumentBuilderFactory(dFac)));
        Assert.fail("Expected exception");
    } catch (XMLUnitException ex) {
        Mockito.verify(b).parse(Mockito.any(InputSource.class));
    }
}
 
Example #4
Source File: EvaluateXPathMatcherTest.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
@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));
    }
}
 
Example #5
Source File: HasXPathMatcherTest.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
@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("//fruits/fruit").withDocumentBuilderFactory(dFac));
        Assert.fail("Expected exception");
    } catch (XMLUnitException ex) {
        Mockito.verify(b).parse(Mockito.any(InputSource.class));
    }
}
 
Example #6
Source File: DiffBuilderTest.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
@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 control = "<a><b></b><c/></a>";
    String test = "<a><b></b><c/><d/></a>";

    try {
        DiffBuilder.compare(control).withTest(test)
            .withDocumentBuilderFactory(dFac).build();
        Assert.fail("Expected exception");
    } catch (XMLUnitException ex) {
        Mockito.verify(b).parse(Mockito.any(InputSource.class));
    }
}
 
Example #7
Source File: DOMDifferenceEngine.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
@Override
public void compare(Source control, Source test) {
    if (control == null) {
        throw new IllegalArgumentException("control must not be null");
    }
    if (test == null) {
        throw new IllegalArgumentException("test must not be null");
    }
    try {
        Node controlNode = Convert.toNode(control, documentBuilderFactory);
        Node testNode = Convert.toNode(test, documentBuilderFactory);
        compareNodes(controlNode, xpathContextFor(controlNode),
                     testNode, xpathContextFor(testNode));
    } catch (Exception ex) {
        throw new XMLUnitException("Caught exception during comparison",
                                   ex);
    }
}
 
Example #8
Source File: test_Transform.java    From xmlunit with Apache License 2.0 6 votes vote down vote up
public void testUnwrappingOfXMLUnitException() throws Exception {
    final Exception inner = new NullPointerException();
    Transform.Trans<String> t = new Transform.Trans<String>() {
            @Override
            public String transform() {
                throw new XMLUnitException(inner);
            }
        };
    try {
        Transform.withExceptionHandling(t);
        fail("should have thrown an exception");
    } catch (XMLUnitRuntimeException ex) {
        assertFalse(ex instanceof ConfigurationException);
        assertSame(inner, ex.getCause());
    }
}
 
Example #9
Source File: TransformationTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldTransformTransformerException() throws Exception {
    doThrow(new TransformerException("foo"))
        .when(transformer)
        .transform(any(Source.class), any(Result.class));
    t.setFactory(fac);
    try {
        t.transformToString();
        fail("should have thrown XMLUnitException");
    } catch (XMLUnitException ex) {
        // assert this is not a XMLUnitException subclass
        assertEquals(XMLUnitException.class, ex.getClass());
    }
}
 
Example #10
Source File: MqMockHelper.java    From AuTe-Framework with Apache License 2.0 5 votes vote down vote up
protected ComparisonResult compareRequestsBody(ExpectedMqRequest expectedMqRequest, MockedRequest actualRequest, Map<String, Object> scenarioVariables) {
    Set<String> ignoredTags;
    if (expectedMqRequest.getIgnoredTags() != null) {
        ignoredTags = new HashSet<>(Arrays.stream(expectedMqRequest.getIgnoredTags()
            .split(","))
            .map(String::trim)
            .collect(toList()));
    } else {
        ignoredTags = new HashSet<>();
    }

    String expectedRequestBody = ExecutorUtils.evaluateExpressions(
            ExecutorUtils.insertSavedValues(expectedMqRequest.getRequestBody(), scenarioVariables),
            scenarioVariables);
    String actualRequestBody = actualRequest.getRequestBody();

    ComparisonResult comparisonResult = null;
    try {
        comparisonResult = CompareUtils.compareRequestAsXml(expectedRequestBody, actualRequestBody, ignoredTags);
    } catch (XMLUnitException xUnitEx) {
        log.info("Exception while compare mq request as XML. Trying parse as json");
        log.debug("Detached exception", xUnitEx);
        try {
            comparisonResult = CompareUtils.compareRequestAsJson(expectedRequestBody, actualRequestBody, ignoredTags, null);
        } catch (JsonParsingException jsonEx) {
            log.info("Exception while compare mq request as JSON. Trying parse as string");
            log.debug("Detached exception", jsonEx);
            try {
                comparisonResult = CompareUtils.compareRequestAsString(expectedRequestBody, actualRequestBody);
            } catch (ComparisonException strEx) {
                log.debug("Exception while compare mq request as String", strEx);
            }
        }
    }

    return comparisonResult;
}
 
Example #11
Source File: PlaceholderDifferenceEvaluatorTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test
public void hasIgnorePlaceholder_Attribute_Exception_ExclusivelyOccupy() throws Exception {
    String control = "<elem1 attr='${xmlunit.ignore}abc'/>";
    String test = "<elem1 attr='abc'/>";
    DiffBuilder diffBuilder = DiffBuilder.compare(control).withTest(test)
            .withDifferenceEvaluator(new PlaceholderDifferenceEvaluator());

    try {
        diffBuilder.build();
        fail();
    } catch (XMLUnitException e) {
        assertEquals("The placeholder must exclusively occupy the text node.", e.getCause().getMessage());
    }
}
 
Example #12
Source File: PlaceholderDifferenceEvaluatorTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test
public void hasIgnorePlaceholder_Exception_ExclusivelyOccupy() throws Exception {
    String control = "<elem1><elem11> ${xmlunit.ignore}abc</elem11></elem1>";
    String test = "<elem1><elem11>abc</elem11></elem1>";
    DiffBuilder diffBuilder = DiffBuilder.compare(control).withTest(test)
            .withDifferenceEvaluator(new PlaceholderDifferenceEvaluator());

    try {
        diffBuilder.build();
        fail();
    } catch (XMLUnitException e) {
        assertEquals("The placeholder must exclusively occupy the text node.", e.getCause().getMessage());
    }
}
 
Example #13
Source File: MatchesRegexPlaceholderHandler.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Override
public ComparisonResult evaluate(String testText, String... param) {
    if (param.length > 0 && param[0] != null && !param[0].equals("")) {
        try {
            final Pattern pattern = Pattern.compile(param[0].trim());
            if (testText != null && evaluate(testText.trim(), pattern)) {
                return EQUAL;
            }
        } catch(PatternSyntaxException e) {
            throw new XMLUnitException(e.getMessage(), e);
        }
    }
    return DIFFERENT;
}
 
Example #14
Source File: Jaxp13XpathEngine.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Execute the specified xpath syntax <code>select</code> expression
 * on the specified document and return the list of nodes (could have
 * length zero) that match
 * @param select
 * @param document
 * @return list of matching nodes
 */
public NodeList getMatchingNodes(String select, Document document)
    throws XpathException {
    try {
        return new NodeListForIterable(engine
                                       .selectNodes(select,
                                                    new DOMSource(document))
                                       );
    } catch (XMLUnitException ex) {
        throw new XpathException(ex.getCause());
    }
}
 
Example #15
Source File: Jaxp13XpathEngine.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate the result of executing the specified xpath syntax
 * <code>select</code> expression on the specified document
 * @param select
 * @param document
 * @return evaluated result
 * @throws XpathException
 */
public String evaluate(String select, Document document)
    throws XpathException {
    try {
        return engine.evaluate(select, new DOMSource(document));
    } catch (XMLUnitException ex) {
        throw new XpathException(ex.getCause());
    }
}
 
Example #16
Source File: ConvertTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldMapIOException() throws Exception {
    doThrow(new IOException())
        .when(builder)
        .parse(any(InputSource.class));

    try {
        Convert.toDocument(new StreamSource(new File(TestResources.ANIMAL_FILE)),
                           dFac);
    } catch (XMLUnitException ex) {
        // assert this is not a XMLUnitException subclass
        assertEquals(XMLUnitException.class, ex.getClass());
    }
}
 
Example #17
Source File: ConvertTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldMapSAXException() throws Exception {
    doThrow(new SAXException())
        .when(builder)
        .parse(any(InputSource.class));

    try {
        Convert.toDocument(new StreamSource(new File(TestResources.ANIMAL_FILE)),
                           dFac);
    } catch (XMLUnitException ex) {
        // assert this is not a XMLUnitException subclass
        assertEquals(XMLUnitException.class, ex.getClass());
    }
}
 
Example #18
Source File: ConvertTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldMapTransformerException() throws Exception {
    doThrow(new TransformerException("foo"))
        .when(transformer)
        .transform(any(Source.class), any(Result.class));
    try {
        Convert.toInputSource(new DOMSource(animalDocument()), tFac);
        fail("should have thrown XMLUnitException");
    } catch (XMLUnitException ex) {
        // assert this is not a XMLUnitException subclass
        assertEquals(XMLUnitException.class, ex.getClass());
    }
}
 
Example #19
Source File: test_Transform.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
public void testUnwrappingOfXMLUnitExceptionWithTransformerException() throws Exception {
    final Exception inner = new TransformerException("foo");
    Transform.Trans<String> t = new Transform.Trans<String>() {
            @Override
            public String transform() {
                throw new XMLUnitException(inner);
            }
        };
    try {
        Transform.withExceptionHandling(t);
        fail("should have thrown an exception");
    } catch (TransformerException ex) {
        assertSame(inner, ex);
    }
}
 
Example #20
Source File: JAXPValidatorTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test(expected=XMLUnitException.class)
public void validateInstanceTranslatesSAXException() throws Exception {
    doThrow(new SAXException()).when(validator).validate(any(Source.class));
    JAXPValidator v = new JAXPValidator(Languages.W3C_XML_SCHEMA_NS_URI, fac);
    v.setSchemaSource(new StreamSource(BOOK_XSD));
    v.validateInstance(new StreamSource(new File(TEST_RESOURCE_DIR
                                                 + "BookXsdGenerated.xml")));
}
 
Example #21
Source File: JAXPValidatorTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test(expected=XMLUnitException.class)
public void validateSchemaTranslatesSAXException() throws Exception {
    when(fac.newSchema(any(Source[].class))).thenThrow(new SAXException());
    JAXPValidator v = new JAXPValidator(Languages.W3C_XML_SCHEMA_NS_URI, fac);
    v.setSchemaSource(new StreamSource(BOOK_XSD));
    v.validateSchema();
}
 
Example #22
Source File: JAXPValidatorTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test public void shouldThrowWhenValidatingInstanceAndSchemaIsInvalid() {
    JAXPValidator v = new JAXPValidator(Languages.W3C_XML_SCHEMA_NS_URI);
    v.setSchemaSource(new StreamSource(new File(TEST_RESOURCE_DIR + "broken.xsd")));
    try {
        v.validateInstance(new StreamSource(new File(TEST_RESOURCE_DIR
                                                     + "BookXsdGenerated.xml")));
        fail("should have thrown an exception");
    } catch (Exception e) {
        assertThat(e, instanceOf(XMLUnitException.class));
    }
}
 
Example #23
Source File: JAXPXPathEngine.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Iterable<Node> selectNodes(String xPath, Source s) {
    try {
        return new IterableNodeList(
            (NodeList) xpath.evaluate(xPath, Convert.toInputSource(s),
                                      XPathConstants.NODESET)
                                    );
    } catch (XPathExpressionException ex) {
        throw new XMLUnitException(ex);
    }
}
 
Example #24
Source File: JAXPXPathEngine.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public String evaluate(String xPath, Source s) {
    try {
        return xpath.evaluate(xPath, Convert.toInputSource(s));
    } catch (XPathExpressionException ex) {
        throw new XMLUnitException(ex);
    }
}
 
Example #25
Source File: JAXPXPathEngine.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Iterable<Node> selectNodes(String xPath, Node n) {
    try {
        return new IterableNodeList(
            (NodeList) xpath.evaluate(xPath, n, XPathConstants.NODESET));
    } catch (XPathExpressionException ex) {
        throw new XMLUnitException(ex);
    }
}
 
Example #26
Source File: JAXPXPathEngine.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public String evaluate(String xPath, Node n) {
    try {
        return xpath.evaluate(xPath, n);
    } catch (XPathExpressionException ex) {
        throw new XMLUnitException(ex);
    }
}
 
Example #27
Source File: Input.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Build a Source from an URL.
 */
public static Builder fromURL(URL url) {
    try {
        InputStream in = null;
        try {
            in = url.openStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int read = -1;
            byte[] buf = new byte[4096];
            while ((read = in.read(buf)) >= 0) {
                if (read > 0) {
                    baos.write(buf, 0, read);
                }
            }
            StreamBuilder b =
                (StreamBuilder) fromByteArray(baos.toByteArray());
            try {
                b.setSystemId(url.toURI().toString());
            } catch (URISyntaxException use) {
                // impossible - shouldn't have been an URL in the
                // first place
                b.setSystemId(url.toString());
            }
            return b;
        } finally {
            if (in != null) {
                in.close();
            }
        }
    } catch (IOException ex) {
        throw new XMLUnitException(ex);
    }
}
 
Example #28
Source File: ParsingValidatorTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test(expected = XMLUnitException.class)
public void shouldNotAllowSchemaValidation() {
    ParsingValidator v =
        new ParsingValidator(Languages.XML_DTD_NS_URI);
    v.setSchemaSource(new StreamSource(new File(BOOK_DTD)));
    v.validateSchema();
}
 
Example #29
Source File: ParsingValidatorTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test(expected = XMLUnitException.class)
public void shouldMapSAXExceptionDuringParse() throws Exception {
    doThrow(new SAXException()).when(parser)
            .parse(any(InputSource.class), any(DefaultHandler.class));
    ParsingValidator v =
        new ParsingValidator(Languages.XML_DTD_NS_URI);
    v.setSchemaSource(new StreamSource(new File(BOOK_DTD)));
    v.validateInstance(new StreamSource(new File(TEST_RESOURCE_DIR
                                                 + "BookWithDoctype.xml")),
                       fac);
}
 
Example #30
Source File: ParsingValidatorTest.java    From xmlunit with Apache License 2.0 5 votes vote down vote up
@Test(expected = XMLUnitException.class)
public void shouldMapSAXException() throws Exception {
    when(fac.newSAXParser()).thenThrow(new SAXException());
    ParsingValidator v =
        new ParsingValidator(Languages.XML_DTD_NS_URI);
    v.validateInstance(new StreamSource(new File(TEST_RESOURCE_DIR
                                                 + "BookWithDoctype.xml")),
                       fac);
}