org.custommonkey.xmlunit.XMLAssert Java Examples

The following examples show how to use org.custommonkey.xmlunit.XMLAssert. 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: 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 #2
Source File: TransformersTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
     * Tests mapping of fields 310a and 008/18 to {@code frequency@authority}.
     * See issue 118 and 181.
     */
    @Test
    public void testMarcAsMods_FrequencyAuthority_Issue181() throws Exception {
        InputStream xmlIS = TransformersTest.class.getResourceAsStream("frequencyAuthority.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.assertXpathNotExists("/m:mods/m:originInfo/m:frequency[1]/@authority", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("2x ročně", "/m:mods/m:originInfo/m:frequency[1]", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("marcfrequency", "/m:mods/m:originInfo/m:frequency[2]/@authority", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("Semiannual", "/m:mods/m:originInfo/m:frequency[2]", xmlResult);
            validateMods(new StreamSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
        }
    }
 
Example #3
Source File: TransformersTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
     * Tests mapping of field 653 indicator_9 $a to {@code subject/topic@lang}.
     * See issue 185.
     * See issue 433.
     */
    @Test
    public void testMarcAsMods_SubjectTopic_Issue185_Issue433() 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);
            }}));
            // 653
            XMLAssert.assertXpathExists("/m:mods/m:subject[not(@authority)]/m:topic[text()='kočky' and @lang='cze']", xmlResult);
            XMLAssert.assertXpathExists("/m:mods/m:subject[not(@authority)]/m:topic[text()='cats' and @lang='eng']", xmlResult);
            XMLAssert.assertXpathNotExists("/m:mods/m:subject/m:name/m:namePart[text()='kočky']", xmlResult);
            XMLAssert.assertXpathNotExists("/m:mods/m:subject/m:name/m:namePart[text()='cats']", xmlResult);
            validateMods(new StreamSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
        }
    }
 
Example #4
Source File: TransformersTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
     * Test mapping of 072#7 $x to {@code subject/topic} and $a/$9 to {@code classification}.
     * See issue 303.
     */
    @Test
    public void testMarcAsMods_Conspectus_Issue303() 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("Umění", "/m:mods/m:subject[@authority='Konspekt']/m:topic", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("7.01/.09", "/m:mods/m:classification[@authority='udc' and @edition='Konspekt']", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("21", "/m:mods/m:classification[@authority='Konspekt']", xmlResult);
            validateMods(new StreamSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
        }
    }
 
Example #5
Source File: TransformersTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@Test
    public void testMarcAsMods() throws Exception {
        XMLUnit.setNormalizeWhitespace(true);
        InputStream goldenIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsMods.xml");
        assertNotNull(goldenIS);
        InputStream xmlIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsMarcXml.xml");// from test
        assertNotNull(xmlIS);
        StreamSource streamSource = new StreamSource(xmlIS);
        Transformers mt = new Transformers();

        try {
            byte[] contents = mt.transformAsBytes(streamSource, Transformers.Format.MarcxmlAsMods3);
            assertNotNull(contents);
//            System.out.println(new String(contents, "UTF-8"));
            XMLAssert.assertXMLEqual(new InputSource(goldenIS), new InputSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
            close(goldenIS);
        }
    }
 
Example #6
Source File: TransformersTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
/**
     * Tests mapping of field 264_4 to {@code originInfo}.
     * See issue 298.
     */
    @Test
    public void testMarcAsMods_Mapping264_ind4_Issue298() throws Exception{
        InputStream xmlIS = TransformersTest.class.getResourceAsStream("marc_originInfo_264_ind4.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:originInfo[@eventType='copyright']", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("Praha","/m:mods/m:originInfo[@eventType='copyright']/m:place/m:placeTerm", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("Albatros","/m:mods/m:originInfo[@eventType='copyright']/m:publisher", xmlResult);
            XMLAssert.assertXpathEvaluatesTo("2015", "/m:mods/m:originInfo[@eventType='copyright']/m:copyrightDate", xmlResult);
            validateMods(new StreamSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
        }
    }
 
Example #7
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 #8
Source File: TransformersTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@Test
    public void testOaiMarcAsMarc() throws Exception {
        InputStream goldenIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsMarcXml.xml");
        assertNotNull(goldenIS);
        InputStream xmlIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseAsOaiMarc.xml");
        assertNotNull(xmlIS);
        StreamSource streamSource = new StreamSource(xmlIS);
        Transformers mt = new Transformers();

        try {
            byte[] contents = mt.transformAsBytes(streamSource, Transformers.Format.OaimarcAsMarc21slim);
            assertNotNull(contents);
//            System.out.println(new String(contents, "UTF-8"));
            XMLAssert.assertXMLEqual(new InputSource(goldenIS), new InputSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
            close(goldenIS);
        }
    }
 
Example #9
Source File: TransformersTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@Test
    public void testAlephXServerDetailNamespaceFix() throws Exception {
        InputStream goldenIS = TransformersTest.class.getResourceAsStream("alephXServerDetailResponseFixed.xml");
        assertNotNull(goldenIS);
        InputStream xmlIS = TransformersTest.class.getResourceAsStream("../catalog/alephXServerDetailResponse.xml");
        assertNotNull(xmlIS);
        StreamSource streamSource = new StreamSource(xmlIS);
        Transformers mt = new Transformers();

        try {
            byte[] contents = mt.transformAsBytes(streamSource, Transformers.Format.AlephOaiMarcFix);
            assertNotNull(contents);
//            System.out.println(new String(contents, "UTF-8"));
            XMLAssert.assertXMLEqual(new InputSource(goldenIS), new InputSource(new ByteArrayInputStream(contents)));
        } finally {
            close(xmlIS);
            close(goldenIS);
        }
    }
 
Example #10
Source File: PageMapperTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@Test
    public void testWriteUpdate() throws Exception {
        ModsDefinition mods = ModsUtils.unmarshal(PageMapperTest.class.getResource("page_mods.xml"), ModsDefinition.class);
        Page page = new Page();
        page.setNote("note updated");
        page.setIndex("2");
        page.setNumber("[2]");
        page.setType("TitlePage");
        page.setIdentifiers(Arrays.asList(
                new IdentifierItem(1, "uuid", "1 updated"),
                new IdentifierItem(0, "issn", "issn value updated"),
                new IdentifierItem("isbn", "isbn value inserted")));

        PageMapper instance = new PageMapper();
        ModsDefinition result = instance.map(mods, page);
        String resultXml = ModsUtils.toXml(result, true);
//        System.out.println(resultXml);

        ModsDefinition expectedMods = ModsUtils.unmarshal(PageMapperTest.class.getResource("page_mods_updated.xml"), ModsDefinition.class);
        String expectedXml = ModsUtils.toXml(expectedMods, true);
//        System.out.println(expectedXml);
        XMLAssert.assertXMLEqual(expectedXml, resultXml);
    }
 
Example #11
Source File: BatchJobUploadBodyProviderTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidOperations() throws BatchJobException, IOException, SAXException {
  RequestT request = createMutateRequest();
  addBudgetOperation(request, -1L, "Test budget", 50000000L, "STANDARD");
  addCampaignOperation(
      request, -2L, "Test campaign #1", "PAUSED", "SEARCH", -1L, "MANUAL_CPC", false);
  addCampaignOperation(
      request, -3L, "Test campaign #2", "PAUSED", "SEARCH", -1L, "MANUAL_CPC", false);
  addCampaignNegativeKeywordOperation(request, -2L, "venus", "BROAD");
  addCampaignNegativeKeywordOperation(request, -3L, "venus", "BROAD");
  ByteArrayContent httpContent =
      request.createBatchJobUploadBodyProvider().getHttpContent(request, true, true);
  String actualRequestXml = Streams.readAll(httpContent.getInputStream(), Charset.forName(UTF_8));
  actualRequestXml =
      SoapRequestXmlProvider.normalizeXmlForComparison(actualRequestXml, getApiVersion());
  String expectedRequestXml = SoapRequestXmlProvider.getTestBatchUploadRequest(getApiVersion());

  // Perform an XML diff using the custom difference listener that properly handles namespaces
  // and attributes.
  Diff diff = new Diff(expectedRequestXml, actualRequestXml);
  DifferenceListener diffListener = new CustomDifferenceListener();
  diff.overrideDifferenceListener(diffListener);
  XMLAssert.assertXMLEqual("Serialized upload request does not match expected XML", diff, true);
}
 
Example #12
Source File: DcStreamEditorTest.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testWriteMods() throws Exception {
    LocalStorage storage = new LocalStorage();
    LocalStorage.LocalObject local = storage.create();
    ModsStreamEditor modsEditor = new ModsStreamEditor(local);
    ModsDefinition mods = modsEditor.createPage(local.getPid(), "1", "[1]", "pageType");
    String model = "model:page";
    long timestamp = 0L;
    DcStreamEditor instance = new DcStreamEditor(local);
    instance.write(mods, model, timestamp, null);
    local.flush();

    DublinCoreRecord result = instance.read();
    assertNotNull(result);
    assertNotNull(result.getDc());
    assertEquals(local.getPid(), result.getPid());

    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("oai_dc", DcStreamEditor.DATASTREAM_FORMAT_URI);
    namespaces.put("dc", "http://purl.org/dc/elements/1.1/");
    XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces));
    String toXml = DcUtils.toXml(result.getDc(), true);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:title[text()='[1]']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:identifier[text()='" + local.getPid() +"']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:type[text()='" + model +"']", toXml);
}
 
Example #13
Source File: FullRoundtripTest.java    From dashencrypt with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testEncrypt2_encrypted1_clearlead() throws Exception {
    File outputDir = File.createTempFile("FullRoundtrip", "testEncrypt2");
    outputDir.delete();
    outputDir.mkdir();

    Main.main(new String[]{
            "encrypt2",
            "-o", outputDir.getAbsolutePath(),
            "-clearlead", "30",
            "--secretKey:v", "cbfed0736042e5962db8e23ddf1d0425",
            "--uuid:v", "22089b3b-527f-4612-a7bb-944559547306",
            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_encrypted1_clearlead.mpd")), new InputSource(new FileInputStream(new File(outputDir, "Manifest.mpd"))));
    FileUtils.deleteDirectory(outputDir);
}
 
Example #14
Source File: FullRoundtripTest.java    From dashencrypt with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testEncrypt2_encrypted1() throws Exception {
    File outputDir = File.createTempFile("FullRoundtrip", "testEncrypt2");
    outputDir.delete();
    outputDir.mkdir();

    Main.main(new String[]{
            "encrypt2",
            "-o", outputDir.getAbsolutePath(),
            "--secretKey:v", "cbfed0736042e5962db8e23ddf1d0425",
            "--uuid:v", "22089b3b-527f-4612-a7bb-944559547306",
            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);
    System.out.println(FileUtils.readFileToString(new File(outputDir, "Manifest.mpd")));
    XMLAssert.assertXMLEqual(new InputSource(getClass().getResourceAsStream("testEncrypt2_encrypted1.mpd")), new InputSource(new FileInputStream(new File(outputDir, "Manifest.mpd"))));
    FileUtils.deleteDirectory(outputDir);
}
 
Example #15
Source File: FullRoundtripTest.java    From dashencrypt with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void testEncrypt2_plain() throws Exception {
    File outputDir = File.createTempFile("FullRoundtrip", "testEncrypt2");
    outputDir.delete();
    outputDir.mkdir();

    Main.main(new String[]{
            "encrypt2",
            "-o", outputDir.getAbsolutePath(),
            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_plain.mpd")), new InputSource(new FileInputStream(new File(outputDir, "Manifest.mpd"))));
    FileUtils.deleteDirectory(outputDir);
}
 
Example #16
Source File: XsdGeneratorHelperTest.java    From jaxb2-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void validateProcessingNodes()
{

    // Assemble
    final String newPrefix = "changedFoo";
    final String oldPrefix = "foo";
    final String originalXml = getXmlDocumentSample( oldPrefix );
    final String changedXml = getXmlDocumentSample( newPrefix );
    final NodeProcessor changeNamespacePrefixProcessor = new ChangeNamespacePrefixProcessor( oldPrefix, newPrefix );

    // Act
    final Document processedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( originalXml ) );
    XsdGeneratorHelper.process( processedDocument.getFirstChild(), true, changeNamespacePrefixProcessor );

    // Assert
    final Document expectedDocument = XsdGeneratorHelper.parseXmlStream( new StringReader( changedXml ) );
    final Diff diff = new Diff( expectedDocument, processedDocument, null, new ElementNameAndAttributeQualifier() );
    diff.overrideElementQualifier( new ElementNameAndAttributeQualifier() );

    XMLAssert.assertXMLEqual( processedDocument, expectedDocument );
}
 
Example #17
Source File: SchemaOrderedNormalizedNodeWriterTest.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void testWriteOrder() throws XMLStreamException, IOException, SAXException {
    final StringWriter stringWriter = new StringWriter();
    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(stringWriter);
    SchemaContext schemaContext = getSchemaContext("/bug1848/order.yang");
    NormalizedNodeStreamWriter writer = XMLStreamNormalizedNodeStreamWriter.create(xmlStreamWriter, schemaContext);

    try (NormalizedNodeWriter nnw = new SchemaOrderedNormalizedNodeWriter(writer, schemaContext, SchemaPath.ROOT)) {

        DataContainerChild<?, ?> cont = Builders.containerBuilder()
                .withNodeIdentifier(getNodeIdentifier(ORDER_NAMESPACE, "cont"))
                .withChild(ImmutableNodes.leafNode(createQName(ORDER_NAMESPACE, "content"), "content1"))
                .build();

        NormalizedNode<?, ?> root = Builders.containerBuilder()
                .withNodeIdentifier(getNodeIdentifier(ORDER_NAMESPACE, "root"))
                .withChild(cont)
                .withChild(ImmutableNodes.leafNode(createQName(ORDER_NAMESPACE, "id"), "id1"))
                .build();

        nnw.write(root);
    }

    XMLAssert.assertXMLIdentical(new Diff(EXPECTED_2, stringWriter.toString()), true);
}
 
Example #18
Source File: DocumentContentTest.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Tests modification of the DocumentContentVO object directly.
 */
@Test public void testManualDocumentContentModification() throws Exception {
	WorkflowDocument document = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("ewestfal"), "TestDocumentType");
	document.saveDocumentData();
	
	// fetch it from WorkflowInfo
	DocumentContent content = KewApiServiceLocator.getWorkflowDocumentService().getDocumentContent(document.getDocumentId());
	assertTrue("Should contain default content, was " + content.getFullContent(), KewApiConstants.DEFAULT_DOCUMENT_CONTENT.equals(content.getFullContent()) ||
			KewApiConstants.DEFAULT_DOCUMENT_CONTENT2.equals(content.getFullContent()));
	
	String appContent = "<abcdefg>hijklm n o p</abcdefg>";
	DocumentContentUpdate.Builder contentUpdate = DocumentContentUpdate.Builder.create(content);
	contentUpdate.setApplicationContent(appContent);
	document.updateDocumentContent(contentUpdate.build());
    document.saveDocumentData();
	
	// test that the content on the document is the same as the content we just set
	XMLAssert.assertXMLEqual(appContent, document.getApplicationContent());
	
	// fetch the document fresh and make sure the content is correct
	document = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("ewestfal"), document.getDocumentId());
	XMLAssert.assertXMLEqual(appContent, document.getApplicationContent());
	
}
 
Example #19
Source File: AnalysisEngineFactoryTest.java    From uima-uimafit with Apache License 2.0 6 votes vote down vote up
@Test
  public void serializeComponent() throws Exception {
    File reference = new File("src/test/resources/data/reference/SerializationTestAnnotator.xml");
    
    File target = new File("target/test-output/AnalysisEngineFactoryTest/SerializationTestAnnotator.xml");
    target.getParentFile().mkdirs();
    
    AnalysisEngineDescription desc = createEngineDescription(SerializationTestAnnotator.class);
    try (OutputStream os = new FileOutputStream(target)) {
      desc.toXML(os);
    }
    
    String actual = FileUtils.readFileToString(target, "UTF-8");
    String expected = FileUtils.readFileToString(reference, "UTF-8");
    XMLUnit.setIgnoreWhitespace(true);
    XMLAssert.assertXMLEqual(expected, actual);
//    assertEquals(expected, actual);
  }
 
Example #20
Source File: PrettyPrinterTest.java    From googleads-java-lib with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that pretty printing works properly under normal circumstances.
 */
@Test
public void testPrettyPrint() throws SAXException, IOException, ParserConfigurationException {
  when(adsApiConfiguration.getSensitiveXPaths()).thenReturn(new String[] {TEST_SENSITIVE_XPATH});

  String prettyPrintedXml = createPrettyPrinter().prettyPrint(TEST_XML);
  String expectedXml = TEST_XML.replace("moe", "REDACTED");
  
  Document expectedDocument =
      XMLUnit.getControlDocumentBuilderFactory()
          .newDocumentBuilder()
          .parse(new InputSource(new StringReader(expectedXml)));
  Document actualDocument =
      XMLUnit.getTestDocumentBuilderFactory()
          .newDocumentBuilder()
          .parse(new InputSource(new StringReader(prettyPrintedXml)));
  XMLAssert.assertXMLEqual(
      XMLUnit.getWhitespaceStrippedDocument(expectedDocument),
      XMLUnit.getWhitespaceStrippedDocument(actualDocument));
}
 
Example #21
Source File: Bug8745Test.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testParsingAttributes() throws Exception {
    final QName contWithAttributes = QName.create("foo", "cont-with-attributes");
    final ContainerSchemaNode contWithAttr = (ContainerSchemaNode) SchemaContextUtil.findDataSchemaNode(
        SCHEMA_CONTEXT, SchemaPath.create(true, contWithAttributes));

    final Document doc = loadDocument("/bug8745/foo.xml");
    final DOMSource domSource = new DOMSource(doc.getDocumentElement());

    final DOMResult domResult = new DOMResult(UntrustedXML.newDocumentBuilder().newDocument());

    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);

    final NormalizedNodeStreamWriter streamWriter = XMLStreamNormalizedNodeStreamWriter.create(
            xmlStreamWriter, SCHEMA_CONTEXT);

    final XMLStreamReader reader = new DOMSourceXMLStreamReader(domSource);
    final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, SCHEMA_CONTEXT, contWithAttr);
    xmlParser.parse(reader);

    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalize(true);

    final String expectedXml = toString(doc.getDocumentElement());
    final String serializedXml = toString(domResult.getNode());
    final Diff diff = new Diff(expectedXml, serializedXml);

    XMLAssert.assertXMLEqual(diff, true);
}
 
Example #22
Source File: DcStreamEditorTest.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testTransformation() throws Exception {
    ModsDefinition mods = ModsUtils.unmarshalModsType(new StreamSource(DcStreamEditorTest.class.getResource("periodical.xml").toExternalForm()));
    Transformer t = DcUtils.modsTransformer("model:periodical");
    JAXBSource jaxbSource = new JAXBSource(ModsUtils.defaultMarshaller(false),
            new ObjectFactory().createMods(mods));
    StringWriter dump = new StringWriter();
    t.transform(jaxbSource, new StreamResult(dump));
    String toXml = dump.toString();
    System.out.println(toXml);

    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("oai_dc", DcStreamEditor.DATASTREAM_FORMAT_URI);
    namespaces.put("dc", "http://purl.org/dc/elements/1.1/");
    XMLUnit.setXpathNamespaceContext(new SimpleNamespaceContext(namespaces));
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:title[text()='main']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:title[text()='key']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:title[text()='alternative']", toXml);
    XMLAssert.assertXpathEvaluatesTo("3", "count(/oai_dc:dc/dc:title)", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:creator[text()='Boleslav']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:description[text()='poznámka']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:identifier[text()='uuid:40d13cb2-811f-468c-a6d3-1ad6b01f06f7']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:identifier[text()='isbn:0eaa6730']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:identifier[text()='issn-l:idIssn-l']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:identifier[text()='idWitEmptyType']", toXml);
    XMLAssert.assertXpathExists("/oai_dc:dc/dc:identifier[text()='idWithoutType']", toXml);
    // XXX needs more test
}
 
Example #23
Source File: EntryXmlReadOnlyTest.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@Test
public void entryMediaResource() throws Exception {
  HttpResponse response = callUri("Employees('2')/$value");
  checkMediaType(response, IMAGE_JPEG);
  assertNotNull(getBody(response));

  response = callUri("Employees('2')/$value?$format=xml", HttpStatusCodes.BAD_REQUEST);
  String body = getBody(response);
  XMLAssert.assertXpathExists("/m:error/m:message", body);
}
 
Example #24
Source File: AbstractYinExportTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
private static void assertXMLEquals(final String fileName, final Document expectedXMLDoc, final String output)
        throws SAXException, IOException {
    final String expected = YinExportTestUtils.toString(expectedXMLDoc.getDocumentElement());

    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalize(true);
    XMLUnit.setNormalizeWhitespace(true);

    final Diff diff = new Diff(expected, output);
    diff.overrideElementQualifier(new ElementNameAndAttributeQualifier());
    XMLAssert.assertXMLEqual(fileName, diff, true);
}
 
Example #25
Source File: AxisSerializerTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testSerialize() throws SAXException, IOException {
  BatchJobMutateRequest mutate = new BatchJobMutateRequest();

  List<Operation> ops = Lists.newArrayList();
  Campaign campaign = new Campaign();
  campaign.setId(-1L);
  campaign.setName("Test campaign");
  campaign.setAdvertisingChannelType(AdvertisingChannelType.SEARCH);
  ops.add(new CampaignOperation(Operator.ADD, "ADD", campaign));

  AdGroup adGroup = new AdGroup();
  adGroup.setName("Test ad group");
  adGroup.setCampaignId(campaign.getId());

  ops.add(new AdGroupOperation(Operator.ADD, "ADD", adGroup));

  mutate.setOperations(ops.toArray(new Operation[0]));
  AxisSerializer serializer = new AxisSerializer();
  StringWriter writer = new StringWriter();
  SerializationContext context = new SerializationContext(writer);
  context.setSendDecl(true);
  context.setPretty(true);
  serializer.serialize(mutate, context);

  String serializedRequest = writer.toString();
  assertNotNull("Serialized request is null", serializedRequest);

  String expectedSerializedRequest =
      CharStreams.toString(
          new InputStreamReader(
              AxisSerializerTest.class.getResourceAsStream(
                  "resources/BatchJobMutate.request.xml"),
              UTF_8));
  XMLAssert.assertXMLEqual("Serialized request does not match expected XML",
      expectedSerializedRequest, serializedRequest);
}
 
Example #26
Source File: AnydataSerializeTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAnydataLoadFromXML() throws IOException, SAXException, XMLStreamException, URISyntaxException {
    // Load XML file
    Document doc = loadXmlDocument("/test-anydata.xml");
    final DOMSource domSource = new DOMSource(doc.getDocumentElement());

    //Load XML from file and write it with xmlParseStream
    final DOMResult domResult = new DOMResult(UntrustedXML.newDocumentBuilder().newDocument());
    final XMLStreamWriter xmlStreamWriter = factory.createXMLStreamWriter(domResult);
    final AnydataSchemaNode anyDataSchemaNode = (AnydataSchemaNode) SchemaContextUtil.findDataSchemaNode(
            SCHEMA_CONTEXT, SchemaPath.create(true, FOO_QNAME));
    final NormalizedNodeStreamWriter streamWriter = XMLStreamNormalizedNodeStreamWriter.create(
            xmlStreamWriter, SCHEMA_CONTEXT);
    final XMLStreamReader reader = new DOMSourceXMLStreamReader(domSource);
    final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, SCHEMA_CONTEXT, anyDataSchemaNode);

    xmlParser.parse(reader);
    xmlParser.flush();

    //Set XML comparing
    XMLUnit.setIgnoreWhitespace(true);
    XMLUnit.setNormalize(true);

    // Check diff
    final String expectedXml = toString(doc.getDocumentElement());
    final String serializedXml = toString(domResult.getNode());
    final Diff diff = new Diff(expectedXml, serializedXml);
    final DifferenceListener differenceListener = new IgnoreTextAndAttributeValuesDifferenceListener();
    diff.overrideDifferenceListener(differenceListener);

    XMLAssert.assertXMLEqual(diff, true);
}
 
Example #27
Source File: AnydataSerializeTest.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testAnydataSerialization()
        throws IOException, SAXException, XMLStreamException, URISyntaxException, TransformerException {
    //Get XML Data.
    Document doc = loadXmlDocument("/test-anydata.xml");
    final DOMSource domSource = new DOMSource(doc.getDocumentElement());

    //Get specific attribute from Yang file.
    final AnydataSchemaNode contWithAttr = (AnydataSchemaNode) SchemaContextUtil.findDataSchemaNode(
            SCHEMA_CONTEXT, SchemaPath.create(true, FOO_QNAME));

    //Create NormalizedNodeResult
    NormalizedNodeResult normalizedResult = new NormalizedNodeResult();
    final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(normalizedResult);

    //Initialize Reader with XML file
    final XMLStreamReader reader = new DOMSourceXMLStreamReader(domSource);
    final XmlParserStream xmlParser = XmlParserStream.create(streamWriter, SCHEMA_CONTEXT, contWithAttr);
    xmlParser.parse(reader);
    xmlParser.flush();

    //Get Result
    final NormalizedNode<?, ?> node = normalizedResult.getResult();
    assertTrue(node instanceof AnydataNode);
    final AnydataNode<?> anydataResult = (AnydataNode<?>) node;

    //Get Result in formatted String
    assertTrue(anydataResult.getValue() instanceof DOMSourceAnydata);
    final String serializedXml = getXmlFromDOMSource(((DOMSourceAnydata)anydataResult.getValue()).getSource());
    final String expectedXml = toString(doc.getDocumentElement());

    //Looking for difference in Serialized xml and in Loaded XML
    final Diff diff = new Diff(expectedXml, serializedXml);
    final DifferenceListener differenceListener = new IgnoreTextAndAttributeValuesDifferenceListener();
    diff.overrideDifferenceListener(differenceListener);

    XMLAssert.assertXMLEqual(diff, true);
}
 
Example #28
Source File: AdManagerAxisSoapIntegrationTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Tests making a Axis Ad Manager API call with OAuth2. */
@Test
public void testGoldenSoap_oauth2() throws Exception {
  testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION));

  GoogleCredential credential =
      new GoogleCredential.Builder()
          .setTransport(new NetHttpTransport())
          .setJsonFactory(new JacksonFactory())
          .build();
  credential.setAccessToken("TEST_ACCESS_TOKEN");

  AdManagerSession session =
      new AdManagerSession.Builder()
          .withApplicationName("TEST_APP")
          .withOAuth2Credential(credential)
          .withEndpoint(testHttpServer.getServerUrl())
          .withNetworkCode("TEST_NETWORK_CODE")
          .build();

  CompanyServiceInterface companyService =
      new AdManagerServices().get(session, CompanyServiceInterface.class);
  Company[] companies = companyService.createCompanies(new Company[] {new Company()});

  assertEquals(1234L, companies[0].getId().longValue());
  XMLAssert.assertXMLEqual(
      SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION),
      testHttpServer.getLastRequestBody());
  assertFalse(
      "Did not request compression but request was compressed",
      testHttpServer.wasLastRequestBodyCompressed());
  assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader());
}
 
Example #29
Source File: AdManagerJaxWsSoapCompressionIntegrationTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Tests making a JAX-WS Ad Manager API call with OAuth2 and compression enabled. */
@Test
public void testGoldenSoap_oauth2() throws Exception {
  testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION));

  GoogleCredential credential =
      new GoogleCredential.Builder()
          .setTransport(new NetHttpTransport())
          .setJsonFactory(new JacksonFactory())
          .build();
  credential.setAccessToken("TEST_ACCESS_TOKEN");

  AdManagerSession session =
      new AdManagerSession.Builder()
          .withApplicationName("TEST_APP")
          .withOAuth2Credential(credential)
          .withEndpoint(testHttpServer.getServerUrl())
          .withNetworkCode("TEST_NETWORK_CODE")
          .build();

  CompanyServiceInterface companyService =
      new AdManagerServices().get(session, CompanyServiceInterface.class);
  List<Company> companies = companyService.createCompanies(Lists.newArrayList(new Company()));

  assertEquals(1234L, companies.get(0).getId().longValue());
  assertTrue(
      "Compression was enabled but the last request body was not compressed",
      testHttpServer.wasLastRequestBodyCompressed());

  XMLAssert.assertXMLEqual(
      SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION),
      testHttpServer.getLastRequestBody());
  assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader());
}
 
Example #30
Source File: AdManagerJaxWsSoapIntegrationTest.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/** Tests making a JAX-WS Ad Manager API call with OAuth2. */
@Test
public void testGoldenSoap_oauth2() throws Exception {
  testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION));

  GoogleCredential credential =
      new GoogleCredential.Builder()
          .setTransport(new NetHttpTransport())
          .setJsonFactory(new JacksonFactory())
          .build();
  credential.setAccessToken("TEST_ACCESS_TOKEN");

  AdManagerSession session =
      new AdManagerSession.Builder()
          .withApplicationName("TEST_APP")
          .withOAuth2Credential(credential)
          .withEndpoint(testHttpServer.getServerUrl())
          .withNetworkCode("TEST_NETWORK_CODE")
          .build();

  CompanyServiceInterface companyService =
      new AdManagerServices().get(session, CompanyServiceInterface.class);
  List<Company> companies = companyService.createCompanies(Lists.newArrayList(new Company()));

  assertEquals(1234L, companies.get(0).getId().longValue());
  XMLAssert.assertXMLEqual(
      SoapRequestXmlProvider.getOAuth2SoapRequest(API_VERSION),
      testHttpServer.getLastRequestBody());
  assertFalse(
      "Did not request compression but request was compressed",
      testHttpServer.wasLastRequestBodyCompressed());
  assertEquals("Bearer TEST_ACCESS_TOKEN", testHttpServer.getLastAuthorizationHttpHeader());
}