Skip to content

Commit

Permalink
Merge 372d0ca into 23336de
Browse files Browse the repository at this point in the history
  • Loading branch information
krystiankaluzny committed Jun 27, 2018
2 parents 23336de + 372d0ca commit a7fd314
Show file tree
Hide file tree
Showing 14 changed files with 974 additions and 46 deletions.
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -118,12 +118,13 @@ String content = xpath.evaluate("/foo/text()", source);
assert "bar".equals(content);
```

or using `HasXPathMatcher` and `EvaluateXPathMatcher`
or using `HasXPathMatcher`, `EvaluateXPathMatcher` and `XmlAssert`

```java
assertThat("<foo>bar</foo>", HasXPathMatcher.hasXPath("/foo"));
assertThat("<foo>bar</foo>", EvaluateXPathMatcher.hasXPath("/foo/text()",
equalTo("bar")));
XmlAssert.assertThat("<foo>bar</foo>").hasXPath("/foo");
```

### Validating a Document Against an XML Schema
Expand Down
Expand Up @@ -13,8 +13,16 @@
*/
package org.xmlunit.assertj;

import org.assertj.core.api.Assertions;
import org.assertj.core.api.FactoryBasedNavigableIterableAssert;
import org.w3c.dom.Node;
import org.xmlunit.builder.Input;
import org.xmlunit.util.Convert;
import org.xmlunit.xpath.JAXPXPathEngine;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import java.util.Map;

/**
* Assertion methods for {@link Iterable} of {@link Node}.
Expand All @@ -28,6 +36,7 @@
*
* assertThat(xml).nodesByXPath("//a/b").haveAttribute("attr").
* </pre>
*
* @since XMLUnit 2.6.1
*/
public class MultipleNodeAssert extends FactoryBasedNavigableIterableAssert<MultipleNodeAssert, Iterable<Node>, Node, SingleNodeAssert> {
Expand All @@ -36,10 +45,27 @@ interface SingleNodeAssertConsumer {
void accept(SingleNodeAssert t);
}

MultipleNodeAssert(Iterable<Node> nodes) {
private MultipleNodeAssert(Iterable<Node> nodes) {
super(nodes, MultipleNodeAssert.class, new NodeAssertFactory());
}

static MultipleNodeAssert create(Object xmlSource, Map<String, String> prefix2Uri, DocumentBuilderFactory dbf, String xPath) {

Assertions.assertThat(xPath).isNotBlank();

final JAXPXPathEngine engine = new JAXPXPathEngine();
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)
.describedAs("XPath \"%s\" evaluated to node set", xPath);
}

/**
* Equivalent for {@link #isNotEmpty()}.
*/
Expand Down
@@ -0,0 +1,127 @@
/*
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.assertj;

import org.assertj.core.api.AbstractAssert;
import org.assertj.core.api.Assertions;
import org.xmlunit.builder.Input;
import org.xmlunit.validation.JAXPValidator;
import org.xmlunit.validation.Languages;
import org.xmlunit.validation.ValidationResult;

import javax.xml.transform.Source;
import javax.xml.validation.Schema;

import static org.xmlunit.assertj.error.ShouldBeInvalid.shouldBeInvalid;
import static org.xmlunit.assertj.error.ShouldBeValid.shouldBeValid;

/**
* Assertion methods for XML validation.
*
* <p><b>Simple Example</b></p>
*
* <pre>
* import static org.xmlunit.assertj.XmlAssert.assertThat;
*
* final String xml = &quot;&lt;a&gt;&lt;b attr=\&quot;abc\&quot;&gt;&lt;/b&gt;&lt;/a&gt;&quot;;
*
* assertThat(xml).isValid();
* </pre>
*
* @since XMLUnit 2.6.1
*/
public class ValidationAssert extends AbstractAssert<ValidationAssert, Source> {

private final Source[] schemaSources;
private final Schema schema;

private ValidationAssert(Source actual, Source[] schemaSources, Schema schema) {
super(actual, ValidationAssert.class);
this.schemaSources = schemaSources;
this.schema = schema;
}

static ValidationAssert create(Object xmlSource, Object... schemaSources) {

Assertions.assertThat(xmlSource).isNotNull();

Assertions.assertThat(schemaSources)
.isNotNull()
.isNotEmpty()
.doesNotContainNull();

Source source = Input.from(xmlSource).build();

Source[] sources = new Source[schemaSources.length];

for (int i = 0; i < schemaSources.length; i++) {
sources[i] = Input.from(schemaSources[i]).build();
}

return new ValidationAssert(source, sources, null);
}

static ValidationAssert create(Object xmlSource, Schema schema) {

Assertions.assertThat(xmlSource).isNotNull();
Assertions.assertThat(schema).isNotNull();

Source source = Input.from(xmlSource).build();

return new ValidationAssert(source, null, schema);
}

static ValidationAssert create(Object xmlSource) {

Source source = Input.from(xmlSource).build();

return new ValidationAssert(source, null, null);
}

private ValidationResult validate() {

JAXPValidator validator = new JAXPValidator(Languages.W3C_XML_SCHEMA_NS_URI);
if (schema != null) {
validator.setSchema(schema);
} else {
validator.setSchemaSources(schemaSources);
}
return validator.validateInstance(actual);
}

/**
* Verifies that actual value is valid against given schema
*
* @throws AssertionError if the actual value is not valid against schema
*/
public ValidationAssert isValid() {
ValidationResult validationResult = validate();
if (!validationResult.isValid()) {
throwAssertionError(shouldBeValid(actual.getSystemId(), validationResult.getProblems()));
}
return this;
}

/**
* Verifies that actual value is not valid against given schema
*
* @throws AssertionError if the actual value is valid against schema
*/
public void isInvalid() {
ValidationResult validateResult = validate();
if (validateResult.isValid()) {
throwAssertionError(shouldBeInvalid(actual.getSystemId()));
}
}
}
164 changes: 164 additions & 0 deletions xmlunit-assertj/src/main/java/org/xmlunit/assertj/ValueAssert.java
@@ -0,0 +1,164 @@
/*
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.assertj;

import org.assertj.core.api.*;
import org.w3c.dom.Node;
import org.xmlunit.builder.Input;
import org.xmlunit.util.Convert;
import org.xmlunit.xpath.JAXPXPathEngine;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import java.util.Map;

import static org.xmlunit.assertj.error.ShouldBeConvertible.shouldBeConvertible;

/**
* Assertion methods for {@link String} result of XPath evaluation.
*
* <p><b>Simple Example</b></p>
*
* <pre>
* import static org.xmlunit.assertj.XmlAssert.assertThat;
*
* final String xml = &quot;&lt;a&gt;&lt;b attr=\&quot;abc\&quot;&gt;&lt;/b&gt;&lt;/a&gt;&quot;;
*
* assertThat(xml).valueByXPath("count(//a/b)").isEqualTo(3);
* </pre>
*
* @since XMLUnit 2.6.1
*/
public class ValueAssert extends AbstractCharSequenceAssert<ValueAssert, String> {

private ValueAssert(String value) {
super(value, ValueAssert.class);
}

static ValueAssert create(Object xmlSource, Map<String, String> prefix2Uri, DocumentBuilderFactory dbf, String xPath) {
Assertions.assertThat(xPath).isNotBlank();

final JAXPXPathEngine engine = new JAXPXPathEngine();
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);
}

/**
* Returns an {@code Assert} object that allows performing assertions on integer value of the {@link String} under test.
*
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value does not contain a parsable integer
*/
public AbstractIntegerAssert<?> asInt() {
isNotNull();
int value = 0;
try {
value = Integer.parseInt(actual);
} catch (NumberFormatException e) {
throwAssertionError(shouldBeConvertible(actual, "int"));
}

return Assertions.assertThat(value);
}

/**
* Returns an {@code Assert} object that allows performing assertions on integer value of the {@link String} under test.
*
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value does not contain a parsable double
*/
public AbstractDoubleAssert<?> asDouble() {
isNotNull();
double value = 0;
try {
value = Double.parseDouble(actual);
} catch (NumberFormatException e) {
throwAssertionError(shouldBeConvertible(actual, "double"));
}

return Assertions.assertThat(value);
}

/**
* Returns an {@code Assert} object that allows performing assertions on boolean value of the {@link String} under test.
* <p>
* If actual value after lowercasing is one of the following "true", "false", "1", "0", then it can be parsed to boolean.
*
* @throws AssertionError if the actual value is {@code null}.
* @throws AssertionError if the actual value does not contain a parsable boolean
*/
public AbstractBooleanAssert<?> asBoolean() {
isNotNull();
boolean value = false;
switch (actual.toLowerCase()) {
case "1":
case "true":
value = true;
break;
case "0":
case "false":
value = false;
break;
default:
throwAssertionError(shouldBeConvertible(actual, "boolean"));
}

return Assertions.assertThat(value);
}

/**
* Returns an {@code XmlAssert} object that allows performing assertions on XML value of the {@link String} under test.
*
* @throws AssertionError if the actual value is {@code null}.
*/
public XmlAssert asXml() {
isNotNull();
return XmlAssert.assertThat(actual);
}

/**
* Try convert the {@link String} under test to int using {@link #asInt()} and compare with given value.
*/
public ValueAssert isEqualTo(int expected) {
asInt().isEqualTo(expected);

return this;
}

/**
* Try convert the {@link String} under test to double using {@link #asDouble()} and compare with given value.
*/
public ValueAssert isEqualTo(double expected) {
asDouble().isEqualTo(expected);

return this;
}

/**
* Try convert the {@link String} under test to boolean using {@link #asBoolean()} and compare with given value.
*/
public ValueAssert isEqualTo(boolean expected) {
asBoolean().isEqualTo(expected);

return this;
}
}

0 comments on commit a7fd314

Please sign in to comment.