001: package org.uispec4j.xml;
002:
003: import junit.framework.Assert;
004: import junit.framework.AssertionFailedError;
005: import org.uispec4j.utils.Utils;
006:
007: public class EventLogger {
008:
009: private StringBuffer buffer = new StringBuffer();
010: private Log lastLog;
011:
012: public EventLogger() {
013: reset();
014: }
015:
016: public void assertEquals(String expected) {
017: assertEquals(expected, true);
018: }
019:
020: public void assertEquals(EventLogger expected) {
021: Assert.assertEquals(expected.closeStream(), closeStream());
022: }
023:
024: public void assertEquivalent(String expected) {
025: assertEquals(expected, false);
026: }
027:
028: public void assertEmpty() throws Exception {
029: assertEquals("<log/>");
030: }
031:
032: public void reset() {
033: buffer.setLength(0);
034: buffer.append("<log>").append(Utils.LINE_SEPARATOR);
035: lastLog = null;
036: }
037:
038: public Log log(String eventName) {
039: endLastLog();
040: lastLog = new Log(eventName);
041: return lastLog;
042: }
043:
044: public class Log {
045: private Log(String eventName) {
046: buffer.append('<').append(eventName);
047: }
048:
049: public Log add(String key, String value) {
050: buffer.append(' ').append(key).append("=\"").append(value)
051: .append("\"");
052: return this ;
053: }
054:
055: public Log add(String key, int value) {
056: return add(key, Integer.toString(value));
057: }
058:
059: private void end() {
060: buffer.append("/>").append(Utils.LINE_SEPARATOR);
061: }
062: }
063:
064: private void endLastLog() {
065: if (lastLog != null) {
066: lastLog.end();
067: }
068: }
069:
070: private String closeStream() {
071: endLastLog();
072: buffer.append("</log>");
073: return buffer.toString();
074: }
075:
076: private void assertEquals(String expected,
077: boolean orderIsSignificant) {
078: String actual = closeStream();
079: if (expected.length() == 0) {
080: fail(expected, actual);
081: }
082: try {
083: if (orderIsSignificant) {
084: XmlAssert.assertEquals(expected.replace('\'', '"'),
085: actual.replaceAll("'", ""));
086: } else {
087: XmlAssert.assertEquivalent(expected.replace('\'', '"'),
088: actual.replaceAll("'", ""));
089: }
090: } catch (AssertionFailedError e) {
091: Assert.assertEquals(expected.replace('\'', '"'), actual
092: .replaceAll("'", ""));
093: fail(expected, actual);
094: }
095: reset();
096: }
097:
098: private void fail(String expected, String actual) {
099: throw new AssertionFailedError(new StringBuffer().append(
100: "Expected:").append(Utils.LINE_SEPARATOR).append(
101: expected).append(Utils.LINE_SEPARATOR).append(
102: "...but was:").append(Utils.LINE_SEPARATOR).append(
103: actual).append(Utils.LINE_SEPARATOR).toString());
104: }
105: }
|