/* * Copyright 2005-2011 the original author or authors. * * Licensed 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.wamblee.xml; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import static junit.framework.Assert.*; import static junit.framework.TestCase.*; import static org.wamblee.xml.XMLDocument.*; public class XMLSchemaTest { private URI getResourceUri(String aResource) throws URISyntaxException { return getClass().getResource(aResource).toURI(); } private InputStream getResource(String aResource) { return getClass().getResourceAsStream(aResource); } @Test public void testReadAndValidateOkUseUri() throws Exception { XMLDocument xmldoc = xmldocument("test.xml", getResource("test.xml")).validate(getResourceUri("test.xsd")); Document doc = xmldoc.getDocument(); Element element = doc.getDocumentElement(); assertEquals("http://wamblee.org/test", element.getNamespaceURI()); String val = xmldoc.print(false); // parse the written document Document doc2 = xmldocument("input.xml", new ByteArrayInputStream(val.getBytes())).getDocument(); XmlUtils.assertEquals("", doc, doc2); } @Test public void testReadAndValidateOkUseClasspath() throws Exception { XMLDocument xmldoc = xmldocument("test.xml", getResource("test.xml")).validate( "test.xsd", new ClasspathUriResolver("org/wamblee/xml")); Document doc = xmldoc.getDocument(); Element element = doc.getDocumentElement(); assertEquals("http://wamblee.org/test", element.getNamespaceURI()); String val = xmldoc.print(false); // parse the written document Document doc2 = xmldocument("input.xml", new ByteArrayInputStream(val.getBytes())).getDocument(); XmlUtils.assertEquals("", doc, doc2); } @Test(expected = XMLException.class) public void testSchemaNotFoundUseClasspath() throws Exception { XMLDocument xmldoc = xmldocument("test.xml", getResource("test.xml")).validate( "test.xsd.unknown", new ClasspathUriResolver("org/wamblee/xml")); } @Test(expected = XMLException.class) public void testReadAndValidateNotOk() throws Exception { XMLDocument xmldoc = xmldocument("testInvalid.xml", getResource("testInvalid.xml")).validate(getResourceUri("test.xsd")); } }