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 File: CacheMediatorTest.java    From micro-integrator with 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 File: SoapPayloadConverterTest.java    From syndesis with 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 #3
Source File: FileAssemblerTest.java    From portals-pluto with 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 File: TckValidator.java    From juddi with 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 #5
Source File: AtomEntryProducerTest.java    From cloud-odata-java with 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 #6
Source File: JaxbWlsTest.java    From tomee with 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 #7
Source File: AtomServiceDocumentProducerTest.java    From olingo-odata2 with 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 #8
Source File: SxmpWriterTest.java    From cloudhopper-commons with 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 #9
Source File: FullRoundtripTest.java    From dashencrypt with 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 #10
Source File: OpenejbJarTest.java    From tomee with 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 #11
Source File: OPML20GeneratorTest.java    From rome with 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 #12
Source File: HttpExceptionResponseTest.java    From olingo-odata2 with 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 #13
Source File: TransformersTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
     * Tests mapping of field 520 and subfield $9 to {@code abstract@lang}.
     * 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 #14
Source File: JsonDataGeneratorTest.java    From json-data-generator with 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 #15
Source File: Kramerius4ExportTest.java    From proarc with 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 #16
Source File: SuggestTest.java    From java-client-api with 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 #17
Source File: AbstractProviderTest.java    From olingo-odata2 with 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 #18
Source File: DLNAServiceTest.java    From Connect-SDK-Android-Core with Apache License 2.0 5 votes vote down vote up
private void assertXMLEquals(String expectedXML, String actualXML) throws SAXException, IOException {
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setIgnoreAttributeOrder(true);
    XMLUnit.setNormalize(true);
    DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expectedXML, actualXML));
    List<?> allDifferences = diff.getAllDifferences();
    Assert.assertEquals("XML differences found: " + diff.toString(), 0, allDifferences.size());
}
 
Example #19
Source File: AtomEntryProducerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void noneSyndicationWithNullUriAndNullPrefix() throws Exception {
  // prepare Mock
  EdmEntitySet employeesSet = MockFacade.getMockEdm().getDefaultEntityContainer().getEntitySet("Employees");
  EdmCustomizableFeedMappings employeeCustomPropertyMapping = mock(EdmCustomizableFeedMappings.class);
  when(employeeCustomPropertyMapping.isFcKeepInContent()).thenReturn(Boolean.TRUE);
  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("f", "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(EntityProviderProducerException.class, EntityProviderException.INVALID_NAMESPACE.getKey(), e);
    thrown = true;
  }
  if (!thrown) {
    fail("Exception should have been thrown");
  }
}
 
Example #20
Source File: SxmpWriterTest.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void writeSubmitRequestWithNationalAndApplication() throws Exception {
    SubmitRequest request = new SubmitRequest();
    request.setAccount(new Account("customer1", "test1"));
    request.setApplication(new Application("TestApp"));
    request.setOperatorId(20);
    request.setSourceAddress(new MobileAddress(MobileAddress.Type.NATIONAL, "0123456789"));
    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=\"submit\">\n")
        .append(" <account username=\"customer1\" password=\"test1\"/>\n")
        .append(" <application>TestApp</application>\n")
        .append(" <submitRequest>\n")
        .append("  <operatorId>20</operatorId>\n")
        .append("  <priority>0</priority>\n")
        .append("  <deliveryReport>false</deliveryReport>\n")
        .append("  <sourceAddress type=\"national\">0123456789</sourceAddress>\n")
        .append("  <destinationAddress type=\"international\">+13135551212</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());
}
 
Example #21
Source File: ExceptionsTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void exceptionBasicTest() throws Exception {
  final HttpResponse response = executeGetRequest("NoContainer.NoEntitySet()");
  assertEquals(HttpStatusCodes.NOT_FOUND.getStatusCode(), response.getStatusLine().getStatusCode());

  final String payload = 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", payload);
  assertXpathExists("/a:error/a:code", payload);
  assertXpathExists("/a:error/a:message[@xml:lang=\"en\"]", payload);
}
 
Example #22
Source File: TransformerEncodeTest.java    From exificient with MIT License 5 votes vote down vote up
@Test
public void testEncode() throws Exception {
	final StringReader reader = new StringReader(XML);
	final EXIFactory factory = getFactory(true);
	final byte[] bytes = encode(factory, reader).toByteArray();
	final Document decode = decode(factory, new InputSource(
			new ByteArrayInputStream(bytes)));
	final Diff diff = XMLUnit.compareXML(XMLUnit.buildControlDocument(XML),
			decode);
	Assert.assertTrue(diff.toString(), diff.similar());
}
 
Example #23
Source File: AtomEntrySerializerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void noneSyndicationWithNullUri() 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");
  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));

  AtomSerializerDeserializer ser = createAtomEntityProvider();
  employeeData.setWriteProperties(DEFAULT_PROPERTIES);
  boolean thrown = false;
  try {
    ser.writeEntry(employeesSet, employeeData);
  } catch (EntityProviderException e) {
    verifyRootCause(EntityProviderProducerException.class, EntityProviderException.INVALID_NAMESPACE.getKey(), e);
    thrown = true;
  }
  if (!thrown) {
    fail("Exception should have been thrown");
  }
}
 
Example #24
Source File: AtomEntryProducerTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@Test
public void noneSyndicationWithNullUri() 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");
  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 #25
Source File: BasicProviderTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
private void setNamespaces() {
  Map<String, String> prefixMap = new HashMap<String, String>();
  prefixMap.put("edmx", Edm.NAMESPACE_EDMX_2007_06);
  prefixMap.put("m", Edm.NAMESPACE_M_2007_08);
  prefixMap.put("a", Edm.NAMESPACE_EDM_2008_09);
  prefixMap.put("annoPrefix", "http://annoNamespace");
  prefixMap.put("prefix", "namespace");
  prefixMap.put("b", "RefScenario");
  prefixMap.put("pre", "namespaceForAnno");
  XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));
}
 
Example #26
Source File: LanguageNegotiationTest.java    From olingo-odata2 with 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 File: SxmpWriterTest.java    From cloudhopper-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void writeSubmitResponse() throws Exception {
    SubmitResponse submitResponse = new SubmitResponse();
    submitResponse.setErrorCode(5);
    submitResponse.setErrorMessage("Success");
    submitResponse.setTicketId("THISISTICKET");

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

    logger.debug(sw.toString());

    StringBuilder expectedXML = new StringBuilder(200)
        .append("<?xml version=\"1.0\"?>\n")
        .append("<operation type=\"submit\">\n")
        .append(" <submitResponse>\n")
        .append("   <error code=\"5\" message=\"Success\"/>\n")
        .append("   <ticketId>THISISTICKET</ticketId>\n")
        .append(" </submitResponse>\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 #28
Source File: XmlMetadataProducerTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@Test
public void writeValidMetadata() throws Exception {
  List<Schema> schemas = new ArrayList<Schema>();

  List<AnnotationElement> annotationElements = new ArrayList<AnnotationElement>();
  annotationElements.add(new AnnotationElement().setName("test").setText("hallo"));
  Schema schema = new Schema().setAnnotationElements(annotationElements);
  schema.setNamespace("http://namespace.com");
  schemas.add(schema);

  DataServices data = new DataServices().setSchemas(schemas).setDataServiceVersion(ODataServiceVersion.V20);
  OutputStreamWriter writer = null;
  CircleStreamBuffer csb = new CircleStreamBuffer();
  writer = new OutputStreamWriter(csb.getOutputStream(), "UTF-8");
  XMLStreamWriter xmlStreamWriter = xmlStreamWriterFactory.createXMLStreamWriter(writer);
  XmlMetadataProducer.writeMetadata(data, xmlStreamWriter, null);

  Map<String, String> prefixMap = new HashMap<String, String>();
  prefixMap.put("edmx", "http://schemas.microsoft.com/ado/2007/06/edmx");
  prefixMap.put("a", "http://schemas.microsoft.com/ado/2008/09/edm");

  NamespaceContext ctx = new SimpleNamespaceContext(prefixMap);
  XMLUnit.setXpathNamespaceContext(ctx);

  String metadata = StringHelper.inputStreamToString(csb.getInputStream());
  assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:test", metadata);
}
 
Example #29
Source File: MappingTest.java    From olingo-odata2 with 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("a", Edm.NAMESPACE_ATOM_2005);
  prefixMap.put("d", Edm.NAMESPACE_D_2007_08);
  prefixMap.put("m", Edm.NAMESPACE_M_2007_08);
  XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(prefixMap));
}
 
Example #30
Source File: XmlMetadataProducerTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void writeValidMetadata() throws Exception {
  List<Schema> schemas = new ArrayList<Schema>();

  List<AnnotationElement> annotationElements = new ArrayList<AnnotationElement>();
  annotationElements.add(new AnnotationElement().setName("test").setText("hallo"));
  Schema schema = new Schema().setAnnotationElements(annotationElements);
  schema.setNamespace("http://namespace.com");
  schemas.add(schema);

  DataServices data = new DataServices().setSchemas(schemas).setDataServiceVersion(ODataServiceVersion.V20);
  OutputStreamWriter writer = null;
  CircleStreamBuffer csb = new CircleStreamBuffer();
  writer = new OutputStreamWriter(csb.getOutputStream(), "UTF-8");
  XMLStreamWriter xmlStreamWriter = xmlStreamWriterFactory.createXMLStreamWriter(writer);
  XmlMetadataProducer.writeMetadata(data, xmlStreamWriter, null);

  Map<String, String> prefixMap = new HashMap<String, String>();
  prefixMap.put("edmx", "http://schemas.microsoft.com/ado/2007/06/edmx");
  prefixMap.put("a", "http://schemas.microsoft.com/ado/2008/09/edm");

  NamespaceContext ctx = new SimpleNamespaceContext(prefixMap);
  XMLUnit.setXpathNamespaceContext(ctx);

  String metadata = StringHelper.inputStreamToString(csb.getInputStream());
  assertXpathExists("/edmx:Edmx/edmx:DataServices/a:Schema/a:test", metadata);
}