1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.commons.csv.issues;
21
22 import static org.junit.jupiter.api.Assertions.assertEquals;
23 import static org.junit.jupiter.api.Assertions.assertTrue;
24
25 import java.io.ByteArrayInputStream;
26 import java.io.ByteArrayOutputStream;
27 import java.io.IOException;
28 import java.io.InputStreamReader;
29 import java.io.OutputStreamWriter;
30 import java.nio.charset.StandardCharsets;
31 import java.util.List;
32
33 import org.apache.commons.csv.CSVFormat;
34 import org.apache.commons.csv.CSVParser;
35 import org.apache.commons.csv.CSVPrinter;
36 import org.apache.commons.csv.CSVRecord;
37 import org.junit.jupiter.api.Test;
38
39 class JiraCsv294Test {
40
41 private static void testInternal(final CSVFormat format, final String expectedSubstring) throws IOException {
42 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
43 try (CSVPrinter printer = new CSVPrinter(new OutputStreamWriter(bos, StandardCharsets.UTF_8), format)) {
44 printer.printRecord("a", "b \"\"", "c");
45 }
46 final byte[] written = bos.toByteArray();
47 final String writtenString = new String(written, StandardCharsets.UTF_8);
48 assertTrue(writtenString.contains(expectedSubstring));
49 try (CSVParser parser = CSVParser.builder().setReader(new InputStreamReader(new ByteArrayInputStream(written), StandardCharsets.UTF_8))
50 .setFormat(format).get()) {
51 final List<CSVRecord> records = parser.getRecords();
52 assertEquals(1, records.size());
53 final CSVRecord record = records.get(0);
54 assertEquals("a", record.get(0));
55 assertEquals("b \"\"", record.get(1));
56 assertEquals("c", record.get(2));
57 }
58 }
59
60 @Test
61 void testDefaultCsvFormatWithBackslashEscapeWorks() throws IOException {
62 testInternal(CSVFormat.Builder.create().setEscape('\\').get(), ",\"b \\\"\\\"\",");
63 }
64
65 @Test
66 void testDefaultCsvFormatWithNullEscapeWorks() throws IOException {
67 testInternal(CSVFormat.Builder.create().setEscape(null).get(), ",\"b \"\"\"\"\",");
68 }
69
70 @Test
71 void testDefaultCsvFormatWithQuoteEscapeWorks() throws IOException {
72
73
74 testInternal(CSVFormat.Builder.create().setEscape('"').get(), ",\"b \"\"\"\"\",");
75 }
76
77 @Test
78 void testDefaultCsvFormatWorks() throws IOException {
79 testInternal(CSVFormat.Builder.create().get(), ",\"b \"\"\"\"\",");
80 }
81 }