]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.util/ext/test/org/argeo/util/CsvWriterTest.java
Add Eclipse text components to RCP.
[lgpl/argeo-commons.git] / org.argeo.util / ext / test / org / argeo / util / CsvWriterTest.java
1 /*
2 * Copyright (C) 2007-2012 Argeo GmbH
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package org.argeo.util;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.ByteArrayOutputStream;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.List;
23
24 /** {@link CsvWriter} tests. */
25 public class CsvWriterTest {
26 public void testWrite() throws Exception {
27 ByteArrayOutputStream out = new ByteArrayOutputStream();
28 final CsvWriter csvWriter = new CsvWriter(out);
29
30 String[] header = { "Header1", "Header 2", "Header,3", "Header\n4", "Header\"5\"" };
31 String[] line1 = { "Value1", "Value 2", "Value,3", "Value\n4", "Value\"5\"" };
32 csvWriter.writeLine(Arrays.asList(header));
33 csvWriter.writeLine(Arrays.asList(line1));
34
35 String reference = "Header1,Header 2,\"Header,3\",\"Header\n4\",\"Header\"\"5\"\"\"\n"
36 + "Value1,Value 2,\"Value,3\",\"Value\n4\",\"Value\"\"5\"\"\"\n";
37 String written = new String(out.toByteArray());
38 assert reference.equals(written);
39 out.close();
40 System.out.println(written);
41
42 final List<String> allTokens = new ArrayList<String>();
43 CsvParser csvParser = new CsvParser() {
44 protected void processLine(Integer lineNumber, List<String> header, List<String> tokens) {
45 if (lineNumber == 2)
46 allTokens.addAll(header);
47 allTokens.addAll(tokens);
48 }
49 };
50 ByteArrayInputStream in = new ByteArrayInputStream(written.getBytes());
51 csvParser.parse(in);
52 in.close();
53 List<String> allTokensRef = new ArrayList<String>();
54 allTokensRef.addAll(Arrays.asList(header));
55 allTokensRef.addAll(Arrays.asList(line1));
56
57 assert allTokensRef.size() == allTokens.size();
58 for (int i = 0; i < allTokensRef.size(); i++)
59 assert allTokensRef.get(i).equals(allTokens.get(i));
60 }
61
62 }