1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 package org.eclipse.jgit.util.io;
46
47 import java.io.ByteArrayInputStream;
48 import java.io.ByteArrayOutputStream;
49 import java.io.IOException;
50 import java.io.InputStream;
51 import java.io.OutputStream;
52
53 import org.junit.Assert;
54 import org.junit.Test;
55
56 public class AutoCRLFOutputStreamTest {
57
58 @Test
59 public void test() throws IOException {
60 assertNoCrLf("", "");
61 assertNoCrLf("\r", "\r");
62 assertNoCrLf("\r\n", "\n");
63 assertNoCrLf("\r\n", "\r\n");
64 assertNoCrLf("\r\r", "\r\r");
65 assertNoCrLf("\r\n\r", "\n\r");
66 assertNoCrLf("\r\n\r\r", "\r\n\r\r");
67 assertNoCrLf("\r\n\r\n", "\r\n\r\n");
68 assertNoCrLf("\r\n\r\n\r", "\n\r\n\r");
69 assertNoCrLf("\0\n", "\0\n");
70 }
71
72 @Test
73 public void testBoundary() throws IOException {
74 for (int i = AutoCRLFOutputStream.BUFFER_SIZE - 10; i < AutoCRLFOutputStream.BUFFER_SIZE + 10; i++) {
75 String s1 = Strings.repeat("a", i);
76 assertNoCrLf(s1, s1);
77 String s2 = Strings.repeat("\0", i);
78 assertNoCrLf(s2, s2);
79 }
80 }
81
82 private void assertNoCrLf(String string, String string2) throws IOException {
83 assertNoCrLfHelper(string, string2);
84
85
86 assertNoCrLfHelper("\u00e5" + string, "\u00e5" + string2);
87 assertNoCrLfHelper("\u00e5" + string + "\u00e5", "\u00e5" + string2
88 + "\u00e5");
89 assertNoCrLfHelper(string + "\u00e5", string2 + "\u00e5");
90 }
91
92 private void assertNoCrLfHelper(String expect, String input)
93 throws IOException {
94 byte[] inbytes = input.getBytes();
95 byte[] expectBytes = expect.getBytes();
96 for (int i = -4; i < 5; ++i) {
97 int size = Math.abs(i);
98 byte[] buf = new byte[size];
99 InputStream in = new ByteArrayInputStream(inbytes);
100 ByteArrayOutputStream bos = new ByteArrayOutputStream();
101 OutputStream out = new AutoCRLFOutputStream(bos);
102 if (i > 0) {
103 int n;
104 while ((n = in.read(buf)) >= 0) {
105 out.write(buf, 0, n);
106 }
107 } else if (i < 0) {
108 int n;
109 while ((n = in.read(buf)) >= 0) {
110 byte[] b = new byte[n];
111 System.arraycopy(buf, 0, b, 0, n);
112 out.write(b);
113 }
114 } else {
115 int c;
116 while ((c = in.read()) != -1)
117 out.write(c);
118 }
119 out.flush();
120 in.close();
121 out.close();
122 byte[] actualBytes = bos.toByteArray();
123 Assert.assertEquals("bufsize=" + size, encode(expectBytes),
124 encode(actualBytes));
125 }
126 }
127
128 String encode(byte[] in) {
129 StringBuilder str = new StringBuilder();
130 for (byte b : in) {
131 if (b < 32)
132 str.append(0xFF & b);
133 else {
134 str.append("'");
135 str.append((char) b);
136 str.append("'");
137 }
138 str.append(' ');
139 }
140 return str.toString();
141 }
142
143 }