Package net.sourceforge.chaperon.test

Source Code of net.sourceforge.chaperon.test.ParserProcessorTestCase

/*
*  Copyright (C) Chaperon. All rights reserved.
*  -------------------------------------------------------------------------
*  This software is published under the terms of the Apache Software License
*  version 1.1, a copy of which has been included  with this distribution in
*  the LICENSE file.
*/

package net.sourceforge.chaperon.test;

import junit.framework.*;

import net.sourceforge.chaperon.build.ParserAutomatonBuilder;
import net.sourceforge.chaperon.common.ConsoleLog;
import net.sourceforge.chaperon.model.grammar.Grammar;
import net.sourceforge.chaperon.model.grammar.GrammarFactory;
import net.sourceforge.chaperon.process.*;

import org.custommonkey.xmlunit.Diff;

import org.w3c.dom.*;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import java.io.*;

import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.sax.*;
import javax.xml.transform.stream.*;

public class ParserProcessorTestCase extends TestCase
{
  private String name;
  private Element step;

  public ParserProcessorTestCase(String name)
  {
    super(name);
    this.name = name;
  }

  public ParserProcessorTestCase(String name, Element step)
  {
    super(name);
    this.name = name;
    this.step = step;
  }

  public void runTest() throws Throwable
  {
    System.out.println("======================= "+name+" =======================");

    Grammar grammar = getGrammar(step);

    //System.out.println("Grammar:\n"+grammar);
    ParserProcessor processor = getParserProcessor(grammar);

    Document result = null;

    result = process(processor, step);

    Document expected = getResult(step);

    assertEqual(expected, result);
  }

  private ParserProcessor getParserProcessor(Grammar grammar)
  {
    ParserProcessor processor = new ParserProcessor();
    processor.setLog(new ConsoleLog());

    ParserAutomaton automaton =
      (new ParserAutomatonBuilder(grammar, new ConsoleLog())).getParserAutomaton();

    //  (new ParserAutomatonBuilder(grammar)).getParserAutomaton();
    assertNotNull("Test if automaton is generated", automaton);

    //System.out.println("Automaton:\n"+automaton);
    processor.setParserAutomaton(automaton);

    NodeList list = step.getElementsByTagName("parameter");
    for (int i = 0; i<list.getLength(); i++)
    {
      Element element = (Element)list.item(i);
      if (element.getAttribute("name").equals("flatten"))
        processor.setFlatten(Boolean.valueOf(element.getAttribute("value")).booleanValue());
    }

    return processor;
  }

  private Document process(ParserProcessor processor, Element step)
    throws Exception
  {
    NodeList list =
      step.getElementsByTagNameNS(LexicalProcessor.NS_OUTPUT, LexicalProcessor.OUTPUT);
    Node node = list.item(0);

    TransformerFactory streamerfactory = TransformerFactory.newInstance();
    Transformer streamer = streamerfactory.newTransformer();

    SAXTransformerFactory serializerfactory =
      (SAXTransformerFactory)SAXTransformerFactory.newInstance();
    TransformerHandler serializer = serializerfactory.newTransformerHandler();
    DOMResult result = new DOMResult();
    serializer.setResult(result);

    processor.setContentHandler(new WhitespaceFilter(serializer));

    streamer.transform(new DOMSource(node), new SAXResult(processor));

    return (Document)result.getNode();
  }

  private Grammar getGrammar(Element step) throws Exception
  {
    NodeList list =
      step.getElementsByTagNameNS("http://chaperon.sourceforge.net/schema/grammar/1.0", "grammar");
    Node node = list.item(0);

    TransformerFactory streamerfactory = TransformerFactory.newInstance();
    Transformer streamer = streamerfactory.newTransformer();

    GrammarFactory grammarfactory = new GrammarFactory();

    streamer.transform(new DOMSource(node), new SAXResult(grammarfactory));

    Grammar grammar = grammarfactory.getGrammar();

    System.out.println("Grammar:\n"+grammar);

    return grammar;
  }

  private Document getResult(Element step) throws Exception
  {
    NodeList list = step.getElementsByTagNameNS(ParserProcessor.NS_OUTPUT, ParserProcessor.OUTPUT);
    Node node = list.item(0);

    TransformerFactory streamerfactory = TransformerFactory.newInstance();
    Transformer streamer = streamerfactory.newTransformer();

    //DOMSource source = new DOMSource(node);
    DOMResult result = new DOMResult();

    streamer.transform(new DOMSource(node), result);

    return (Document)result.getNode();
  }

  private static Document getDocument(String filename, InputStream in)
    throws Exception
  {
    SAXParserFactory parserfactory = SAXParserFactory.newInstance();
    parserfactory.setNamespaceAware(true);

    XMLReader parser = parserfactory.newSAXParser().getXMLReader();

    SAXTransformerFactory serializerfactory =
      (SAXTransformerFactory)SAXTransformerFactory.newInstance();
    TransformerHandler handler = serializerfactory.newTransformerHandler();
    DOMResult result = new DOMResult();
    handler.setResult(result);

    parser.setContentHandler(new WhitespaceFilter(handler));

    InputSource inputsource = new InputSource(in);
    inputsource.setSystemId(filename);
    parser.parse(inputsource);

    return (Document)result.getNode();
  }

  public final void print(Document document) throws Exception
  {
    TransformerFactory factory = TransformerFactory.newInstance();
    javax.xml.transform.Transformer serializer = factory.newTransformer();
    serializer.transform(new DOMSource(document), new StreamResult(System.out));
    System.out.println();
  }

  /**
   * Compare two XML documents provided as strings
   *
   * @param control Control document
   * @param test Document to test
   *
   * @return Diff object describing differences in documents
   */
  public final Diff compareXML(Document control, Document test)
  {
    return new Diff(control, test);
  }

  /**
   * Assert that the result of an XML comparison is similar.
   *
   * @param msg The assertion message
   * @param expected The expected XML document
   * @param actual The actual XML Document
   */
  public final void assertEqual(String msg, Document expected, Document actual)
  {
    expected.getDocumentElement().normalize();
    actual.getDocumentElement().normalize();

    Diff diff = compareXML(expected, actual);

    if (!diff.similar())
    {
      try
      {
        System.out.println("expected:");
        print(expected);
        System.out.println("actual:");
        print(actual);
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
    }

    assertEquals(msg+", "+diff.toString(), true, diff.similar());
  }

  /**
   * Assert that the result of an XML comparison is similar.
   *
   * @param msg The assertion message
   * @param expected The expected XML document
   * @param actual The actual XML Document
   */
  public final void assertEqual(Document expected, Document actual)
  {
    expected.getDocumentElement().normalize();
    actual.getDocumentElement().normalize();

    Diff diff = compareXML(expected, actual);

    if (!diff.similar())
    {
      try
      {
        System.out.println("expected:");
        print(expected);
        System.out.println("actual:");
        print(actual);
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
    }

    assertEquals("Test if the assertion document is equal, "+diff.toString(), true, diff.similar());
  }

  public static Test suite()
  {
    TestSuite suite = new TestSuite("ParserProcessorTest");

    try
    {
      File directory = new File(ParserProcessorTestCase.class.getResource("parser").getFile());
      File[] files = directory.listFiles();

      for (int i = 0; i<files.length; i++)
        if ((files[i].getName().endsWith(".xml"))  /* && (files[i].getName().startsWith("test18"))*/)
        {
          Document test = getDocument(files[i].toString(), new FileInputStream(files[i]));

          NodeList list = test.getDocumentElement().getElementsByTagName("step");
          for (int j = 0; j<list.getLength(); j++)
          {
            Element step = (Element)list.item(j);

            suite.addTest(new ParserProcessorTestCase("ParserProcessorTest "+files[i].getName()+":"+
                                                      step.getAttribute("name"), step));
          }
        }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }

    return suite;
  }
}
TOP

Related Classes of net.sourceforge.chaperon.test.ParserProcessorTestCase

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.