KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jimm > datavision > test > CharSepTest


1 package jimm.datavision.test;
2 import jimm.datavision.*;
3 import jimm.datavision.field.*;
4 import jimm.datavision.layout.CharSepLE;
5 import jimm.datavision.source.Column;
6 import jimm.datavision.source.charsep.CharSepSource;
7 import java.io.*;
8 import java.util.Date JavaDoc;
9 import java.text.DecimalFormat JavaDoc;
10 import java.text.SimpleDateFormat JavaDoc;
11 import junit.framework.TestCase;
12 import junit.framework.TestSuite;
13 import junit.framework.Test;
14
15 /**
16  * Reads a report from an XML file, runs it, and verifies the output. Uses
17  * a {@link CharSepSource} data source and the {@link CharSepLE} layout engine
18  * to produce a tab-delimited output file.
19  * <p>
20  * These tests are tightly coupled with the contents of the files
21  * <code>charsep.xml</code> and <code>charsep_data.csv</code>.
22  *
23  * @author Jim Menard, <a HREF="mailto:jimm@io.com">jimm@io.com</a>
24  */

25 public class CharSepTest extends TestCase {
26
27 protected static final File EXAMPLE_REPORT =
28     new File(AllTests.testDataFile("charsep.xml"));
29 protected static final String JavaDoc DATA_FILE =
30     AllTests.testDataFile("charsep_data.csv");
31 protected static final String JavaDoc EMPTY_DATA_FILE =
32     AllTests.testDataFile("empty.csv");
33 protected static final String JavaDoc DATA_FILE_WITH_SHORT_LINES =
34     AllTests.testDataFile("short_lines.csv");
35 protected static final File OUT_FILE =
36     new File(System.getProperty("java.io.tmpdir"),
37          "datavision_charsep_test_out.txt");
38 // This must match the format string for the report.date field in
39
// EXAMPLE_REPORT.
40
protected static final String JavaDoc REPORT_DATE_FORMAT = "yyyy-MM-dd";
41 // This must be an alphabetically sorted list of office names from the
42
// offices table, EXCEPT for Chicago, which is excluded by the where
43
// clause.
44
protected static final String JavaDoc OFFICES[] = {
45     "New Jersey", "New York"
46 };
47 // The value of the report.title special field, which appears
48
// in the report header.
49
protected static final String JavaDoc REPORT_TITLE = "Example Report";
50
51 protected Report report;
52 protected CharSepSource dataSource;
53 protected DecimalFormat JavaDoc dollarFormatter;
54 protected DecimalFormat JavaDoc lastColFormatter;
55 protected SimpleDateFormat JavaDoc titleDateFormatter;
56 protected int reportRowNumber;
57 protected int officeRowNumber;
58 protected int postDateRowNumber;
59
60 public static Test suite() {
61     return new TestSuite(CharSepTest.class);
62 }
63
64 public CharSepTest(String JavaDoc name) {
65     super(name);
66 }
67
68 public void setUp() throws Exception JavaDoc {
69     dollarFormatter = new DecimalFormat JavaDoc("$#,###.00");
70     lastColFormatter = new DecimalFormat JavaDoc("#,###.##");
71     titleDateFormatter = new SimpleDateFormat JavaDoc(REPORT_DATE_FORMAT);
72
73     report = new Report();
74     reportRowNumber = officeRowNumber = postDateRowNumber = 1;
75
76     OUT_FILE.deleteOnExit();
77     PrintWriter out = new PrintWriter(new FileWriter(OUT_FILE));
78     report.setLayoutEngine(new CharSepLE(out, '\t'));
79
80     report.read(EXAMPLE_REPORT); // Must come after setting password
81

82     dataSource = (CharSepSource)report.getDataSource();
83     dataSource.setSepChar(',');
84     dataSource.setInput(DATA_FILE);
85 }
86
87 public void tearDown() {
88     if (OUT_FILE.exists())
89     OUT_FILE.delete();
90 }
91
92 public void testColumnInfo() {
93     String JavaDoc[] colNames = { "office.name", "jobs.ID", "jobs.title",
94               "jobs.hourly rate", "jobs.post_date" };
95     for (int i = 0; i < colNames.length; ++i) {
96     Column col;
97     assertNotNull(col = dataSource.findColumn(colNames[i]));
98     assertEquals(i, dataSource.indexOfSelectable(col));
99     }
100 }
101
102 public void testReportRun() throws IOException, FileNotFoundException {
103     assertEquals("{office.name} != 'Chicago'",
104          report.getDataSource().getQuery().getWhereClause());
105
106     // Run report in this thread, not a separate one. Running the
107
// report closes the output stream.
108
report.runReport();
109
110     // Open the output and look for various things.
111
BufferedReader in = new BufferedReader(new FileReader(OUT_FILE));
112
113     expectHeaders(in);
114
115     // Each of the office groups. checkOfficeGroup() returns the total
116
// dollar amount (really the total id number amount, but that is proved
117
// to be the same thing within checkDetailLine()).
118
int total = 0;
119     for (int i = 0; i < OFFICES.length; ++i)
120     total += checkOfficeGroup(in, OFFICES[i]);
121
122     // The grand total.
123
String JavaDoc line = in.readLine();
124     assertNotNull(line);
125     if (line.startsWith("Page "))
126     assertNotNull(line = in.readLine());
127
128     assertEquals("Grand Total:\t" + dollarFormatter.format(total)
129          + "\t" + (reportRowNumber - 1)
130          + "\t" + (reportRowNumber - 1),
131          line);
132
133     // The final page number.
134
assertNotNull(line = in.readLine());
135     assertEquals("Page ", line.substring(0, 5));
136
137     // Make sure we are at the end of the file.
138
assertNull(in.readLine());
139
140     in.close();
141 }
142
143 protected void expectHeaders(BufferedReader in) throws IOException {
144     String JavaDoc line;
145
146     // Line 1: report title and formatted date.
147
// since that will most definitely be different.
148
assertNotNull(line = in.readLine());
149     assertEquals(REPORT_TITLE + '\t'
150          + "file:examples/Home16.gif"
151          + '\t' + titleDateFormatter.format(new Date JavaDoc()),
152          line);
153
154     // Line 2: the page header.
155
assertNotNull(line = in.readLine());
156     assertEquals(0, line.indexOf("Job #\tTitle\tHourly Rate"));
157 }
158
159 /**
160  * Checks a group (header plus detail lines) and returns the total
161  * of the dollar amounts in the group.
162  *
163  * @param in the input reader
164  * @param officeName the group name
165  * @return the total dollar amount in the group
166  */

167 protected int checkOfficeGroup(BufferedReader in, String JavaDoc officeName)
168     throws IOException
169 {
170     String JavaDoc line;
171     int aggregate = 0;
172
173     officeRowNumber = 1;
174
175     // The office name. Skip page delimiters ("Page" at foot and
176
// page headers at top).
177
assertNotNull(line = in.readLine());
178     while (line.startsWith("Page ") || line.startsWith("Job #\t"))
179     assertNotNull(line = in.readLine());
180     assertEquals(officeName, line);
181
182     Object JavaDoc postDateGroupEnd;
183     while ((postDateGroupEnd = checkPostDateGroup(in)) instanceof Integer JavaDoc)
184     aggregate += ((Integer JavaDoc)postDateGroupEnd).intValue();
185     line = (String JavaDoc)postDateGroupEnd;
186
187     assertEquals("Total:\t" + dollarFormatter.format(aggregate)
188          + "\t" + (reportRowNumber - 1)
189          + "\t" + (officeRowNumber - 1),
190          line);
191
192     return aggregate;
193 }
194
195 /**
196  * Checks a subgroup (header plus detail lines) and returns the total
197  * of the dollar amounts in the group. If the next report section is
198  * not a subgroup, it will be a group total line; we return the line
199  *
200  * @param in the input reader
201  * @return either an Integer containing the total or the next line read
202  * from the report
203  */

204 protected Object JavaDoc checkPostDateGroup(BufferedReader in) throws IOException {
205     int aggregate = 0;
206     String JavaDoc line;
207
208     postDateRowNumber = 1;
209
210     // Read either post date or next (super)group name. Return false if we
211
// see a non-date group name; that means we're done. Skip page
212
// delimiters ("Page" at foot and page headers at top).
213
while (true) {
214     assertNotNull(line = in.readLine());
215     if (line.startsWith("Page ") || line.startsWith("Job #\t"))
216         continue;
217     if (line.startsWith("Total:"))
218         return line;
219
220     // Primitive date check
221
assertTrue(Character.isDigit(line.charAt(0)) && line.length() == 10
222            && line.charAt(4) == '-' && line.charAt(7) == '-');
223     break;
224     }
225
226     // The detail lines. Collect the id number from the beginning of each
227
// detail line. It is the same as the dollar amount value. Add that
228
// amount to the aggregate.
229
while (true) {
230     assertNotNull(line = in.readLine());
231     if (line.startsWith("Post Date Total:"))
232         break;
233     if (line.startsWith("Page ") || line.startsWith("Job #\t"))
234         continue;
235
236     aggregate += checkDetailLine(line);
237     }
238
239     assertEquals("Post Date Total:\t" + dollarFormatter.format(aggregate)
240          + "\t" + (reportRowNumber - 1)
241          + "\t" + (postDateRowNumber - 1),
242          line);
243
244     return new Integer JavaDoc(aggregate);
245 }
246
247 /**
248  * Checks the format of a detail line and returns the integer id found
249  * at the beginning of line. This is the same as the dollar amount.
250  *
251  * @param line a detail line
252  * @return the id number
253  */

254 protected int checkDetailLine(String JavaDoc line) {
255     // Read job id from the beginning of the line.
256
int id = Integer.parseInt(line.substring(0, line.indexOf("\t")));
257
258     // The description, at random, may be repeated ("job 3 job 3"). We
259
// check for the first full description.
260
String JavaDoc str = "" + id + "\tThis is the short description of job " + id;
261     assertTrue("line does not start with \"" + str + "\"",
262            line.startsWith(str));
263
264     // Check for the remaining columns at the end of the line. We are also
265
// assuring that the dollar amount is the same as the id number.
266
if (id == 0) {
267     assertEquals("0\tThis is the short description of job 0\t\t\t\t"
268              + reportRowNumber + "\t" + postDateRowNumber,
269              line);
270     }
271     else {
272     str = "\t" + (id * 100)
273         + "\t" + dollarFormatter.format(id)
274         + "\t" + lastColFormatter.format(id)
275         + "\t" + reportRowNumber
276         + "\t" + postDateRowNumber;
277     assertTrue("line \"" + line + "\" does not end with \"" + str,
278            line.endsWith(str));
279     }
280
281     ++reportRowNumber;
282     ++officeRowNumber;
283     ++postDateRowNumber;
284
285     return id;
286 }
287
288 // We used to throw an exception if there were no records returned
289
// by the query but there was a column field in the page header or
290
// report header.
291
public void testNoRecords() {
292     try {
293     // Add a column field to the report header
294
Section pageHeader =
295         report.getFirstSectionByArea(SectionArea.PAGE_HEADER);
296     assertNotNull(pageHeader);
297     ColumnField f = new ColumnField(null, report, pageHeader,
298                     "office.name", true);
299     pageHeader.addField(f);
300
301     // Create a query that returns 0 records
302
report.getDataSource().getQuery().setWhereClause("1 == 2");
303
304     // Run the report. We shouldn't throw an exception.
305
report.runReport();
306     }
307     catch (Exception JavaDoc e) {
308     fail("should not throw an exception just 'cause there are no records");
309     }
310 }
311
312 // public void testWhereClause() {
313
// }
314

315 public void testEmptyFile() {
316     try {
317     dataSource.setInput(EMPTY_DATA_FILE);
318     report.runReport();
319     }
320     catch (Exception JavaDoc e) {
321     fail("should not throw an exception just 'cause the file is empty");
322     }
323 }
324
325 public void testShortInputLines() {
326     try {
327     dataSource.setInput(DATA_FILE_WITH_SHORT_LINES);
328     report.runReport();
329     }
330     catch (Exception JavaDoc e) {
331     fail("should not throw an exception just 'cause some lines are short");
332     }
333 }
334
335 public static void main(String JavaDoc[] args) {
336     junit.textui.TestRunner.run(suite());
337     System.exit(0);
338 }
339
340 }
341
Popular Tags