View Javadoc
1   /*
2    * Copyright (C) 2020, Thomas Wolf <thomas.wolf@paranor.ch> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.util.io;
12  
13  import static java.nio.charset.StandardCharsets.UTF_8;
14  import static org.junit.Assert.assertArrayEquals;
15  
16  import java.io.ByteArrayOutputStream;
17  import java.io.IOException;
18  import java.io.OutputStream;
19  
20  import org.junit.Test;
21  
22  public class AutoLFOutputStreamTest {
23  
24  	@Test
25  	public void testLF() throws IOException {
26  		final byte[] bytes = asBytes("1\n2\n3");
27  		test(bytes, bytes, false);
28  	}
29  
30  	@Test
31  	public void testCR() throws IOException {
32  		final byte[] bytes = asBytes("1\r2\r3");
33  		test(bytes, bytes, false);
34  	}
35  
36  	@Test
37  	public void testCRLFNoDetect() throws IOException {
38  		test(asBytes("1\r\n2\r\n3"), asBytes("1\n2\n3"), false);
39  	}
40  
41  	@Test
42  	public void testLFCR() throws IOException {
43  		final byte[] bytes = asBytes("1\n\r2\n\r3");
44  		test(bytes, bytes, false);
45  	}
46  
47  	@Test
48  	public void testEmpty() throws IOException {
49  		final byte[] bytes = asBytes("");
50  		test(bytes, bytes, false);
51  	}
52  
53  	@Test
54  	public void testBinaryDetect() throws IOException {
55  		final byte[] bytes = asBytes("1\r\n2\r\n3\0");
56  		test(bytes, bytes, true);
57  	}
58  
59  	@Test
60  	public void testBinaryDontDetect() throws IOException {
61  		test(asBytes("1\r\n2\r\n3\0"), asBytes("1\n2\n3\0"), false);
62  	}
63  
64  	@Test
65  	public void testCrLfDetect() throws IOException {
66  		byte[] bytes = asBytes("1\r\n2\n3\r\n\r");
67  		test(bytes, bytes, true);
68  	}
69  
70  	private static void test(byte[] input, byte[] expected,
71  			boolean detectBinary) throws IOException {
72  		try (ByteArrayOutputStream result = new ByteArrayOutputStream();
73  				OutputStream out = new AutoLFOutputStream(result,
74  						detectBinary)) {
75  			out.write(input);
76  			out.close();
77  			assertArrayEquals(expected, result.toByteArray());
78  		}
79  	}
80  
81  	private static byte[] asBytes(String in) {
82  		return in.getBytes(UTF_8);
83  	}
84  }