org.custommonkey.xmlunit.XMLUnit Java Examples

The following examples show how to use org.custommonkey.xmlunit.XMLUnit. 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 Project: micro-integrator   Author: wso2   File: CacheMediatorTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testMediatorSerializer() {
    OMElement mediatorElement = SynapseConfigUtils.stringToOM(mediatorXml);

    CacheMediatorFactory factory = new CacheMediatorFactory();
    CacheMediator mediator =
            (CacheMediator) factory.createSpecificMediator(mediatorElement, new Properties());
    CacheMediatorSerializer serializer = new CacheMediatorSerializer();
    OMElement serializedMediatorElement = serializer.serializeSpecificMediator(mediator);

    XMLUnit.setIgnoreWhitespace(true);

    try {
        assertXMLEqual(serializedMediatorElement.toString(), mediatorXml);
    } catch (Exception ignored) {
    }
}
 
Example #2
Source Project: juddi   Author: apache   File: TckValidator.java    License: Apache License 2.0 6 votes vote down vote up
public static void checkKeyInfo(KeyInfoType kit1, KeyInfoType kit2) {
    if (kit1 == null || kit2 == null) {
            assertEquals(kit1, kit2);
            return;
    }
    assertEquals(kit1.getId(), kit2.getId());

    DOMResult domResult1 = new DOMResult();
    DOMResult domResult2 = new DOMResult();
    JAXB.marshal(kit1, domResult1);
    JAXB.marshal(kit2, domResult2);
    
    Document doc1 = (Document)domResult1.getNode();
    DOMSource domSource1 = new DOMSource(doc1.getDocumentElement());
    Document doc2 = (Document)domResult2.getNode();
    DOMSource domSource2 = new DOMSource(doc2.getDocumentElement());
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreWhitespace(true);
    Diff diff = new Diff(domSource1, domSource2);
    assertTrue("Key info elements should match", diff.similar());
}
 
Example #3
Source Project: portals-pluto   Author: apache   File: FileAssemblerTest.java    License: Apache License 2.0 6 votes vote down vote up
protected void setUp() throws Exception {
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setControlEntityResolver( new ResourceEntityResolver() );
    XMLUnit.setTestEntityResolver( new ResourceEntityResolver() );

    final URL webXmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/web.xml");
    this.webXmlFile = new File(webXmlUrl.getFile());

    final URL web23XmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/webServlet23.xml");
    this.web23XmlFile = new File(web23XmlUrl.getFile());

    final URL portletXmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/portlet.xml");
    this.portletXmlFile = new File(portletXmlUrl.getFile());

    final URL portlet23XmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/portletWebServlet23.xml");
    this.portlet23XmlFile = new File(portlet23XmlUrl.getFile());

    final URL assembledWebXmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/assembled.web.xml");
    this.assembledWebXmlFile = new File(assembledWebXmlUrl.getFile());

    final URL assembledWeb23XmlUrl = this.getClass().getResource("/org/apache/pluto/util/assemble/file/assembled.webServlet23.xml");
    this.assembledWeb23XmlFile = new File(assembledWeb23XmlUrl.getFile());
}
 
Example #4
Source Project: syndesis   Author: syndesisio   File: SoapPayloadConverterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void convertXmlToCxfToXml() throws IOException, XMLStreamException {

    // read XML bytes as an XML Document
    final ByteArrayInputStream bis = new ByteArrayInputStream(IOUtils.readBytesFromStream(inputStream));
    final Document request = StaxUtils.read(bis);
    bis.reset();

    // convert XML to CxfPayload
    final Exchange exchange = createExchangeWithBody(bis);
    final Message in = exchange.getIn();
    requestConverter.process(exchange);

    Assertions.assertThat(in.getBody()).isInstanceOf(CxfPayload.class);

    // convert CxfPayload back to XML
    final SoapMessage soapMessage = new SoapMessage(Soap12.getInstance());
    in.setHeader("CamelCxfMessage", soapMessage);
    responseConverter.process(exchange);

    assertIsInstanceOf(InputStream.class, in.getBody());
    Document response = StaxUtils.read((InputStream) in.getBody());

    XMLUnit.setIgnoreAttributeOrder(true);
    assertThat(response, isSimilarTo(request).ignoreWhitespace());
}
 
Example #5
Source Project: cloudhopper-commons   Author: twitter   File: SxmpWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void writeDeliveryReportResponse() throws Exception {
    DeliveryReportResponse deliveryResponse = new DeliveryReportResponse();
    deliveryResponse.setErrorCode(5);
    deliveryResponse.setErrorMessage("Success");

    StringWriter sw = new StringWriter();
    SxmpWriter.write(sw, deliveryResponse);

    logger.debug(sw.toString());

    StringBuilder expectedXML = new StringBuilder(200)
        .append("<?xml version=\"1.0\"?>\n")
        .append("<operation type=\"deliveryReport\">\n")
        .append(" <deliveryReportResponse>\n")
        .append("   <error code=\"5\" message=\"Success\"/>\n")
        .append(" </deliveryReportResponse>\n")
        .append("</operation>\n")
        .append("");

    // compare to actual correct submit response
    XMLUnit.setIgnoreWhitespace(true);
    Diff myDiff = new Diff(expectedXML.toString(), sw.toString());
    DetailedDiff myDetailedDiff = new DetailedDiff(myDiff);
    Assert.assertTrue("XML are similar " + myDetailedDiff, myDetailedDiff.similar());
}
 
Example #6
Source Project: rome   Author: rometools   File: OPML20GeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
private NodeList categoryOf(final String... categories) {

        try {

            final Outline outline = new Outline("outline1", null);
            outline.setCategories(Arrays.asList(categories));

            final Opml opml = new Opml();
            opml.setFeedType("opml_2.0");
            opml.setTitle("title");
            opml.setOutlines(Arrays.asList(outline));

            final WireFeedOutput output = new WireFeedOutput();
            final String xml = output.outputString(opml);

            final Document document = XMLUnit.buildControlDocument(xml);
            return XMLUnit.newXpathEngine().getMatchingNodes("/opml/body/outline/@category", document);

        } catch (final Exception e) {
            throw new RuntimeException(e);
        }

    }
 
Example #7
Source Project: proarc   Author: proarc   File: TransformersTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
     * Tests mapping of field 520 and subfield $9 to {@code [email protected]}.
     * See issue 434.
     */
    @Test
    public void testMarcAsMods_AbstractLang_Issue434() throws Exception {
        InputStream xmlIS = TransformersTest.class.getResourceAsStream("marc_subject_65X_X9.xml");
        assertNotNull(xmlIS);
        StreamSource streamSource = new StreamSource(xmlIS);
        Transformers mt = new Transformers();

        try {
            byte[] contents = mt.transformAsBytes(streamSource, Transformers.Format.MarcxmlAsMods3);
            assertNotNull(contents);
            String xmlResult = new String(contents, "UTF-8");
//            System.out.println(xmlResult);
            XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(new HashMap() {{
                put("m", ModsConstants.NS);
            }}));
            XMLAssert.assertXpathExists("/m:mods/m:abstract[@lang='cze' and @type='Abstract' and text()='Text cze']", xmlResult);
            XMLAssert.assertXpathExists("/m:mods/m:abstract[@lang='eng' and @type='Abstract' and text()='Text eng']", xmlResult);
            XMLAssert.assertXpathExists("/m:mods/m:abstract[not(@lang) and @type='Abstract' and text()='Text no lang']", xmlResult);
            validateMods(new StreamSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
        }
    }
 
Example #8
Source Project: json-data-generator   Author: vincentrussell   File: JsonDataGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
  public void testXmlTemplate() throws IOException, JsonDataGeneratorException, SAXException, ParserConfigurationException, XpathException {
      parser.generateTestDataJson(this.getClass().getClassLoader().getResource("xmlfunctionWithRepeat.xml"), outputStream);
      
      ByteArrayInputStream inputstream = new ByteArrayInputStream(outputStream.toByteArray());
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      dbf.setNamespaceAware(true);
      dbf.setCoalescing(true);
      dbf.setIgnoringElementContentWhitespace(true);
      dbf.setIgnoringComments(true);
      DocumentBuilder db = dbf.newDocumentBuilder();

      Document doc = db.parse(inputstream);
      XpathEngine simpleXpathEngine = XMLUnit.newXpathEngine();
      String value = simpleXpathEngine.evaluate("//root/tags", doc);
assertEquals(value.split(",").length, 7);
assertTrue(simpleXpathEngine.evaluate("//root/element[1]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/element[2]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[1]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[2]/name", doc).length() > 1);
assertTrue(simpleXpathEngine.evaluate("//root/friends/friend[3]/name", doc).length() > 1);
  }
 
Example #9
Source Project: proarc   Author: proarc   File: Kramerius4ExportTest.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    config = AppConfigurationFactory.getInstance().create(new HashMap<String, String>() {{
        put(AppConfiguration.PROPERTY_APP_HOME, temp.getRoot().getPath());
    }});
    fedora = new FedoraTestSupport();
    fedora.cleanUp();
    MetaModelRepository.setInstance(config.getPlugins());
    DigitalObjectManager.setDefault(new DigitalObjectManager(
            config,
            EasyMock.createNiceMock(ImportBatchManager.class),
            fedora.getRemoteStorage(),
            MetaModelRepository.getInstance(),
            EasyMock.createNiceMock(UserManager.class)));

    // check datastreams with xpath
    HashMap<String, String> namespaces = new HashMap<>();
    namespaces.put("dc", DcConstants.NS_PURL);
    namespaces.put("f", "info:fedora/fedora-system:def/foxml#");
    namespaces.put("kramerius", Kramerius4Export.KRAMERIUS_RELATION_NS);
    namespaces.put("mods", ModsStreamEditor.DATASTREAM_FORMAT_URI);
    namespaces.put("oai", Kramerius4Export.OAI_NS);
    namespaces.put("proarc-rels", Relations.PROARC_RELS_NS);
    XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces));
}
 
Example #10
Source Project: java-client-api   Author: marklogic   File: SuggestTest.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void setup()
  throws FileNotFoundException, ResourceNotFoundException, ForbiddenUserException, FailedRequestException, ResourceNotResendableException {
  XMLUnit.setIgnoreWhitespace(true);
  Common.connectAdmin();
  writeOptions(Common.adminClient);

  Common.adminClient.newServerConfigManager().setServerRequestLogging(true);
  Common.connect();

  // write three files for alert tests.
  XMLDocumentManager docMgr = Common.client.newXMLDocumentManager();
  docMgr.write("/sample/suggestion.xml", new StringHandle("<suggest><string>FINDME</string>Something I love to suggest is sugar with savory succulent limes.</suggest>"));
  docMgr.write("/sample2/suggestion.xml", new StringHandle("<suggest>Something I hate to suggest is liver with lard.</suggest>"));

}
 
Example #11
Source Project: olingo-odata2   Author: apache   File: HttpExceptionResponseTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void genericHttpExceptions() throws Exception {
  disableLogging();

  final List<ODataHttpException> toTestExceptions = getHttpExceptionsForTest();

  int firstKey = 1;
  for (final ODataHttpException oDataException : toTestExceptions) {
    final String key = String.valueOf(firstKey++);
    final Matcher<GetEntityUriInfo> match = new EntityKeyMatcher(key);
    when(processor.readEntity(Matchers.argThat(match), any(String.class))).thenThrow(oDataException);

    final HttpResponse response = executeGetRequest("Managers('" + key + "')");

    assertEquals("Expected status code does not match for exception type '"
        + oDataException.getClass().getSimpleName() + "'.",
        oDataException.getHttpStatus().getStatusCode(), response.getStatusLine().getStatusCode());

    final String content = StringHelper.inputStreamToString(response.getEntity().getContent());
    Map<String, String> prefixMap = new HashMap<String, String>();
    prefixMap.put("a", Edm.NAMESPACE_M_2007_08);
    XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));
    assertXpathExists("/a:error/a:code", content);
  }

}
 
Example #12
Source Project: tomee   Author: apache   File: OpenejbJarTest.java    License: Apache License 2.0 6 votes vote down vote up
private <T> void unmarshalAndMarshal(final Class<T> type, final java.lang.String xmlFileName, final java.lang.String expectedFile) throws Exception {
    final InputStream in = getInputStream(xmlFileName);
    assertNotNull(in);
    final Object object = JaxbOpenejbJar2.unmarshal(type, in);

    final String actual = JaxbOpenejbJar2.marshal(type, object);

    final String expected;
    if (xmlFileName.equals(expectedFile)) {
        expected = readContent(getInputStream(xmlFileName));
    } else {
        expected = readContent(getInputStream(expectedFile));
    }
    XMLUnit.setIgnoreWhitespace(true);
    try {
        final Diff myDiff = new DetailedDiff(new Diff(expected, actual));
        assertTrue("Files are not similar " + myDiff, myDiff.similar());
    } catch (final AssertionFailedError e) {
        e.printStackTrace();
        assertEquals(expected, actual);
        throw e;
    }
}
 
Example #13
Source Project: dashencrypt   Author: castlabs   File: FullRoundtripTest.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testEncrypt2_encrypted2() throws Exception {
    File outputDir = File.createTempFile("FullRoundtrip", "testEncrypt2");
    outputDir.delete();
    outputDir.mkdir();

    Main.main(new String[]{
            "encrypt2",
            "-o", outputDir.getAbsolutePath(),
            "--secretKey:v", "550e8400e29b11d4a716446655441111",
            "--uuid:v", "550e8400-e29b-11d4-a716-446655440000",
            "--secretKey:a", "660e8400e29b11d4a716446655441111",
            "--uuid:a", "660e8400-e29b-11d4-a716-446655440000",
            new File(tos, "tears_of_steel/Tears_Of_Steel_1000000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_1400000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_800000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_600000.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_128000_eng.mp4").getAbsolutePath(),
            new File(tos, "tears_of_steel/Tears_Of_Steel_128000_ita.mp4").getAbsolutePath(),
    });

    XMLUnit.setIgnoreWhitespace(true);
    XMLAssert.assertXMLEqual(new InputSource(getClass().getResourceAsStream("testEncrypt2_encrypted2.mpd")), new InputSource(new FileInputStream(new File(outputDir, "Manifest.mpd"))));
    FileUtils.deleteDirectory(outputDir);
}
 
Example #14
Source Project: tomee   Author: apache   File: JaxbWlsTest.java    License: Apache License 2.0 6 votes vote down vote up
public void marshallAndUnmarshall(final String xmlFile) throws Exception {

        final InputStream in = this.getClass().getClassLoader().getResourceAsStream(xmlFile);
        final String expected = readContent(in);

        final Object object = JaxbWls.unmarshal(WeblogicEjbJar.class, new ByteArrayInputStream(expected.getBytes()));

        final JAXBElement element = (JAXBElement) object;

        assertTrue(element.getValue() instanceof WeblogicEjbJar);

        final String actual = JaxbWls.marshal(WeblogicEjbJar.class, element);

        XMLUnit.setIgnoreWhitespace(true);
        try {
            final Diff myDiff = new DetailedDiff(new Diff(expected, actual));
            assertTrue("Files are not similar " + myDiff, myDiff.similar());
        } catch (final AssertionFailedError e) {
            assertEquals(expected, actual);
            throw e;
        }
    }
 
Example #15
Source Project: olingo-odata2   Author: apache   File: AtomServiceDocumentProducerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void before() throws ODataException {
  Map<String, String> prefixMap = new HashMap<String, String>();
  prefixMap.put("atom", Edm.NAMESPACE_ATOM_2005);
  prefixMap.put("a", Edm.NAMESPACE_APP_2007);
  prefixMap.put("xml", Edm.NAMESPACE_XML_1998);
  prefixMap.put("custom", "http://localhost");
  XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));

  schemas = new ArrayList<Schema>();

  EdmProvider edmProvider = mock(EdmProvider.class);
  when(edmProvider.getSchemas()).thenReturn(schemas);

  EdmServiceMetadata edmServiceMetadata = new EdmServiceMetadataImplProv(edmProvider);

  edm = mock(Edm.class);
  when(edm.getServiceMetadata()).thenReturn(edmServiceMetadata);
}
 
Example #16
Source Project: cloud-odata-java   Author: SAP   File: AtomEntryProducerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void syndicationWithComplexProperty() throws Exception {
  //prepare Mock
  EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  EdmCustomizableFeedMappings employeeCustomPropertyMapping = mock(EdmCustomizableFeedMappings.class);
  when(employeeCustomPropertyMapping.isFcKeepInContent()).thenReturn(Boolean.TRUE);
  when(employeeCustomPropertyMapping.getFcNsPrefix()).thenReturn("customPre");
  when(employeeCustomPropertyMapping.getFcNsUri()).thenReturn("http://customUri.com");
  EdmTyped employeeLocationProperty = employeesSet.getEntityType().getProperty("Location");
  when(((EdmProperty) employeeLocationProperty).getCustomizableFeedMappings()).thenReturn(employeeCustomPropertyMapping);

  Map<String, String> prefixMap = new HashMap<String, String>();
  prefixMap.put("a", Edm.NAMESPACE_ATOM_2005);
  prefixMap.put("d", Edm.NAMESPACE_D_2007_08);
  prefixMap.put("m", Edm.NAMESPACE_M_2007_08);
  prefixMap.put("xml", Edm.NAMESPACE_XML_1998);
  prefixMap.put("customPre", "http://customUri.com");
  XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));

  AtomEntityProvider ser = createAtomEntityProvider();
  ODataResponse response = ser.writeEntry(employeesSet, employeeData, DEFAULT_PROPERTIES);
  String xmlString = verifyResponse(response);

  assertXpathNotExists("/a:entry/customPre:Location", xmlString);
  assertXpathExists("/a:entry/m:properties/d:Location", xmlString);
}
 
Example #17
Source Project: n2o-framework   Author: i-novus-llc   File: N2oConfigConflictParserTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testParse(String conflictFilePath, String originFilePath) throws IOException, SAXException {
    URL conflict = this.getClass().getClassLoader().getResource(RESOURCE_PATH + conflictFilePath);
    URL parent = this.getClass().getClassLoader().getResource(RESOURCE_PATH + originFilePath);
    Assert.assertTrue(conflict != null && parent != null);
    N2oConfigConflict configConflict = new N2oConfigConflict();
    configConflict.setConflictContent(IOUtils.toString(conflict, "UTF-8"));
    N2oConfigConflictParser.restoreContentsByConflict(configConflict);
    Diff diff = XMLUnit.compareXML(configConflict.getParentContent(), IOUtils.toString(parent, "UTF-8"));
    Assert.assertTrue(diff.identical());
}
 
Example #18
Source Project: gate-core   Author: GateNLP   File: TestCreoleAnnotationHandler.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
  // Initialise the GATE library and creole register
  Gate.init();

  XMLUnit.setIgnoreComments(true);
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setIgnoreAttributeOrder(true);
}
 
Example #19
Source Project: cloudhopper-commons   Author: twitter   File: SxmpWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void writeSubmitRequestWithUTF8PushDestination() throws Exception {
    SubmitRequest request = new SubmitRequest(SxmpParser.VERSION_1_1);
    request.setAccount(new Account("customer1", "test1"));
    request.setOperatorId(20);
    request.setDestinationAddress(new MobileAddress(MobileAddress.Type.PUSH_DESTINATION, "abcd\n1234\rfghi-€£æ_\u20AC\u0623\u0647\u0644"));
    request.setText("Hello World");

    StringWriter sw = new StringWriter();
    SxmpWriter.write(sw, request);

    logger.debug("UTF8 PUSH DEST: "+sw.toString());

    StringBuilder expectedXML = new StringBuilder(200)
        .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        .append("<operation type=\"submit\">\n")
        .append(" <account username=\"customer1\" password=\"test1\"/>\n")
        .append(" <submitRequest>\n")
        .append("  <operatorId>20</operatorId>\n")
        .append("  <priority>0</priority>\n")
        .append("  <deliveryReport>false</deliveryReport>\n")
        .append("  <destinationAddress type=\"push_destination\">abcd\n1234\rfghi-€£æ_\u20AC\u0623\u0647\u0644</destinationAddress>\n")
        .append("  <text encoding=\"UTF-8\">48656C6C6F20576F726C64</text>\n")
        .append(" </submitRequest>\n")
        .append("</operation>\n")
        .append("");

    // compare to actual correct submit response
    XMLUnit.setIgnoreWhitespace(true);
    Diff myDiff = new Diff(expectedXML.toString(), sw.toString());
    DetailedDiff myDetailedDiff = new DetailedDiff(myDiff);
    Assert.assertTrue("XML are similar " + myDetailedDiff, myDetailedDiff.similar());
    // verify there's no optionalParams entry
    Assert.assertTrue(!expectedXML.toString().contains("optionalParams"));
}
 
Example #20
Source Project: spring4-understanding   Author: langtianya   File: CastorMarshallerTests.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Assert the values of xpath expression evaluation is exactly the same as expected value.
 * <p>The xpath may contain the xml namespace prefixes, since namespaces from flight example
 * are being registered.
 * @param msg the error message that will be used in case of test failure
 * @param expected the expected value
 * @param xpath the xpath to evaluate
 * @param xmlDoc the xml to use
 * @throws Exception if any error occurs during xpath evaluation
 */
private void assertXpathEvaluatesTo(String msg, String expected, String xpath, String xmlDoc) throws Exception {
	Map<String, String> namespaces = new HashMap<String, String>();
	namespaces.put("tns", "http://samples.springframework.org/flight");
	namespaces.put("xsi", "http://www.w3.org/2001/XMLSchema-instance");

	NamespaceContext ctx = new SimpleNamespaceContext(namespaces);
	XpathEngine engine = XMLUnit.newXpathEngine();
	engine.setNamespaceContext(ctx);

	Document doc = XMLUnit.buildControlDocument(xmlDoc);
	NodeList node = engine.getMatchingNodes(xpath, doc);
	assertEquals(msg, expected, node.item(0).getNodeValue());
}
 
Example #21
Source Project: olingo-odata4   Author: apache   File: ODataXmlDeserializerTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() {
  XMLUnit.setIgnoreComments(true);
  XMLUnit.setIgnoreAttributeOrder(true);
  XMLUnit.setIgnoreWhitespace(true);
  XMLUnit.setNormalizeWhitespace(true);
  XMLUnit.setCompareUnmatched(false);
}
 
Example #22
Source Project: cloud-odata-java   Author: SAP   File: AbstractProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setXmlNamespacePrefixes() throws Exception {
  Map<String, String> prefixMap = new HashMap<String, String>();
  prefixMap.put("a", Edm.NAMESPACE_ATOM_2005);
  prefixMap.put("d", Edm.NAMESPACE_D_2007_08);
  prefixMap.put("m", Edm.NAMESPACE_M_2007_08);
  prefixMap.put("xml", Edm.NAMESPACE_XML_1998);
  prefixMap.put("ру", "http://localhost");
  prefixMap.put("custom", "http://localhost");
  prefixMap.put("at", TombstoneCallback.NAMESPACE_TOMBSTONE);
  XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));
}
 
Example #23
Source Project: java-client-api   Author: marklogic   File: ResourceExtensionsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testResourceServiceExtension() throws XpathException, SAXException, IOException {
  ResourceExtensionsManager extensionMgr =
    Common.adminClient.newServerConfigManager().newResourceExtensionsManager();

  StringHandle handle = new StringHandle();

  ExtensionMetadata metadata = makeMetadata();
  MethodParameters[] params = makeParameters();

  handle.set(resourceServices);
  extensionMgr.writeServices(RESOURCE_NAME, handle, metadata, params);

  extensionMgr.readServices(RESOURCE_NAME, handle);
  assertEquals("Failed to retrieve resource services", resourceServices, handle.get());

  String result = extensionMgr.listServices(new StringHandle().withFormat(Format.XML), true).get();
  assertNotNull("Failed to retrieve resource services list", result);
  assertTrue("List without resource", xpather.getMatchingNodes(
    "/rapi:resources/rapi:resource/rapi:name[string(.) = 'testresource']",
    XMLUnit.buildControlDocument(result)
  ).getLength() == 1);

  extensionMgr.deleteServices(RESOURCE_NAME);

  result = extensionMgr.readServices(RESOURCE_NAME, handle).get();
  assertTrue("Failed to delete resource services", result == null);
}
 
Example #24
Source Project: cerberus-source   Author: cerberustesting   File: XmlUnitService.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Initializes {@link XMLUnit} properties
 */
private void initXMLUnitProperties() {
    XMLUnit.setIgnoreComments(true);
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true);
    XMLUnit.setCompareUnmatched(false);
}
 
Example #25
Source Project: proarc   Author: proarc   File: TransformersTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
     * Tests mapping of 910a(sigla) as {@code <physicalLocation>} and 910b(signatura) as {@code <shelfLocator>}.
     */
    @Test
    public void testMarcAsMods_Issue32() throws Exception {
        InputStream xmlIS = TransformersTest.class.getResourceAsStream("marc.xml");
        assertNotNull(xmlIS);
        StreamSource streamSource = new StreamSource(xmlIS);
        Transformers mt = new Transformers();

        try {
            byte[] contents = mt.transformAsBytes(streamSource, Transformers.Format.MarcxmlAsMods3);
            assertNotNull(contents);
            String xmlResult = new String(contents, "UTF-8");
//            System.out.println(xmlResult);
            XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(new HashMap() {{
                put("m", ModsConstants.NS);
            }}));
            XMLAssert.assertXpathEvaluatesTo("HKA001", "/m:mods/m:location/m:physicalLocation[1]", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("test sigla", "/m:mods/m:location/m:physicalLocation[2]", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("2", "count(/m:mods/m:location/m:physicalLocation)", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("54 487", "/m:mods/m:location/m:shelfLocator[1]", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("test signatura", "/m:mods/m:location/m:shelfLocator[2]", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("2", "count(/m:mods/m:location/m:shelfLocator)", xmlResult);
            validateMods(new StreamSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
        }
    }
 
Example #26
Source Project: cloud-odata-java   Author: SAP   File: LanguageNegotiationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Before
public void before() {
  super.before();

  Map<String, String> prefixMap = new HashMap<String, String>();
  prefixMap.put("m", Edm.NAMESPACE_M_2007_08);
  XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));

  disableLogging();
}
 
Example #27
Source Project: cloud-odata-java   Author: SAP   File: AtomEntryProducerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void noneSyndicationWithNullPrefix() throws Exception {
  //prepare Mock
  EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  EdmCustomizableFeedMappings employeeCustomPropertyMapping = mock(EdmCustomizableFeedMappings.class);
  when(employeeCustomPropertyMapping.isFcKeepInContent()).thenReturn(Boolean.TRUE);
  when(employeeCustomPropertyMapping.getFcNsUri()).thenReturn("http://customUri.com");
  EdmTyped employeeEntryDateProperty = employeesSet.getEntityType().getProperty("EmployeeName");
  when(((EdmProperty) employeeEntryDateProperty).getCustomizableFeedMappings()).thenReturn(employeeCustomPropertyMapping);

  Map<String, String> prefixMap = new HashMap<String, String>();
  prefixMap.put("a", Edm.NAMESPACE_ATOM_2005);
  prefixMap.put("d", Edm.NAMESPACE_D_2007_08);
  prefixMap.put("m", Edm.NAMESPACE_M_2007_08);
  prefixMap.put("xml", Edm.NAMESPACE_XML_1998);
  prefixMap.put("customPre", "http://customUri.com");
  XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));

  AtomEntityProvider ser = createAtomEntityProvider();
  boolean thrown = false;
  try {
    ser.writeEntry(employeesSet, employeeData, DEFAULT_PROPERTIES);
  } catch (EntityProviderException e) {
    verifyRootCause(EntityProviderException.class, EntityProviderException.INVALID_NAMESPACE.getKey(), e);
    thrown = true;
  }
  if (!thrown) {
    fail("Exception should have been thrown");
  }
}
 
Example #28
Source Project: rice   Author: kuali   File: PostProcessorTest.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * Tests that modifying a document in the post processor works.  This test will do a few things:
 * 
 * 1) Change the document content in the post processor
 * 2) Send an app specific FYI request to the initiator of the document
 * 3) Modify the document title.
 * 
 * This test is meant to expose the bug KULWF-668 where it appears an OptimisticLockException is
 * being thrown after returning from the EPIC post processor.
 */
@Test public void testModifyDocumentInPostProcessor() throws Exception {
       XMLUnit.setIgnoreWhitespace(true);
	WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("ewestfal"), "testModifyDocumentInPostProcessor");
	document.saveDocument("");
       assertEquals("application content should be empty initially", "", document.getApplicationContent());
	assertTrue("Doc title should be empty initially", StringUtils.isBlank(document.getTitle()));

       document.adHocToPrincipal(ActionRequestType.APPROVE, "AdHoc", "", "2002", "", true);
	document.complete("");
       document = WorkflowDocumentFactory.loadDocument("2002", document.getDocumentId());

       // now approve the document, it should through a 2 nodes, then go PROCESSED then FINAL
       document.approve("");

       assertEquals("Should have transitioned nodes twice", 2, DocumentModifyingPostProcessor.levelChanges);
	assertTrue("SHould have called the processed status change", DocumentModifyingPostProcessor.processedChange);
	assertTrue("Document should be final.", document.isFinal());
	XMLAssert.assertXMLEqual("Application content should have been sucessfully modified.", APPLICATION_CONTENT, document.getApplicationContent());
			
	// check that the title was modified successfully
	assertEquals("Wrong doc title", DOC_TITLE, document.getTitle());
	
	// check that the document we routed from the post processor exists
	assertNotNull("SHould have routed a document from the post processor.", DocumentModifyingPostProcessor.routedDocumentId);
	document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), DocumentModifyingPostProcessor.routedDocumentId);
	assertTrue("document should be enroute", document.isEnroute());
	assertEquals("Document should have 1 pending request.", 1, KEWServiceLocator.getActionRequestService().findPendingByDoc(document.getDocumentId()).size());
	assertTrue("ewestfal should have an approve request.", document.isApprovalRequested());
	document.approve("");
	assertTrue("Document should be final.", document.isFinal());
}
 
Example #29
Source Project: cloudhopper-commons   Author: twitter   File: SxmpWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void writeDeliveryReportRequest0() throws Exception {
    DeliveryReportRequest request = new DeliveryReportRequest();
    request.setAccount(new Account("customer1", "test1"));
    //request.setOperatorId(20);
    request.setReferenceId("TESTREF");
    request.setStatus(new DeliveryStatus(5, "Expired"));
    request.setTicketId("000:20090118002220948:000");
    //request.setSourceAddress(new MobileAddress(MobileAddress.Type.NETWORK, "40404"));
    //request.setDestinationAddress(new MobileAddress(MobileAddress.Type.INTERNATIONAL, "+13135551212"));
    //request.setText("Hello World");

    StringWriter sw = new StringWriter();
    SxmpWriter.write(sw, request);

    logger.debug(sw.toString());

    StringBuilder expectedXML = new StringBuilder(200)
        .append("<?xml version=\"1.0\"?>\n")
        .append("<operation type=\"deliveryReport\">\n")
        .append(" <account username=\"customer1\" password=\"test1\"/>\n")
        .append(" <deliveryReportRequest referenceId=\"TESTREF\">\n")
        .append("   <status code=\"5\" message=\"Expired\"/>\n")
        .append("   <ticketId>000:20090118002220948:000</ticketId>\n")
        .append(" </deliveryReportRequest>\n")
        .append("</operation>\n")
        .append("");

    // compare to actual correct submit response
    XMLUnit.setIgnoreWhitespace(true);
    Diff myDiff = new Diff(expectedXML.toString(), sw.toString());
    DetailedDiff myDetailedDiff = new DetailedDiff(myDiff);
    Assert.assertTrue("XML are similar " + myDetailedDiff, myDetailedDiff.similar());
}
 
Example #30
Source Project: proarc   Author: proarc   File: TransformersTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
     * Tests mapping of field 787 to {@code relatedItem}.
     * See issue 313.
     */
    @Test
    public void testMarcAsMods_RelatedItem_Issue313() throws Exception {
        InputStream xmlIS = TransformersTest.class.getResourceAsStream("marc_relatedItem_787.xml");
        assertNotNull(xmlIS);
        StreamSource streamSource = new StreamSource(xmlIS);
        Transformers mt = new Transformers();

        try {
            byte[] contents = mt.transformAsBytes(streamSource, Transformers.Format.MarcxmlAsMods3);
            assertNotNull(contents);
            String xmlResult = new String(contents, "UTF-8");
//            System.out.println(xmlResult);
            XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(new HashMap() {{
                put("m", ModsConstants.NS);
            }}));
            // test 78708 |i Recenze na: |a Čeřovský, Jan |t Jak jsme zachraňovali svět aneb Půl století ve službách ochrany přírody |d Praha : Nakladatelství Academia, 2014 |4 kniha
            XMLAssert.assertXpathEvaluatesTo(
                    "Jak jsme zachraňovali svět aneb Půl století ve službách ochrany přírody",
                    "/m:mods/m:relatedItem[not(@type) and @displayLabel='Recenze na:']"
                    + "/m:titleInfo/m:title/text()", xmlResult);
            XMLAssert.assertXpathEvaluatesTo(
                    "Čeřovský, Jan",
                    "/m:mods/m:relatedItem[not(@type) and @displayLabel='Recenze na:']"
                    + "/m:name/m:namePart/text()", xmlResult);
            XMLAssert.assertXpathEvaluatesTo(
                    "Praha : Nakladatelství Academia, 2014",
                    "/m:mods/m:relatedItem[not(@type) and @displayLabel='Recenze na:']"
                    + "/m:originInfo/m:publisher/text()", xmlResult);
            validateMods(new StreamSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
        }
    }