EventLogger.java :  » Testing » UISpec4J » org » uispec4j » xml » Java Open Source

Java Open Source » Testing » UISpec4J 
UISpec4J » org » uispec4j » xml » EventLogger.java
package org.uispec4j.xml;

import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import org.uispec4j.utils.Utils;

public class EventLogger {

  private StringBuffer buffer = new StringBuffer();
  private Log lastLog;

  public EventLogger() {
    reset();
  }

  public void assertEquals(String expected) {
    assertEquals(expected, true);
  }

  public void assertEquals(EventLogger expected) {
    Assert.assertEquals(expected.closeStream(), closeStream());
  }

  public void assertEquivalent(String expected) {
    assertEquals(expected, false);
  }

  public void assertEmpty() throws Exception {
    assertEquals("<log/>");
  }

  public void reset() {
    buffer.setLength(0);
    buffer.append("<log>").append(Utils.LINE_SEPARATOR);
    lastLog = null;
  }

  public Log log(String eventName) {
    endLastLog();
    lastLog = new Log(eventName);
    return lastLog;
  }

  public class Log {
    private Log(String eventName) {
      buffer.append('<').append(eventName);
    }

    public Log add(String key, String value) {
      buffer.append(' ').append(key).append("=\"").append(value).append("\"");
      return this;
    }

    public Log add(String key, int value) {
      return add(key, Integer.toString(value));
    }

    private void end() {
      buffer.append("/>").append(Utils.LINE_SEPARATOR);
    }
  }

  private void endLastLog() {
    if (lastLog != null) {
      lastLog.end();
    }
  }

  private String closeStream() {
    endLastLog();
    buffer.append("</log>");
    return buffer.toString();
  }

  private void assertEquals(String expected, boolean orderIsSignificant) {
    String actual = closeStream();
    if (expected.length() == 0) {
      fail(expected, actual);
    }
    try {
      if (orderIsSignificant) {
        XmlAssert.assertEquals(expected.replace('\'', '"'), actual.replaceAll("'", ""));
      }
      else {
        XmlAssert.assertEquivalent(expected.replace('\'', '"'), actual.replaceAll("'", ""));
      }
    }
    catch (AssertionFailedError e) {
      Assert.assertEquals(expected.replace('\'', '"'), actual.replaceAll("'", ""));
      fail(expected, actual);
    }
    reset();
  }

  private void fail(String expected, String actual) {
    throw new AssertionFailedError(new StringBuffer()
      .append("Expected:").append(Utils.LINE_SEPARATOR)
      .append(expected).append(Utils.LINE_SEPARATOR)
      .append("...but was:").append(Utils.LINE_SEPARATOR)
      .append(actual).append(Utils.LINE_SEPARATOR).toString());
  }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.