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
24 import java.io.IOException;
25 import java.io.StringReader;
26 import java.util.Iterator;
27
28 import org.apache.commons.csv.CSVFormat;
29 import org.apache.commons.csv.CSVParser;
30 import org.apache.commons.csv.CSVRecord;
31 import org.junit.jupiter.api.Test;
32
33
34
35
36 class JiraCsv265Test {
37
38 @Test
39 void testCharacterPositionWithComments() throws IOException {
40
41 final String csv =
42 "# Comment1\n" +
43 "Header1,Header2\n" +
44 "# Comment2\n" +
45 "Value1,Value2\n" +
46 "# Comment3\n" +
47 "Value3,Value4\n" +
48 "# Comment4\n";
49 final CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
50 .setCommentMarker('#')
51 .setHeader()
52 .setSkipHeaderRecord(true)
53 .get();
54
55 try (CSVParser parser = csvFormat.parse(new StringReader(csv))) {
56 final Iterator<CSVRecord> itr = parser.iterator();
57 final CSVRecord record1 = itr.next();
58 assertEquals(csv.indexOf("# Comment2"), record1.getCharacterPosition());
59 final CSVRecord record2 = itr.next();
60 assertEquals(csv.indexOf("# Comment3"), record2.getCharacterPosition());
61 }
62 }
63
64 @Test
65 void testCharacterPositionWithCommentsSpanningMultipleLines() throws IOException {
66
67 final String csv =
68 "# Comment1\n" +
69 "# Comment2\n" +
70 "Header1,Header2\n" +
71 "# Comment3\n" +
72 "# Comment4\n" +
73 "Value1,Value2\n" +
74 "# Comment5\n" +
75 "# Comment6\n" +
76 "Value3,Value4";
77 final CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
78 .setCommentMarker('#')
79 .setHeader()
80 .setSkipHeaderRecord(true)
81 .get();
82
83 try (CSVParser parser = csvFormat.parse(new StringReader(csv))) {
84 final Iterator<CSVRecord> itr = parser.iterator();
85 final CSVRecord record1 = itr.next();
86 assertEquals(csv.indexOf("# Comment3"), record1.getCharacterPosition());
87 final CSVRecord record2 = itr.next();
88 assertEquals(csv.indexOf("# Comment5"), record2.getCharacterPosition());
89 }
90 }
91
92 }