1 21 22 package net.percederberg.grammatica.test; 23 24 import java.io.PrintWriter ; 25 import java.io.StringWriter ; 26 27 import junit.framework.TestCase; 28 29 import net.percederberg.grammatica.parser.Node; 30 import net.percederberg.grammatica.parser.ParseException; 31 import net.percederberg.grammatica.parser.Parser; 32 import net.percederberg.grammatica.parser.ParserCreationException; 33 import net.percederberg.grammatica.parser.ParserLogException; 34 35 41 abstract class ParserTestCase extends TestCase { 42 43 48 public ParserTestCase(String name) { 49 super(name); 50 } 51 52 60 protected void parse(Parser parser, String output) { 61 try { 62 validateTree(parser.parse(), output); 63 } catch (ParserCreationException e) { 64 fail(e.getMessage()); 65 } catch (ParserLogException e) { 66 fail(e.getError(0).getMessage()); 67 } 68 } 69 70 80 protected void failParse(Parser parser, 81 int type, 82 int line, 83 int column) { 84 85 try { 86 parser.parse(); 87 fail("parsing succeeded"); 88 } catch (ParserCreationException e) { 89 fail(e.getMessage()); 90 } catch (ParserLogException e) { 91 ParseException p = e.getError(0); 92 93 assertEquals("error count", 1, e.getErrorCount()); 94 assertEquals("error type", type, p.getErrorType()); 95 assertEquals("line number", line, p.getLine()); 96 assertEquals("column number", column, p.getColumn()); 97 } 98 } 99 100 108 private void validateTree(Node root, String str) { 109 StringWriter output = new StringWriter (); 110 111 root.printTo(new PrintWriter (output)); 112 validateLines(str, output.toString()); 113 } 114 115 122 private void validateLines(String expected, String result) { 123 int line = 1; 124 String expectLine; 125 String resultLine; 126 int pos; 127 128 while (expected.length() > 0 || result.length() > 0) { 129 pos = expected.indexOf('\n'); 130 if (pos >= 0) { 131 expectLine = expected.substring(0, pos); 132 expected = expected.substring(pos + 1); 133 } else { 134 expectLine = expected; 135 expected = ""; 136 } 137 pos = result.indexOf('\n'); 138 if (pos >= 0) { 139 resultLine = result.substring(0, pos); 140 result = result.substring(pos + 1); 141 } else { 142 resultLine = result; 143 result = ""; 144 } 145 validateLine(line, expectLine, resultLine); 146 line++; 147 } 148 } 149 150 158 private void validateLine(int line, String expected, String result) { 159 if (!expected.trim().equals(result.trim())) { 160 fail("on line: " + line + ", expected: '" + expected + 161 "', found: '" + result + "'"); 162 } 163 } 164 } 165 | Popular Tags |