Initial Implementation

This commit is contained in:
apenski 2017-10-26 09:50:58 +02:00
parent 2950785e25
commit beeb104007
98 changed files with 29308 additions and 0 deletions

View file

@ -0,0 +1,149 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.api;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.impl.ConversionServiceTest;
/**
* Testet den Hashcode-Service.
*
* @author Andreas Penski
*/
public class InputFactoryTest {
private static final URL CONTENT = ConversionServiceTest.class.getResource("/valid/scenarios.xml");
private static final URL OTHER_CONTENT = ConversionServiceTest.class.getResource("/valid/report.xml");
public static final String SOME_VALUE = "some value";
private static URL NOT_EXISTING;
static {
try {
NOT_EXISTING = new URL("file://localhost/somefile.text");
} catch (MalformedURLException e) {
// just ignore;
}
}
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testDefaultDigestAlgorithm() {
assertThat(new InputFactory().getAlgorithm()).isEqualTo(InputFactory.DEFAULT_ALGORITH);
assertThat(new InputFactory("").getAlgorithm()).isEqualTo(InputFactory.DEFAULT_ALGORITH);
}
@Test
public void testSimple() {
final byte[] s1 = InputFactory.read(CONTENT).getHashCode();
final byte[] s2 = InputFactory.read(CONTENT).getHashCode();
final byte[] s3 = InputFactory.read(OTHER_CONTENT).getHashCode();
assertThat(s1).isNotEmpty();
assertThat(s1).isEqualTo(s2);
assertThat(s3).isNotEmpty();
assertThat(s1).isNotEqualTo(s3);
}
@Test
public void testWrongAlgorithm() {
expectedException.expect(IllegalStateException.class);
InputFactory service = new InputFactory("unknown");
}
@Test
public void testNullInputURL() {
expectedException.expect(IllegalArgumentException.class);
InputFactory.read((URL) null);
}
@Test
public void testInputByte() {
final Input input = InputFactory.read(SOME_VALUE.getBytes(), SOME_VALUE);
assertThat(input).isNotNull();
}
@Test
public void testInputStream() {
final Input input = InputFactory.read(new ByteArrayInputStream(SOME_VALUE.getBytes()), SOME_VALUE);
assertThat(input).isNotNull();
}
@Test
public void testNullStream() {
expectedException.expect(IllegalArgumentException.class);
final Input input = InputFactory.read((InputStream)null, SOME_VALUE);
}
@Test
public void testInputFile() throws URISyntaxException {
final Input input = InputFactory.read(new File(CONTENT.toURI()));
assertThat(input).isNotNull();
}
@Test
public void testInputPath() throws URISyntaxException {
final Input input = InputFactory.read(Paths.get(CONTENT.toURI()));
assertThat(input).isNotNull();
}
@Test
public void testNullInput() {
expectedException.expect(IllegalArgumentException.class);
InputFactory.read((byte[]) null, SOME_VALUE);
}
@Test
public void testNullInputName() {
expectedException.expect(IllegalArgumentException.class);
InputFactory.read(SOME_VALUE.getBytes(), null);
}
@Test
public void testEmptyInputName() {
expectedException.expect(IllegalArgumentException.class);
InputFactory.read(SOME_VALUE.getBytes(), "");
}
@Test
public void testUnexistingInput() {
expectedException.expect(IllegalArgumentException.class);
InputFactory.read(NOT_EXISTING);
}
}

View file

@ -0,0 +1,77 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.cmd;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import de.kosit.validationtool.api.InputFactory;
import de.kosit.validationtool.cmd.assertions.Assertions;
import de.kosit.validationtool.impl.Helper;
import de.kosit.validationtool.impl.ObjectFactory;
import de.kosit.validationtool.impl.tasks.CheckAction;
import de.kosit.validationtool.model.reportInput.CreateReportInput;
/**
* Testet das Assertion-Feature.
*
* @author Andreas Penski
*/
public class CheckAssertionActionTest {
private static final URL SAMPLE = CheckAssertionActionTest.class.getResource("/examples/assertions/ubl-0001.xml");
private static final URL SAMPLE_REPORT = CheckAssertionActionTest.class.getResource("/examples/assertions/ubl-0001-report.xml");
private static final URL SAMPLE_ASSERTIONS = CheckAssertionActionTest.class.getResource("/examples/assertions/tests-xrechnung.xml");
private CommandLine commandLine;
@Before
public void setup() throws IOException {
commandLine = new CommandLine();
commandLine.activate();
}
@Test
public void testEmptyInput() {
CheckAssertionAction a = new CheckAssertionAction(new Assertions(), ObjectFactory.createProcessor());
a.check(new CheckAction.Bag(InputFactory.read(SAMPLE), new CreateReportInput()));
assertThat(commandLine.getErrorOutput()).contains("Can not find assertions for");
}
@Test
public void testSimple() throws URISyntaxException {
final CheckAction.Bag bag = new CheckAction.Bag(InputFactory.read(SAMPLE), new CreateReportInput());
bag.setReport(Helper.load(SAMPLE_REPORT).getObject());
final Assertions assertions = Helper.load(SAMPLE_ASSERTIONS, Assertions.class);
CheckAssertionAction a = new CheckAssertionAction(assertions, ObjectFactory.createProcessor());
a.check(bag);
assertThat(commandLine.getErrorOutput()).contains("Assertion mismatch");
}
}

View file

@ -0,0 +1,130 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.cmd;
import java.io.*;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.TeeOutputStream;
import lombok.Getter;
import lombok.Setter;
/**
* Helferlein um Ausgaben auf der Kommandozeile zu testen.
*
* @author Andreas Penski
*/
public class CommandLine {
private static ReplaceableOutputStream<ByteArrayOutputStream> out = new ReplaceableOutputStream<>();
private static ReplaceableOutputStream<ByteArrayOutputStream> error = new ReplaceableOutputStream<>();
static {
// Initialisierung muss vor SL4J's SimpleLogger erfolgen, sonst sind logs nicht erfasst.
// deshalb darf diese Klasse kein Log haben
System.setOut(new PrintStream(new TeeOutputStream(System.out, out)));
System.setErr(new PrintStream(new TeeOutputStream(System.err, error)));
}
public String getOutput() {
return new String(out.getOut().toByteArray());
}
public String getErrorOutput() {
return new String(error.getOut().toByteArray());
}
public List<String> getOutputLines() {
return readLines(out.getOut().toByteArray());
}
public List<String> getErrorLines() {
return readLines(error.getOut().toByteArray());
}
private List<String> readLines(byte[] bytes) {
try ( ByteArrayInputStream in = new ByteArrayInputStream(bytes);
Reader r = new InputStreamReader(in) ) {
return IOUtils.readLines(r);
} catch (IOException e) {
throw new IllegalStateException("Can not read input");
}
}
public void activate() {
out.setOut(new ByteArrayOutputStream());
error.setOut(new ByteArrayOutputStream());
}
public void deactivate() {
out.setOut(null);
error.setOut(null);
}
/**
* Simpler Proxy für {@link OutputStream}, dessen target ausgetauscht werden kann.
*
* @param <O> Typ des eigentlichen {@link OutputStream}
*/
private static class ReplaceableOutputStream<O extends OutputStream> extends OutputStream {
@Getter
@Setter
private O out;
public void write(int idx) throws IOException {
if (out != null) {
this.out.write(idx);
}
}
public void write(byte[] bts) throws IOException {
if (out != null) {
this.out.write(bts);
}
}
public void write(byte[] bts, int st, int end) throws IOException {
if (out != null) {
this.out.write(bts, st, end);
}
}
public void flush() throws IOException {
if (out != null) {
this.out.flush();
}
}
public void close() throws IOException {
if (out != null) {
this.out.close();
}
}
}
}

View file

@ -0,0 +1,178 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.cmd;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import static de.kosit.validationtool.impl.Helper.*;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Testet die Parameter des Kommandozeilen-Tools.
*
* @author Andreas Penski
*/
public class CommandlineApplicationTest {
public static final String RESULT_OUTPUT = "Processing 1 object(s) completed";
private CommandLine commandLine;
@Before
public void setup() throws IOException {
commandLine = new CommandLine();
commandLine.activate();
}
@Test
public void testHelp() {
String[] args = new String[] { "-?" };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).isEmpty();
checkForHelp(commandLine.getOutputLines());
}
private void checkForHelp(List<String> outputLines) {
assertThat(outputLines.size()).isGreaterThan(0);
outputLines.subList(1, outputLines.size() - 1).forEach(l -> assertThat(l.startsWith(" -") || l.startsWith(" ")));
}
@Test
public void testRequiredScenarioFile() {
String[] args = new String[] { "-d", "arguments", "egal welche", "argument drin sind" };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).isNotEmpty();
assertThat(commandLine.getErrorOutput()).contains("Missing required option: s");
}
@Test
public void testNotExistingScenarioFile() {
String[] args = new String[] { "-s", Paths.get(NOT_EXISTING).toString(), Paths.get(NOT_EXISTING).toString() };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).isNotEmpty();
assertThat(commandLine.getErrorOutput()).contains("Not a valid path for scenario definition specified");
}
@Test
public void testIncorrectRepository() {
String[] args = new String[] { "-s", Paths.get(SCENARIO_FILE).toString(), Paths.get(NOT_EXISTING).toString() };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).isNotEmpty();
assertThat(commandLine.getErrorOutput()).contains("Can not load schema from sources");
}
@Test
public void testNotExistingTestTarget() {
String[] args = new String[] { "-s", Paths.get(SCENARIO_FILE).toString(), "-r", Paths.get(REPOSITORY).toString(),
Paths.get(NOT_EXISTING).toString() };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).isNotEmpty();
assertThat(commandLine.getErrorOutput()).contains("No test targets found");
}
@Test
public void testValidMinimalConfiguration() {
String[] args = new String[] { "-s", Paths.get(SCENARIO_FILE).toString(), "-r", Paths.get(REPOSITORY).toString(),
Paths.get(SAMPLE).toString() };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).contains(RESULT_OUTPUT);
}
@Test
public void testValidMultipleInput() {
String[] args = new String[] { "-s", Paths.get(SCENARIO_FILE).toString(), "-r", Paths.get(REPOSITORY).toString(),
Paths.get(SAMPLE).toString(), Paths.get(SAMPLE2).toString() };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).contains("Processing 2 object(s) completed");
}
@Test
public void testValidDirectoryInput() {
String[] args = new String[] { "-s", Paths.get(SCENARIO_FILE).toString(), "-r", Paths.get(REPOSITORY).toString(),
Paths.get(SAMPLE_DIR).toString() };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).contains("Processing 4 object(s) completed");
}
@Test
public void testValidOutputConfiguration() throws IOException {
Path output = Paths.get("output");
// assertThat(output).doesNotExist();
String[] args = new String[] { "-s", Paths.get(SCENARIO_FILE).toString(), "-o", output.getFileName().toString(), "-r",
Paths.get(REPOSITORY).toString(), Paths.get(SAMPLE).toString() };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).contains(RESULT_OUTPUT);
assertThat(output).exists();
assertThat(Files.list(output)).hasSize(1);
}
@Test
public void testNoInput() {
// assertThat(output).doesNotExist();
String[] args = new String[] { "-s", Paths.get(SCENARIO_FILE).toString(), "-r", Paths.get(REPOSITORY).toString(), };
CommandLineApplication.mainProgram(args);
checkForHelp(commandLine.getOutputLines());
}
@Test
public void testPrint() {
String[] args = new String[] { "-s", Paths.get(SCENARIO_FILE).toString(), "-p", "-r", Paths.get(REPOSITORY).toString(),
Paths.get(SAMPLE).toString() };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).contains(RESULT_OUTPUT);
assertThat(commandLine.getOutputLines()).contains("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
}
@Test
public void testHtmlExtraktion() throws IOException {
Path output = Files.createTempDirectory("pruef-tool-test");
String[] args = new String[] { "-s", Paths.get(SCENARIO_FILE).toString(), "-h", "-o", output.toAbsolutePath().toString(), "-r",
Paths.get(REPOSITORY).toString(), Paths.get(SAMPLE).toString() };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).contains(RESULT_OUTPUT);
assertThat(Files.list(output).filter(f -> f.toString().endsWith(".html")).count()).isGreaterThan(0);
}
@Test
public void testAssertionsExtraktion() throws IOException {
String[] args = new String[] { "-d", "-s", Paths.get(SCENARIO_FILE).toString(), "-r", Paths.get(REPOSITORY).toString(), "-c",
Paths.get(ASSERTIONS).toString(), Paths.get(REPOSITORY).toString(), Paths.get(SAMPLE).toString() };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).contains(RESULT_OUTPUT);
assertThat(commandLine.getErrorOutput()).contains("Can not find assertions for ");
}
@Test
public void testDebugFlag() throws IOException {
String[] args = new String[] { "-s", Paths.get(SCENARIO_FILE).toString(), "-r", "unknown", "-d", Paths.get(ASSERTIONS).toString() };
CommandLineApplication.mainProgram(args);
assertThat(commandLine.getErrorOutput()).contains("at de.kosit.validationtool");
}
}

View file

@ -0,0 +1,74 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.cmd;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import de.kosit.validationtool.api.InputFactory;
import de.kosit.validationtool.impl.Helper;
import de.kosit.validationtool.impl.tasks.CheckAction;
/**
* Testet die HTML-Extrkation des Kommondazeilenprogramms.
*
* @author Andreas Penski
*/
public class ExtractHtmlActionTest {
private static final URL REPORT = SerializeReportActionTest.class.getResource("/examples/results/report.xml");
private ExtractHtmlContentAction action;
private Path tmpDirectory;
@Before
public void setup() throws IOException {
tmpDirectory = Files.createTempDirectory("checktool");
action = new ExtractHtmlContentAction(Helper.loadTestRepository(), tmpDirectory);
}
@After
public void tearDown() throws IOException {
FileUtils.deleteDirectory(tmpDirectory.toFile());
}
@Test
public void testSimple() throws IOException {
CheckAction.Bag b = new CheckAction.Bag(InputFactory.read(REPORT));
assertThat(action.isSkipped(b)).isTrue();
b.setReport(Helper.load(REPORT).getObject());
action.check(b);
assertThat(action.isSkipped(b)).isFalse();
action.check(b);
assertThat(b.isStopped()).isFalse();
assertThat(Files.list(tmpDirectory).collect(Collectors.toList())).hasSize(1);
}
}

View file

@ -0,0 +1,70 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.cmd;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.URL;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import de.kosit.validationtool.api.InputFactory;
import de.kosit.validationtool.impl.Helper;
import de.kosit.validationtool.impl.tasks.CheckAction;
/**
* @author Andreas Penski
*/
public class PrintReportActionTest {
private static final URL REPORT = SerializeReportActionTest.class.getResource("/examples/results/report.xml");
private CommandLine commandLine;
private PrintReportAction action;
@Before
public void setup() throws IOException {
commandLine = new CommandLine();
commandLine.activate();
action = new PrintReportAction();
}
@After
public void tearDownd() throws IOException {
commandLine.deactivate();
}
@Test
public void testSimpleSerialize() {
CheckAction.Bag b = new CheckAction.Bag(InputFactory.read(REPORT));
b.setReport(Helper.load(REPORT).getObject());
assertThat(action.isSkipped(b)).isFalse();
action.check(b);
assertThat(b.isStopped()).isFalse();
assertThat(commandLine.getOutput()).isNotEmpty();
assertThat(commandLine.getOutput()).startsWith("<?xml version=\"1.0\" ");
assertThat(commandLine.getErrorOutput()).isEmpty();
}
}

View file

@ -0,0 +1,78 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.cmd;
import de.kosit.validationtool.api.InputFactory;
import de.kosit.validationtool.impl.Helper;
import de.kosit.validationtool.impl.tasks.CheckAction;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Andreas Penski
*/
public class SerializeReportActionTest {
private static final URL REPORT = SerializeReportActionTest.class.getResource("/examples/results/report.xml");
private Path tmpDirectory;
private SerializeReportAction action;
@Before
public void setup() throws IOException {
tmpDirectory = Files.createTempDirectory("checktool");
action = new SerializeReportAction(tmpDirectory);
}
@After
public void tearDown() throws IOException {
FileUtils.deleteDirectory(tmpDirectory.toFile());
}
@Test
public void testSimpleSerialize() {
CheckAction.Bag b = new CheckAction.Bag(InputFactory.read(REPORT));
assertThat(action.isSkipped(b)).isTrue();
b.setReport(Helper.load(REPORT).getObject());
assertThat(action.isSkipped(b)).isFalse();
action.check(b);
assertThat(b.isStopped()).isFalse();
assertThat(tmpDirectory.toFile().listFiles()).hasSize(1);
}
//ERPT-83
@Test
public void testName(){
final String name = "some.name.with.dots";
CheckAction.Bag b = new CheckAction.Bag(InputFactory.read("ega".getBytes(), name + ".xml"));
assertThat(b.getName()).isEqualTo(name);
}
}

View file

@ -0,0 +1,111 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.impl;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.MalformedURLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.xml.validation.Schema;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import net.sf.saxon.s9api.XPathExecutable;
import net.sf.saxon.s9api.XsltExecutable;
/**
* Testet das ContentRepository.
*
* @author Andreas Penski
*/
public class ContentRepositoryTest {
private ContentRepository repository;
@Rule
public ExpectedException exception = ExpectedException.none();
@Before
public void setup() {
repository = new ContentRepository(ObjectFactory.createProcessor(), Helper.REPOSITORY);
}
@Test
public void testCreateSchema() throws MalformedURLException {
final Schema schema = repository.createSchema(Helper.ASSERTION_SCHEMA.toURL());
assertThat(schema).isNotNull();
}
@Test
public void testSchemaCaching() throws MalformedURLException {
final Schema schema = repository.getReportInputSchema();
assertThat(repository.getReportInputSchema()).isSameAs(schema);
}
@Test
public void testCreateSchemaNotExisting()throws Exception {
exception.expect(IllegalStateException.class);
repository.createSchema(Helper.ASSERTION_SCHEMA.resolve("noexisting").toURL());
}
@Test
public void testLoadXSLT() throws MalformedURLException {
final XsltExecutable executable = repository.loadXsltScript(Helper.SAMPLE_XSLT);
assertThat(executable).isNotNull();
}
@Test
public void testLoadXSLTNotExisting() throws MalformedURLException {
exception.expect(IllegalStateException.class);
repository.loadXsltScript(Helper.SAMPLE_XSLT.resolve("notexisting"));
}
@Test
public void testXpathCreation() throws MalformedURLException {
XPathExecutable xPath = repository.createXPath("//html", null);
assertThat(xPath).isNotNull();
xPath = repository.createXPath("//html", Collections.emptyMap());
assertThat(xPath).isNotNull();
Map<String,String> namespace = new HashMap<>();
namespace.put("html", "http://www.w3.org/1999/xhtml");
xPath = repository.createXPath("//html:html", namespace );
assertThat(xPath).isNotNull();
}
@Test
public void testXpathCreationWithoutNamespace(){
exception.expect(IllegalStateException.class);
repository.createXPath("//html:html", null );
}
@Test
public void testIllegalXpath(){
exception.expect(IllegalStateException.class);
repository.createXPath("kein Xpath Ausdruck", null );
}
}

View file

@ -0,0 +1,121 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.impl;
import static org.assertj.core.api.Java6Assertions.assertThat;
import java.io.File;
import java.io.Serializable;
import java.net.URISyntaxException;
import java.net.URL;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.model.scenarios.Scenarios;
/**
* Simple test for testing the jaxb conversion service.
*
* @author apenski
*/
public class ConversionServiceTest {
private static final URL VALID_XML = ConversionServiceTest.class.getResource("/valid/scenarios.xml");
private static final URL INVALID_XML = ConversionServiceTest.class.getResource("/invalid/scenarios-invalid.xml");
private static final URL ILLFORMED_XML = ConversionServiceTest.class.getResource("/invalid/scenarios-illformed.xml");
private static final URL SCHEMA = ConversionServiceTest.class.getResource("/xsd/scenarios.xsd");
@Rule
public ExpectedException exception = ExpectedException.none();
private ConversionService service;
private ContentRepository repository;
@Before
public void setup() {
service = new ConversionService();
repository = new ContentRepository(ObjectFactory.createProcessor(), new File("src/test/resources/examples/repository").toURI());
}
@Test
public void testMarshalNull() {
exception.expect(ConversionService.ConversionExeption.class);
service.writeXml(null);
}
@Test
public void testMarshalUnknown() {
exception.expect(ConversionService.ConversionExeption.class);
service.writeXml(new Serializable() {
});
}
@Test
public void testUnmarshal() throws URISyntaxException {
final Scenarios s = service.readXml(VALID_XML.toURI(), Scenarios.class);
assertThat(s).isNotNull();
assertThat(s.getName()).isEqualToIgnoringCase("XInneres");
}
@Test
public void testUnmarshalWithSchema() throws URISyntaxException {
final Scenarios s = service.readXml(VALID_XML.toURI(), Scenarios.class, repository.createSchema(SCHEMA));
assertThat(s).isNotNull();
assertThat(s.getName()).isEqualToIgnoringCase("XInneres");
}
@Test
public void testUnmarshalInvalidXml() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(INVALID_XML.toURI(), Scenarios.class, repository.createSchema(SCHEMA));
}
@Test
public void testUnmarshalIllFormed() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(ILLFORMED_XML.toURI(), Scenarios.class, repository.createSchema(SCHEMA));
}
@Test
public void testUnmarshalEmpty() {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(null, Scenarios.class);
}
@Test
public void testUnmarshalUnknownType() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(VALID_XML.toURI(), ConversionService.class);
}
@Test
public void testUnmarshalWithoutType() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(VALID_XML.toURI(), null);
}
}

View file

@ -0,0 +1,75 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.impl;
import de.kosit.validationtool.api.CheckConfiguration;
import de.kosit.validationtool.api.Input;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static de.kosit.validationtool.api.InputFactory.read;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test das Check-Interface
*
* @author Andreas Penski
*/
public class DefaultCheckTest {
private static final URL SCENARIO_DEFINITION = ScenarioRepositoryTest.class.getResource("/examples/UBLReady/scenarios-2.xml");
private static final URL VALID_EXAMPLE = ScenarioRepositoryTest.class
.getResource("/examples/UBLReady/UBLReady_EU_UBL-NL_20170102_FULL.xml");
public static final int MULTI_COUNT = 5;
private DefaultCheck implementation;
@Before
public void setup() throws URISyntaxException {
CheckConfiguration d = new CheckConfiguration(SCENARIO_DEFINITION.toURI());
d.setScenarioRepository(new File("src/test/resources/examples/repository").toURI());
implementation = new DefaultCheck(d);
}
@Test
public void testHappyCase() throws Exception {
final Document doc = implementation.check(read(VALID_EXAMPLE));
assertThat(doc).isNotNull();
}
@Test
public void testMultipleCase() throws Exception {
final List<Input> input = IntStream.range(0, MULTI_COUNT).mapToObj(i -> read(VALID_EXAMPLE)).collect(Collectors.toList());
final List<Document> docs = implementation.check(input);
assertThat(docs).isNotNull();
assertThat(docs).hasSize(MULTI_COUNT);
}
}

View file

@ -0,0 +1,88 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.impl;
import static de.kosit.validationtool.api.InputFactory.read;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.net.URL;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.w3c.dom.Document;
import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.impl.tasks.DocumentParseAction;
import de.kosit.validationtool.model.reportInput.XMLSyntaxError;
/**
* @author Andreas Penski
*/
public class DocumentParserTest {
private static final URL CONTENT = ConversionServiceTest.class.getResource("/valid/scenarios.xml");
private static final URL ILLFORMED = ConversionServiceTest.class.getResource("/invalid/scenarios-illformed.xml");
private static final URL NOT_EXISTING = ConversionServiceTest.class.getResource("/does not exist.xml");
@Rule
public ExpectedException exception = ExpectedException.none();
private DocumentParseAction parser;
@Before
public void setup() {
parser = new DocumentParseAction();
}
@Test
public void testSimple() throws IOException {
final Result<Document, XMLSyntaxError> result = parser.parseDocument(read(CONTENT));
assertThat(result).isNotNull();
assertThat(result.getObject()).isNotNull();
assertThat(result.getErrors()).isEmpty();
assertThat(result.isValid()).isTrue();
}
@Test
public void testIllformed() throws IOException {
final Result<Document, XMLSyntaxError> result = parser.parseDocument(read(ILLFORMED));
assertThat(result).isNotNull();
assertThat(result.getErrors()).isNotEmpty();
assertThat(result.getObject()).isNull();
assertThat(result.isValid()).isFalse();
}
@Test
public void testNullInput() {
exception.expect(IllegalArgumentException.class);
parser.parseDocument(null);
}
}

View file

@ -0,0 +1,102 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.impl;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.w3c.dom.Document;
import de.kosit.validationtool.api.InputFactory;
import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.impl.tasks.CheckAction;
import de.kosit.validationtool.impl.tasks.DocumentParseAction;
import de.kosit.validationtool.model.reportInput.XMLSyntaxError;
/**
* Helferlein für Test-Artefakte
*
* @author Andreas Penski
*/
public class Helper {
public static final URI SOURCE_ROOT = Paths.get("src/main/resources").toUri();
public static final URI MODEL_ROOT = Paths.get("src/main/model").toUri();
public static final URI ASSERTION_SCHEMA = MODEL_ROOT.resolve("xsd/assertions.xsd");
public static final URI SCENARIO_SCHEMA = MODEL_ROOT.resolve("xsd/scenarios.xsd");
public static final URI TEST_ROOT = Paths.get("src/test/resources").toUri();
public static final URI EXAMPLES_DIR = TEST_ROOT.resolve("examples/");
public static final URI ASSERTIONS = EXAMPLES_DIR.resolve("assertions/tests-xrechnung.xml");
public static final URI SCENARIO_FILE = EXAMPLES_DIR.resolve("UBLReady/scenarios-2.xml");
public static final URI REPOSITORY = EXAMPLES_DIR.resolve("repository/");
public static final URI NOT_EXISTING = EXAMPLES_DIR.resolve("doesnotexist");
public static final URI SAMPLE_DIR = EXAMPLES_DIR.resolve("UBLReady/");
public static final URI SAMPLE_XSLT = EXAMPLES_DIR.resolve("repository/resources/eRechnung/report.xsl");
public static final URI SAMPLE = SAMPLE_DIR.resolve("UBLReady_EU_UBL-NL_20170102_FULL.xml");
public static final URI SAMPLE2 = SAMPLE_DIR.resolve("UBLReady_EU_UBL-NL_20170102_FULL-invalid.xml");
/**
* Lädt ein XML-Dokument von der gegebenen URL
*
* @param url die url die geladen werden soll
* @return ein result objekt mit Dokument
*/
public static Result<Document, XMLSyntaxError> load(URL url) {
DocumentParseAction a = new DocumentParseAction();
CheckAction.Bag b = new CheckAction.Bag(InputFactory.read(url));
a.check(b);
return b.getParserResult();
}
public static <T> T load(URL url, Class<T> type) throws URISyntaxException {
ConversionService c = new ConversionService();
c.initialize(de.kosit.validationtool.model.reportInput.ObjectFactory.class.getPackage(),
de.kosit.validationtool.cmd.assertions.ObjectFactory.class.getPackage(),
de.kosit.validationtool.model.scenarios.ObjectFactory.class.getPackage());
return c.readXml(url.toURI(), type);
}
/**
* Lädt das default test repository mit Artefacten für Unit-Tests
*
* @return ein {@link ContentRepository}
*/
public static ContentRepository loadTestRepository() {
return new ContentRepository(ObjectFactory.createProcessor(), new File("src/test/resources/examples/repository").toURI());
}
}

View file

@ -0,0 +1,74 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.impl;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.net.URISyntaxException;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.URIResolver;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
/**
* Testet den Uri-Resolver der relative auflösen soll
*
* @author Andreas Penski
*/
public class RelativeUriResolverTest {
private static final URI BASE;
static {
try {
BASE = RelativeUriResolver.class.getResource("/examples/assertions/").toURI();
} catch (URISyntaxException e) {
throw new IllegalStateException(e);
}
}
@Rule
public ExpectedException exception = ExpectedException.none();
private URIResolver resolver = new RelativeUriResolver(BASE);
@Test
public void testSucces() throws TransformerException {
final Source resource = resolver.resolve("ubl-0001.xml", BASE.toASCIIString());
assertThat(resource).isNotNull();
}
@Test
public void testNotExisting() throws TransformerException {
exception.expect(IllegalStateException.class);
resolver.resolve("ubl-0001", BASE.toASCIIString());
}
@Test
public void testOutOfPath() throws TransformerException {
exception.expect(IllegalStateException.class);
resolver.resolve("../results/report.xml", BASE.toASCIIString());
}
}

View file

@ -0,0 +1,76 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.impl;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.net.URL;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.w3c.dom.Document;
import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.s9api.*;
/**
* Testet verschiedene Saxon Security Einstellungen.
*
* @author Andreas Penski
*/
@Slf4j
public class SaxonSecurityTest {
@Test
public void testEvilStylesheets() throws IOException {
Processor p = ObjectFactory.createProcessor();
for (int i = 1; i <= 5; i++) {
try {
URL resource = SaxonSecurityTest.class.getResource(String.format("/evil/evil%s.xsl", i));
final XsltCompiler compiler = p.newXsltCompiler();
final RelativeUriResolver resolver = new RelativeUriResolver(Helper.REPOSITORY);
compiler.setURIResolver(resolver);
final XsltExecutable exetuable = compiler.compile(new StreamSource(resource.openStream()));
final XsltTransformer transformer = exetuable.load();
final Document document = ObjectFactory.createDocumentBuilder(false).newDocument();
document.createElement("root");
Document result = ObjectFactory.createDocumentBuilder(false).newDocument();
transformer.getUnderlyingController().setUnparsedTextURIResolver(resolver);
transformer.setURIResolver(resolver);
transformer.setSource(new DOMSource(document));
transformer.setDestination(new DOMDestination(result));
transformer.transform();
// wenn der Punkt erreicht wird, sollte wenigstens, das Element evil nicht mit 'bösen' Inhalten gefüllt sein!
if (StringUtils.isNotBlank(result.getDocumentElement().getTextContent())) {
fail(String.format("Saxon configuration should prevent expansion within %s", resource));
}
} catch (SaxonApiException | RuntimeException e) {
log.info("Expected exception detected", e.getMessage());
}
}
}
}

View file

@ -0,0 +1,101 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.impl;
import static de.kosit.validationtool.api.InputFactory.read;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.w3c.dom.Document;
import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.impl.tasks.DocumentParseAction;
import de.kosit.validationtool.model.scenarios.ScenarioType;
import de.kosit.validationtool.model.scenarios.Scenarios;
/**
* Testet das {@link ScenarioRepository}.
*
* @author Andreas Penski
*/
public class ScenarioRepositoryTest {
private static final URL SAMPLE = ScenarioRepositoryTest.class.getResource("/valid/scenarios.xml");
@Rule
public ExpectedException expectedException = ExpectedException.none();
ContentRepository content;
private ScenarioRepository repository;
@Before
public void setup() {
content = new ContentRepository(ObjectFactory.createProcessor(), new File("src/test/resources/examples/repository").toURI());
Scenarios def = new Scenarios();
ScenarioType t = new ScenarioType();
t.setMatch("//*:name");
t.setName("Test");
t.initialize(content, true);
def.getScenario().add(t);
repository = new ScenarioRepository(ObjectFactory.createProcessor(), content);
repository.initialize(def);
}
@Test
public void testHappyCase() throws Exception {
final Result<ScenarioType, String> scenario = repository.selectScenario(load(SAMPLE));
assertThat(scenario).isNotNull();
assertThat(scenario.isValid()).isTrue();
}
@Test
public void testNonMatch() throws Exception {
repository.getScenarios().getScenario().clear();
final Result<ScenarioType, String> scenario = repository.selectScenario(load(SAMPLE));
assertThat(scenario).isNotNull();
assertThat(scenario.isValid()).isFalse();
}
@Test
public void testMultiMatch() throws Exception {
ScenarioType t = new ScenarioType();
t.setMatch("//*:name");
t.setName("Test");
t.initialize(content, true);
repository.getScenarios().getScenario().add(t);
final Result<ScenarioType, String> scenario = repository.selectScenario(load(SAMPLE));
assertThat(scenario).isNotNull();
assertThat(scenario.isValid()).isFalse();
}
private Document load(URL url) throws IOException {
DocumentParseAction p = new DocumentParseAction();
return p.parseDocument(read(url)).getObject();
}
}

View file

@ -0,0 +1,115 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.impl;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Collections;
import javax.xml.validation.Schema;
import org.junit.Before;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.api.InputFactory;
import de.kosit.validationtool.impl.model.Result;
import de.kosit.validationtool.impl.tasks.CheckAction;
import de.kosit.validationtool.impl.tasks.SchemaValidationAction;
import de.kosit.validationtool.model.reportInput.CreateReportInput;
import de.kosit.validationtool.model.scenarios.ResourceType;
import de.kosit.validationtool.model.scenarios.ScenarioType;
import de.kosit.validationtool.model.scenarios.ValidateWithXmlSchema;
/**
* Testet die {@linkSchemaValidatorAction}.
*
* @author Andreas Penski
*/
public class SchemaValidatorActionTest {
private static final URL VALID_EXAMPLE = SchemaValidatorActionTest.class
.getResource("/examples/UBLReady/UBLReady_EU_UBL-NL_20170102_FULL.xml");
private static final URI INVALID_EXAMPLE = Helper.TEST_ROOT.resolve("invalid/scenarios-invalid.xml");
public ExpectedException expectedException = ExpectedException.none();
private SchemaValidationAction service;
private ContentRepository repository;
@Before
public void setup() {
service = new SchemaValidationAction();
repository = new ContentRepository(ObjectFactory.createProcessor(), Helper.REPOSITORY);
}
@Test
public void testSimple() {
CheckAction.Bag bag = new CheckAction.Bag(InputFactory.read(VALID_EXAMPLE), new CreateReportInput());
bag.setParserResult(Helper.load(VALID_EXAMPLE));
ScenarioType t = new ScenarioType();
ValidateWithXmlSchema v = new ValidateWithXmlSchema();
ResourceType r = new ResourceType();
r.setLocation("resources/eRechnung/UBL-2.1/xsdrt/maindoc/UBL-Invoice-2.1.xsd");
r.setName("invoice");
v.getResource().add(r);
t.setValidateWithXmlSchema(v);
t.initialize(repository, true);
bag.setScenarioSelectionResult(new Result<>(t, Collections.emptyList()));
service.check(bag);
assertThat(bag.getSchemaValidationResult().isValid()).isTrue();
assertThat(bag.getSchemaValidationResult()).isNotNull();
assertThat(bag.getSchemaValidationResult().isValid()).isTrue();
}
@Test
public void testValidationFailure() throws MalformedURLException {
CheckAction.Bag bag = new CheckAction.Bag(InputFactory.read(INVALID_EXAMPLE.toURL()), new CreateReportInput());
bag.setParserResult(Helper.load(INVALID_EXAMPLE.toURL()));
ScenarioType t = new ScenarioType();
ValidateWithXmlSchema v = new ValidateWithXmlSchema();
ResourceType r = new ResourceType();
r.setLocation(Helper.REPOSITORY.relativize(Helper.SCENARIO_SCHEMA).getRawPath());
r.setName("invoice");
v.getResource().add(r);
t.setValidateWithXmlSchema(v);
t.initialize(repository, true);
bag.setScenarioSelectionResult(new Result<>(t, Collections.emptyList()));
service.check(bag);
assertThat(bag.getSchemaValidationResult().isValid()).isFalse();
bag.getSchemaValidationResult().getErrors().forEach(e->{
assertThat(e.getRowNumber()).isGreaterThan(0);
assertThat(e.getColumnNumber()).isGreaterThan(0);
});
}
@Test
public void testSchemaReferences() {
final Schema reportInputSchema = repository.getReportInputSchema();
assertThat(reportInputSchema).isNotNull();
}
}

View file

@ -0,0 +1,86 @@
/*
* Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under
* one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. KoSIT licenses this file
* 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 de.kosit.validationtool.impl;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import de.kosit.validationtool.model.scenarios.Scenarios;
/**
* Testet die Versionierung von Scenario-Dateien aka Konfigurationsdaten.
*
* @author Andreas Penski
*/
public class VersioningTest {
private static final URL BASE = VersioningTest.class.getResource("/examples/versioning/scenarios-base.xml");
private static final URL INCREMENT = VersioningTest.class.getResource("/examples/versioning/scenarios-increment.xml");
private static final URL NEW_FEATURE = VersioningTest.class.getResource("/examples/versioning/scenarios-newfeature.xml");
private static final URL NEW_VERSION = VersioningTest.class.getResource("/examples/versioning/scenarios-newVersion.xml");
@Rule
public ExpectedException exception = ExpectedException.none();
private ConversionService service;
private ContentRepository repository;
@Before
public void setup() {
service = new ConversionService();
repository = new ContentRepository(ObjectFactory.createProcessor(), new File("src/test/resources/examples/repository").toURI());
}
@Test
public void testBase() throws URISyntaxException {
final Scenarios result = service.readXml(BASE.toURI(), Scenarios.class, repository.getScenarioSchema());
assertThat(result).isNotNull();
}
@Test
public void testFrameworkIncrement() throws URISyntaxException {
final Scenarios result = service.readXml(INCREMENT.toURI(), Scenarios.class, repository.getScenarioSchema());
assertThat(result).isNotNull();
}
@Test
public void testNewFeature() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(NEW_FEATURE.toURI(), Scenarios.class, repository.getScenarioSchema());
}
@Test
public void testNewVersion() throws URISyntaxException {
exception.expect(ConversionService.ConversionExeption.class);
service.readXml(NEW_VERSION.toURI(), Scenarios.class, repository.getScenarioSchema());
}
}