View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.io.input;
18  
19  import static org.junit.jupiter.api.Assertions.assertEquals;
20  
21  import java.io.IOException;
22  import java.nio.charset.StandardCharsets;
23  
24  import org.junit.jupiter.api.Test;
25  
26  public class WindowsLineEndingInputStreamTest {
27      private String roundtrip(final String msg) throws IOException {
28          return roundtrip(msg, true);
29      }
30  
31      private String roundtrip(final String msg, final boolean ensure) throws IOException {
32          try (WindowsLineEndingInputStream lf = new WindowsLineEndingInputStream(
33                  CharSequenceInputStream.builder().setCharSequence(msg).setCharset(StandardCharsets.UTF_8).get(), ensure)) {
34              final byte[] buf = new byte[100];
35              final int read = lf.read(buf);
36              return new String(buf, 0, read, StandardCharsets.UTF_8);
37          }
38      }
39  
40      @Test
41      public void testInTheMiddleOfTheLine() throws Exception {
42          assertEquals("a\r\nbc\r\n", roundtrip("a\r\nbc"));
43      }
44  
45      @Test
46      public void testLinuxLineFeeds() throws Exception {
47          final String roundtrip = roundtrip("ab\nc", false);
48          assertEquals("ab\r\nc", roundtrip);
49      }
50  
51      @Test
52      public void testMalformed() throws Exception {
53          assertEquals("a\rbc", roundtrip("a\rbc", false));
54      }
55  
56      @Test
57      public void testMultipleBlankLines() throws Exception {
58          assertEquals("a\r\n\r\nbc\r\n", roundtrip("a\r\n\r\nbc"));
59      }
60  
61      @Test
62      public void testRetainLineFeed() throws Exception {
63          assertEquals("a\r\n\r\n", roundtrip("a\r\n\r\n", false));
64          assertEquals("a", roundtrip("a", false));
65      }
66  
67      @Test
68      public void testSimpleString() throws Exception {
69          assertEquals("abc\r\n", roundtrip("abc"));
70      }
71  
72      @Test
73      public void testTwoLinesAtEnd() throws Exception {
74          assertEquals("a\r\n\r\n", roundtrip("a\r\n\r\n"));
75      }
76  }