View Javadoc

1   package au.com.bytecode.opencsv;
2   
3   /**
4    Copyright 2005 Bytecode Pty Ltd.
5   
6    Licensed under the Apache License, Version 2.0 (the "License");
7    you may not use this file except in compliance with the License.
8    You may obtain a copy of the License at
9   
10   http://www.apache.org/licenses/LICENSE-2.0
11  
12   Unless required by applicable law or agreed to in writing, software
13   distributed under the License is distributed on an "AS IS" BASIS,
14   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   See the License for the specific language governing permissions and
16   limitations under the License.
17   */
18  
19  import org.junit.Test;
20  
21  import java.io.*;
22  import java.sql.ResultSet;
23  import java.sql.SQLException;
24  import java.util.ArrayList;
25  import java.util.List;
26  
27  import static org.junit.Assert.*;
28  
29  public class CSVWriterTest {
30  
31  
32      /**
33       * Test routine for converting output to a string.
34       *
35       * @param args the elements of a line of the cvs file
36       * @return a String version
37       * @throws IOException if there are problems writing
38       */
39      private String invokeWriter(String[] args) throws IOException {
40          StringWriter sw = new StringWriter();
41          CSVWriter csvw = new CSVWriter(sw, ',', '\'');
42          csvw.writeNext(args);
43          return sw.toString();
44      }
45  
46      private String invokeNoEscapeWriter(String[] args) throws IOException {
47          StringWriter sw = new StringWriter();
48          CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, '\'', CSVWriter.NO_ESCAPE_CHARACTER);
49          csvw.writeNext(args);
50          return sw.toString();
51      }
52  
53      @Test
54      public void correctlyParseNullString() {
55          StringWriter sw = new StringWriter();
56          CSVWriter csvw = new CSVWriter(sw, ',', '\'');
57          csvw.writeNext(null);
58          assertEquals(0, sw.toString().length());
59      }
60  
61      @Test
62      public void correctlyParserNullObject() {
63          StringWriter sw = new StringWriter();
64          CSVWriter csvw = new CSVWriter(sw, ',', '\'');
65          csvw.writeNext(null, false);
66          assertEquals(0, sw.toString().length());
67      }
68  
69      /**
70       * Tests parsing individual lines.
71       *
72       * @throws IOException if the reader fails.
73       */
74      @Test
75      public void testParseLine() throws IOException {
76  
77          // test normal case
78          String[] normal = {"a", "b", "c"};
79          String output = invokeWriter(normal);
80          assertEquals("'a','b','c'\n", output);
81  
82          // test quoted commas
83          String[] quoted = {"a", "b,b,b", "c"};
84          output = invokeWriter(quoted);
85          assertEquals("'a','b,b,b','c'\n", output);
86  
87          // test empty elements
88          String[] empty = {,};
89          output = invokeWriter(empty);
90          assertEquals("\n", output);
91  
92          // test multiline quoted
93          String[] multiline = {"This is a \n multiline entry", "so is \n this"};
94          output = invokeWriter(multiline);
95          assertEquals("'This is a \n multiline entry','so is \n this'\n", output);
96  
97  
98          // test quoted line
99          String[] quoteLine = {"This is a \" multiline entry", "so is \n this"};
100         output = invokeWriter(quoteLine);
101         assertEquals("'This is a \"\" multiline entry','so is \n this'\n", output);
102 
103     }
104 
105     @Test
106     public void parseLineWithBothEscapeAndQuoteChar() throws IOException {
107         // test quoted line
108         String[] quoteLine = {"This is a 'multiline' entry", "so is \n this"};
109         String output = invokeWriter(quoteLine);
110         assertEquals("'This is a \"'multiline\"' entry','so is \n this'\n", output);
111     }
112 
113     /**
114      * Tests parsing individual lines.
115      *
116      * @throws IOException if the reader fails.
117      */
118     @Test
119     public void testParseLineWithNoEscapeChar() throws IOException {
120 
121         // test normal case
122         String[] normal = {"a", "b", "c"};
123         String output = invokeNoEscapeWriter(normal);
124         assertEquals("'a','b','c'\n", output);
125 
126         // test quoted commas
127         String[] quoted = {"a", "b,b,b", "c"};
128         output = invokeNoEscapeWriter(quoted);
129         assertEquals("'a','b,b,b','c'\n", output);
130 
131         // test empty elements
132         String[] empty = {,};
133         output = invokeNoEscapeWriter(empty);
134         assertEquals("\n", output);
135 
136         // test multiline quoted
137         String[] multiline = {"This is a \n multiline entry", "so is \n this"};
138         output = invokeNoEscapeWriter(multiline);
139         assertEquals("'This is a \n multiline entry','so is \n this'\n", output);
140 
141     }
142 
143     @Test
144     public void parseLineWithNoEscapeCharAndQuotes() throws IOException {
145         String[] quoteLine = {"This is a \" 'multiline' entry", "so is \n this"};
146         String output = invokeNoEscapeWriter(quoteLine);
147         assertEquals("'This is a \" 'multiline' entry','so is \n this'\n", output);
148     }
149 
150 
151     /**
152      * Test writing to a list.
153      *
154      * @throws IOException if the reader fails.
155      */
156     @Test
157     public void testWriteAll() throws IOException {
158 
159         List<String[]> allElements = new ArrayList<String[]>();
160         String[] line1 = "Name#Phone#Email".split("#");
161         String[] line2 = "Glen#1234#glen@abcd.com".split("#");
162         String[] line3 = "John#5678#john@efgh.com".split("#");
163         allElements.add(line1);
164         allElements.add(line2);
165         allElements.add(line3);
166 
167         StringWriter sw = new StringWriter();
168         CSVWriter csvw = new CSVWriter(sw);
169         csvw.writeAll(allElements);
170 
171         String result = sw.toString();
172         String[] lines = result.split("\n");
173 
174         assertEquals(3, lines.length);
175 
176     }
177 
178     /**
179      * Test writing from a list.
180      *
181      * @throws IOException if the reader fails.
182      */
183     @Test
184     public void testWriteAllObjects() throws IOException {
185 
186         List<String[]> allElements = new ArrayList<String[]>(3);
187         String[] line1 = "Name#Phone#Email".split("#");
188         String[] line2 = "Glen#1234#glen@abcd.com".split("#");
189         String[] line3 = "John#5678#john@efgh.com".split("#");
190         allElements.add(line1);
191         allElements.add(line2);
192         allElements.add(line3);
193 
194         StringWriter sw = new StringWriter();
195         CSVWriter csvw = new CSVWriter(sw);
196         csvw.writeAll(allElements, false);
197 
198         String result = sw.toString();
199         String[] lines = result.split("\n");
200 
201         assertEquals(3, lines.length);
202 
203         String[] values = lines[1].split(",");
204         assertEquals("1234", values[1]);
205     }
206 
207     /**
208      * Tests the option of having omitting quotes in the output stream.
209      *
210      * @throws IOException if bad things happen
211      */
212     @Test
213     public void testNoQuoteChars() throws IOException {
214 
215         String[] line = {"Foo", "Bar", "Baz"};
216         StringWriter sw = new StringWriter();
217         CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
218         csvw.writeNext(line);
219         String result = sw.toString();
220 
221         assertEquals("Foo,Bar,Baz\n", result);
222     }
223 
224     /**
225      * Tests the option of having omitting quotes in the output stream.
226      *
227      * @throws IOException if bad things happen
228      */
229     @Test
230     public void testNoQuoteCharsAndNoEscapeChars() throws IOException {
231 
232         String[] line = {"Foo", "Bar", "Baz"};
233         StringWriter sw = new StringWriter();
234         CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
235         csvw.writeNext(line);
236         String result = sw.toString();
237 
238         assertEquals("Foo,Bar,Baz\n", result);
239     }
240 
241     /**
242      * Tests the ability for the writer to apply quotes only where strings contain the separator, escape, quote or new line characters.
243      */
244     @Test
245     public void testIntelligentQuotes() {
246         String[] line = {"1", "Foo", "With,Separator", "Line\nBreak", "Hello \"Foo Bar\" World", "Bar"};
247         StringWriter sw = new StringWriter();
248         CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, CSVWriter.DEFAULT_ESCAPE_CHARACTER);
249         csvw.writeNext(line, false);
250         String result = sw.toString();
251 
252         assertEquals("1,Foo,\"With,Separator\",\"Line\nBreak\",\"Hello \"\"Foo Bar\"\" World\",Bar\n", result);
253     }
254 
255 
256     /**
257      * Test null values.
258      *
259      * @throws IOException if bad things happen
260      */
261     @Test
262     public void testNullValues() throws IOException {
263 
264         String[] line = {"Foo", null, "Bar", "baz"};
265         StringWriter sw = new StringWriter();
266         CSVWriter csvw = new CSVWriter(sw);
267         csvw.writeNext(line);
268         String result = sw.toString();
269 
270         assertEquals("\"Foo\",,\"Bar\",\"baz\"\n", result);
271 
272     }
273 
274     @Test
275     public void testStreamFlushing() throws IOException {
276 
277         String WRITE_FILE = "myfile.csv";
278 
279         String[] nextLine = new String[]{"aaaa", "bbbb", "cccc", "dddd"};
280 
281         FileWriter fileWriter = new FileWriter(WRITE_FILE);
282         CSVWriter writer = new CSVWriter(fileWriter);
283 
284         writer.writeNext(nextLine);
285 
286         // If this line is not executed, it is not written in the file.
287         writer.close();
288 
289     }
290 
291     @Test(expected = IOException.class)
292     public void flushWillThrowIOException() throws IOException {
293         String[] line = {"Foo", "bar's"};
294         StringWriter sw = new StringWriter();
295         CSVWriter csvw = new CSVWriterExceptionThrower(sw);
296         csvw.writeNext(line);
297         csvw.flush();
298     }
299 
300     @Test
301     public void flushQuietlyWillNotThrowException() {
302         String[] line = {"Foo", "bar's"};
303         StringWriter sw = new StringWriter();
304         CSVWriter csvw = new CSVWriterExceptionThrower(sw);
305         csvw.writeNext(line);
306         csvw.flushQuietly();
307     }
308 
309 
310     @Test
311     public void testAlternateEscapeChar() {
312         String[] line = {"Foo", "bar's"};
313         StringWriter sw = new StringWriter();
314         CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, '\'');
315         csvw.writeNext(line);
316         assertEquals("\"Foo\",\"bar''s\"\n", sw.toString());
317     }
318 
319     @Test
320     public void testNoQuotingNoEscaping() {
321         String[] line = {"\"Foo\",\"Bar\""};
322         StringWriter sw = new StringWriter();
323         CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
324         csvw.writeNext(line);
325         assertEquals("\"Foo\",\"Bar\"\n", sw.toString());
326     }
327 
328     @Test
329     public void testNestedQuotes() {
330         String[] data = new String[]{"\"\"", "test"};
331         String oracle = new String("\"\"\"\"\"\",\"test\"\n");
332 
333         CSVWriter writer = null;
334         File tempFile = null;
335         FileWriter fwriter = null;
336 
337         try {
338             tempFile = File.createTempFile("csvWriterTest", ".csv");
339             tempFile.deleteOnExit();
340             fwriter = new FileWriter(tempFile);
341             writer = new CSVWriter(fwriter);
342         } catch (IOException e) {
343             fail();
344         }
345 
346         // write the test data:
347         writer.writeNext(data);
348 
349         try {
350             writer.close();
351         } catch (IOException e) {
352             fail();
353         }
354 
355         try {
356             // assert that the writer was also closed.
357             fwriter.flush();
358             fail();
359         } catch (IOException e) {
360             // we should go through here..
361         }
362 
363         // read the data and compare.
364         FileReader in = null;
365         try {
366             in = new FileReader(tempFile);
367         } catch (FileNotFoundException e) {
368             fail();
369         }
370 
371         StringBuilder fileContents = new StringBuilder(CSVWriter.INITIAL_STRING_SIZE);
372         try {
373             int ch;
374             while ((ch = in.read()) != -1) {
375                 fileContents.append((char) ch);
376             }
377             in.close();
378         } catch (IOException e) {
379             fail();
380         }
381 
382         assertTrue(oracle.equals(fileContents.toString()));
383     }
384 
385     @Test
386     public void testAlternateLineFeeds() {
387         String[] line = {"Foo", "Bar", "baz"};
388         StringWriter sw = new StringWriter();
389         CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, "\r");
390         csvw.writeNext(line);
391         String result = sw.toString();
392 
393         assertTrue(result.endsWith("\r"));
394 
395     }
396 
397     @Test
398     public void testResultSetWithHeaders() throws SQLException, IOException {
399         String[] header = {"Foo", "Bar", "baz"};
400         String[] value = {"v1", "v2", "v3"};
401 
402         StringWriter sw = new StringWriter();
403         CSVWriter csvw = new CSVWriter(sw);
404         csvw.setResultService(new ResultSetHelperService());
405 
406         ResultSet rs = MockResultSetBuilder.buildResultSet(header, value, 1);
407 
408         csvw.writeAll(rs, true); // don't need a result set since I am mocking the result.
409         assertFalse(csvw.checkError());
410         String result = sw.toString();
411 
412         assertNotNull(result);
413         assertEquals("\"Foo\",\"Bar\",\"baz\"\n\"v1\",\"v2\",\"v3\"\n", result);
414     }
415 
416     @Test
417     public void testMultiLineResultSetWithHeaders() throws SQLException, IOException {
418         String[] header = {"Foo", "Bar", "baz"};
419         String[] value = {"v1", "v2", "v3"};
420 
421         StringWriter sw = new StringWriter();
422         CSVWriter csvw = new CSVWriter(sw);
423         csvw.setResultService(new ResultSetHelperService());
424 
425         ResultSet rs = MockResultSetBuilder.buildResultSet(header, value, 3);
426 
427         csvw.writeAll(rs, true); // don't need a result set since I am mocking the result.
428         assertFalse(csvw.checkError());
429         String result = sw.toString();
430 
431         assertNotNull(result);
432         assertEquals("\"Foo\",\"Bar\",\"baz\"\n\"v1\",\"v2\",\"v3\"\n\"v1\",\"v2\",\"v3\"\n\"v1\",\"v2\",\"v3\"\n", result);
433     }
434 
435     @Test
436     public void testResultSetWithoutHeaders() throws SQLException, IOException {
437         String[] header = {"Foo", "Bar", "baz"};
438         String[] value = {"v1", "v2", "v3"};
439 
440         StringWriter sw = new StringWriter();
441         CSVWriter csvw = new CSVWriter(sw);
442         csvw.setResultService(new ResultSetHelperService());
443 
444         ResultSet rs = MockResultSetBuilder.buildResultSet(header, value, 1);
445 
446         csvw.writeAll(rs, false); // don't need a result set since I am mocking the result.
447         assertFalse(csvw.checkError());
448         String result = sw.toString();
449 
450         assertNotNull(result);
451         assertEquals("\"v1\",\"v2\",\"v3\"\n", result);
452     }
453 
454     @Test
455     public void testMultiLineResultSetWithoutHeaders() throws SQLException, IOException {
456         String[] header = {"Foo", "Bar", "baz"};
457         String[] value = {"v1", "v2", "v3"};
458 
459         StringWriter sw = new StringWriter();
460         CSVWriter csvw = new CSVWriter(sw);
461         csvw.setResultService(new ResultSetHelperService());
462 
463         ResultSet rs = MockResultSetBuilder.buildResultSet(header, value, 3);
464 
465         csvw.writeAll(rs, false); // don't need a result set since I am mocking the result.
466 
467         assertFalse(csvw.checkError());
468         String result = sw.toString();
469 
470         assertNotNull(result);
471         assertEquals("\"v1\",\"v2\",\"v3\"\n\"v1\",\"v2\",\"v3\"\n\"v1\",\"v2\",\"v3\"\n", result);
472     }
473 
474     @Test
475     public void testResultSetTrim() throws SQLException, IOException {
476         String[] header = {"Foo", "Bar", "baz"};
477         String[] value = {"v1         ", "v2 ", "v3"};
478 
479         StringWriter sw = new StringWriter();
480         CSVWriter csvw = new CSVWriter(sw);
481         csvw.setResultService(new ResultSetHelperService());
482 
483         ResultSet rs = MockResultSetBuilder.buildResultSet(header, value, 1);
484 
485         csvw.writeAll(rs, true, true); // don't need a result set since I am mocking the result.
486         assertFalse(csvw.checkError());
487         String result = sw.toString();
488 
489         assertNotNull(result);
490         assertEquals("\"Foo\",\"Bar\",\"baz\"\n\"v1\",\"v2\",\"v3\"\n", result);
491     }
492 
493 }