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 static org.junit.Assert.*;
20  import org.junit.Test;
21  
22  import java.io.*;
23  import java.util.ArrayList;
24  import java.util.List;
25  
26  public class CSVWriterTest {
27  
28  
29      /**
30       * Test routine for converting output to a string.
31       *
32       * @param args
33       *            the elements of a line of the cvs file
34       * @return a String version
35       * @throws IOException
36       *             if there are problems writing
37       */
38      private String invokeWriter(String[] args) throws IOException {
39          StringWriter sw = new StringWriter();
40          CSVWriter csvw = new CSVWriter(sw,',','\'');
41          csvw.writeNext(args);
42          return sw.toString();
43      }
44      
45      private String invokeNoEscapeWriter(String[] args) throws IOException {
46          StringWriter sw = new StringWriter();
47          CSVWriter csvw = new CSVWriter(sw,',','\'', CSVWriter.NO_ESCAPE_CHARACTER);
48          csvw.writeNext(args);
49          return sw.toString();
50      }
51  
52      @Test
53      public void correctlyParseNullString(){
54          StringWriter sw = new StringWriter();
55          CSVWriter csvw = new CSVWriter(sw,',','\'');
56          csvw.writeNext(null);
57          assertEquals(0, sw.toString().length());
58      }
59  
60      /**
61       * Tests parsing individual lines.
62       *
63       * @throws IOException
64       *             if the reader fails.
65       */
66      @Test
67      public void testParseLine() throws IOException {
68  
69          // test normal case
70          String[] normal = { "a", "b", "c" };
71          String output = invokeWriter(normal);
72          assertEquals("'a','b','c'\n", output);
73  
74          // test quoted commas
75          String[] quoted = { "a", "b,b,b", "c" };
76          output = invokeWriter(quoted);
77          assertEquals("'a','b,b,b','c'\n", output);
78  
79          // test empty elements
80          String[] empty = { , };
81          output = invokeWriter(empty);
82          assertEquals("\n", output);
83  
84          // test multiline quoted
85          String[] multiline = { "This is a \n multiline entry", "so is \n this" };
86          output = invokeWriter(multiline);
87          assertEquals("'This is a \n multiline entry','so is \n this'\n", output);
88  
89      }
90  
91      /**
92       * Tests parsing individual lines.
93       *
94       * @throws IOException
95       *             if the reader fails.
96       */
97      @Test
98      public void testParseLineWithNoEscapeChar() throws IOException {
99  
100         // test normal case
101         String[] normal = { "a", "b", "c" };
102         String output = invokeNoEscapeWriter(normal);
103         assertEquals("'a','b','c'\n", output);
104 
105         // test quoted commas
106         String[] quoted = { "a", "b,b,b", "c" };
107         output = invokeNoEscapeWriter(quoted);
108         assertEquals("'a','b,b,b','c'\n", output);
109 
110         // test empty elements
111         String[] empty = { , };
112         output = invokeNoEscapeWriter(empty);
113         assertEquals("\n", output);
114 
115         // test multiline quoted
116         String[] multiline = { "This is a \n multiline entry", "so is \n this" };
117         output = invokeNoEscapeWriter(multiline);
118         assertEquals("'This is a \n multiline entry','so is \n this'\n", output);
119 
120         // test quoted line
121         String[] quoteLine = { "This is a \" multiline entry", "so is \n this" };
122         output = invokeNoEscapeWriter(quoteLine);
123         assertEquals("'This is a \" multiline entry','so is \n this'\n", output);
124 
125     }
126 
127     /**
128      * Test parsing from to a list.
129      *
130      * @throws IOException
131      *             if the reader fails.
132      */
133     @Test
134     public void testParseAll() throws IOException {
135 
136         List<String[]> allElements = new ArrayList<String[]>();
137         String[] line1 = "Name#Phone#Email".split("#");
138         String[] line2 = "Glen#1234#glen@abcd.com".split("#");
139         String[] line3 = "John#5678#john@efgh.com".split("#");
140         allElements.add(line1);
141         allElements.add(line2);
142         allElements.add(line3);
143 
144         StringWriter sw = new StringWriter();
145         CSVWriter csvw = new CSVWriter(sw);
146         csvw.writeAll(allElements);
147 
148         String result = sw.toString();
149         String[] lines = result.split("\n");
150 
151         assertEquals(3, lines.length);
152 
153     }
154 
155     /**
156      * Tests the option of having omitting quotes in the output stream.
157      * 
158      * @throws IOException if bad things happen
159      */
160     @Test
161     public void testNoQuoteChars() throws IOException {
162     	
163         String[] line = {"Foo","Bar","Baz"};
164         StringWriter sw = new StringWriter();
165         CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);
166         csvw.writeNext(line);
167         String result = sw.toString();
168 
169         assertEquals("Foo,Bar,Baz\n",result);
170     }
171 
172     /**
173      * Tests the option of having omitting quotes in the output stream.
174      *
175      * @throws IOException if bad things happen
176      */
177     @Test
178     public void testNoQuoteCharsAndNoEscapeChars() throws IOException {
179 
180         String[] line = {"Foo","Bar","Baz"};
181         StringWriter sw = new StringWriter();
182         CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
183         csvw.writeNext(line);
184         String result = sw.toString();
185 
186         assertEquals("Foo,Bar,Baz\n",result);
187     }
188 
189     
190     /**
191      * Test null values.
192      *
193      * @throws IOException if bad things happen
194      */
195     @Test
196     public void testNullValues() throws IOException {
197 
198         String[] line = {"Foo",null,"Bar","baz"};
199         StringWriter sw = new StringWriter();
200         CSVWriter csvw = new CSVWriter(sw);
201         csvw.writeNext(line);
202         String result = sw.toString();
203 
204         assertEquals("\"Foo\",,\"Bar\",\"baz\"\n",result);
205 
206     }
207     
208     @Test
209     public void testStreamFlushing() throws IOException {
210 
211         String WRITE_FILE = "myfile.csv";
212 
213         String[] nextLine = new String[]{"aaaa", "bbbb","cccc","dddd"};
214 
215         FileWriter fileWriter = new FileWriter(WRITE_FILE);
216         CSVWriter writer = new CSVWriter(fileWriter);
217 
218         writer.writeNext(nextLine);
219 
220         // If this line is not executed, it is not written in the file.
221         writer.close();
222 
223     }
224     
225     @Test
226     public void testAlternateEscapeChar() {
227         String[] line = {"Foo","bar's"};
228         StringWriter sw = new StringWriter();
229         CSVWriter csvw = new CSVWriter(sw,CSVWriter.DEFAULT_SEPARATOR,CSVWriter.DEFAULT_QUOTE_CHARACTER,'\'');
230         csvw.writeNext(line);
231         assertEquals("\"Foo\",\"bar''s\"\n",sw.toString());
232     }
233     
234     @Test
235     public void testNoQuotingNoEscaping() {
236         String[] line = {"\"Foo\",\"Bar\""};
237         StringWriter sw = new StringWriter();
238         CSVWriter csvw = new CSVWriter(sw,CSVWriter.DEFAULT_SEPARATOR,CSVWriter.NO_QUOTE_CHARACTER,CSVWriter.NO_ESCAPE_CHARACTER);
239         csvw.writeNext(line);
240         assertEquals("\"Foo\",\"Bar\"\n",sw.toString());
241     }
242     
243     @Test
244     public void testNestedQuotes(){
245         String[] data = new String[]{"\"\"", "test"};
246         String oracle = new String("\"\"\"\"\"\",\"test\"\n");
247 
248         CSVWriter writer=null;
249         File tempFile=null;
250         FileWriter fwriter=null;
251 
252         try{
253             tempFile = File.createTempFile("csvWriterTest", ".csv");
254             tempFile.deleteOnExit();
255             fwriter = new FileWriter(tempFile);
256             writer = new CSVWriter(fwriter);
257         }catch(IOException e){
258             fail();
259         }
260 
261         // write the test data:
262         writer.writeNext(data);
263 
264         try{
265             writer.close();
266         }catch(IOException e){
267             fail();
268         }
269 
270         try{
271             // assert that the writer was also closed.
272             fwriter.flush();
273             fail();
274         }catch(IOException e){
275             // we should go through here..
276         }
277 
278         // read the data and compare.
279         FileReader in=null;
280         try{
281             in = new FileReader(tempFile);
282         }catch(FileNotFoundException e){
283             fail();
284         }
285 
286         StringBuilder fileContents = new StringBuilder(CSVWriter.INITIAL_STRING_SIZE);
287         try{
288             int ch;
289             while((ch = in.read()) != -1){
290                 fileContents.append((char)ch);
291             }
292             in.close();
293         }catch(IOException e){
294             fail();
295         }
296 
297         assertTrue(oracle.equals(fileContents.toString()));
298     }
299 
300     @Test
301     public void testAlternateLineFeeds() {
302         String[] line = {"Foo","Bar","baz"};
303         StringWriter sw = new StringWriter();
304         CSVWriter csvw = new CSVWriter(sw, CSVWriter.DEFAULT_SEPARATOR, CSVWriter.DEFAULT_QUOTE_CHARACTER, "\r");
305         csvw.writeNext(line);
306         String result = sw.toString();
307         
308         assertTrue(result.endsWith("\r"));
309     	
310     }
311 
312 }