1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.csv.issues;
19
20 import static org.junit.jupiter.api.Assertions.assertEquals;
21
22 import java.io.IOException;
23 import java.io.StringReader;
24 import java.util.Iterator;
25
26 import org.apache.commons.csv.CSVFormat;
27 import org.apache.commons.csv.CSVParser;
28 import org.apache.commons.csv.CSVRecord;
29 import org.junit.jupiter.api.Test;
30
31
32
33
34 public class JiraCsv265Test {
35
36 @Test
37 public void testCharacterPositionWithComments() throws IOException {
38
39 final String csv = "# Comment1\n"
40 + "Header1,Header2\n"
41 + "# Comment2\n"
42 + "Value1,Value2\n"
43 + "# Comment3\n"
44 + "Value3,Value4\n"
45 + "# Comment4\n";
46 final CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
47 .setCommentMarker('#')
48 .setHeader()
49 .setSkipHeaderRecord(true)
50 .build();
51
52 try (final CSVParser parser = csvFormat.parse(new StringReader(csv))) {
53 final Iterator<CSVRecord> itr = parser.iterator();
54 final CSVRecord record1 = itr.next();
55 assertEquals(csv.indexOf("# Comment2"), record1.getCharacterPosition());
56 final CSVRecord record2 = itr.next();
57 assertEquals(csv.indexOf("# Comment3"), record2.getCharacterPosition());
58 }
59 }
60
61 @Test
62 public void testCharacterPositionWithCommentsSpanningMultipleLines() throws IOException {
63
64 final String csv = "# Comment1\n"
65 + "# Comment2\n"
66 + "Header1,Header2\n"
67 + "# Comment3\n"
68 + "# Comment4\n"
69 + "Value1,Value2\n"
70 + "# Comment5\n"
71 + "# Comment6\n"
72 + "Value3,Value4";
73 final CSVFormat csvFormat = CSVFormat.DEFAULT.builder()
74 .setCommentMarker('#')
75 .setHeader()
76 .setSkipHeaderRecord(true)
77 .build();
78
79 try (final CSVParser parser = csvFormat.parse(new StringReader(csv))) {
80 final Iterator<CSVRecord> itr = parser.iterator();
81 final CSVRecord record1 = itr.next();
82 assertEquals(csv.indexOf("# Comment3"), record1.getCharacterPosition());
83 final CSVRecord record2 = itr.next();
84 assertEquals(csv.indexOf("# Comment5"), record2.getCharacterPosition());
85 }
86 }
87
88 }