1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.io.input;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20
21 import java.io.ByteArrayInputStream;
22 import java.io.IOException;
23 import java.nio.charset.StandardCharsets;
24
25 import org.junit.jupiter.api.Test;
26
27 class UnixLineEndingInputStreamTest {
28
29 private String roundtrip(final String msg) throws IOException {
30 return roundtrip(msg, true, 0);
31 }
32
33 private String roundtrip(final String msg, final boolean ensureLineFeedAtEndOfFile, final int minBufferLen) throws IOException {
34 final String string;
35
36 try (ByteArrayInputStream baos = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
37 UnixLineEndingInputStream in = new UnixLineEndingInputStream(baos, ensureLineFeedAtEndOfFile)) {
38
39 final byte[] buf = new byte[minBufferLen + msg.length() * 10];
40 string = new String(buf, 0, in.read(buf), StandardCharsets.UTF_8);
41 }
42
43 try (ByteArrayInputStream baos = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
44 UnixLineEndingInputStream in = new UnixLineEndingInputStream(baos, ensureLineFeedAtEndOfFile)) {
45
46 final byte[] buf = new byte[minBufferLen + msg.length() * 10];
47 assertEquals(string, new String(buf, 0, in.read(buf, 0, buf.length), StandardCharsets.UTF_8));
48 }
49
50 try (ByteArrayInputStream baos = new ByteArrayInputStream(msg.getBytes(StandardCharsets.UTF_8));
51 UnixLineEndingInputStream in = new UnixLineEndingInputStream(baos, ensureLineFeedAtEndOfFile)) {
52
53 final int[] buf = new int[minBufferLen + msg.length() * 10];
54 if (buf.length > 0) {
55 int b;
56 int i = 0;
57 while ((b = in.read()) != -1) {
58 buf[i++] = b;
59 }
60 assertEquals(string, new String(buf, 0, i));
61 }
62 }
63 return string;
64 }
65
66 @Test
67 void testCrAtEnd() throws Exception {
68 assertEquals("a\n", roundtrip("a\r"));
69 }
70
71 @Test
72 void testCrOnlyEnsureAtEof() throws Exception {
73 assertEquals("a\nb\n", roundtrip("a\rb"));
74 }
75
76 @Test
77 void testCrOnlyNotAtEof() throws Exception {
78 assertEquals("a\nb", roundtrip("a\rb", false, 0));
79 }
80
81 @Test
82 void testEmpty() throws Exception {
83 assertEquals("", roundtrip(""));
84 }
85
86 @Test
87 void testInTheMiddleOfTheLine() throws Exception {
88 assertEquals("a\nbc\n", roundtrip("a\r\nbc"));
89 }
90
91 @Test
92 void testMultipleBlankLines() throws Exception {
93 assertEquals("a\n\nbc\n", roundtrip("a\r\n\r\nbc"));
94 }
95
96 @Test
97 void testRetainLineFeed() throws Exception {
98 assertEquals("a\n\n", roundtrip("a\r\n\r\n", false, 0));
99 assertEquals("a", roundtrip("a", false, 0));
100 }
101
102 @Test
103 void testSimpleString() throws Exception {
104 assertEquals("abc\n", roundtrip("abc"));
105 }
106
107 @Test
108 void testTwoLinesAtEnd() throws Exception {
109 assertEquals("a\n\n", roundtrip("a\r\n\r\n"));
110 }
111
112 }