Path: blob/master/test/jdk/java/io/BufferedReader/Lines.java
41152 views
/*1* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @bug 8003258 802943426* @run testng Lines27*/2829import java.io.BufferedReader;30import java.io.Reader;31import java.io.StringReader;32import java.io.LineNumberReader;33import java.io.IOException;34import java.io.UncheckedIOException;35import java.util.HashMap;36import java.util.Map;37import java.util.ArrayList;38import java.util.Iterator;39import java.util.NoSuchElementException;40import java.util.Spliterator;41import java.util.stream.Stream;42import java.util.concurrent.atomic.AtomicInteger;43import org.testng.annotations.Test;44import static org.testng.Assert.*;4546@Test(groups = "unit")47public class Lines {48private static final Map<String, Integer> cases = new HashMap<>();4950static {51cases.put("", 0);52cases.put("Line 1", 1);53cases.put("Line 1\n", 1);54cases.put("Line 1\n\n\n", 3);55cases.put("Line 1\nLine 2\nLine 3", 3);56cases.put("Line 1\nLine 2\nLine 3\n", 3);57cases.put("Line 1\n\nLine 3\n\nLine5", 5);58}5960/**61* Helper Reader class which generate specified number of lines contents62* with each line will be "<code>Line <line_number></code>".63*64* <p>This class also support to simulate {@link IOException} when read pass65* a specified line number.66*/67private static class MockLineReader extends Reader {68final int line_count;69boolean closed = false;70int line_no = 0;71String line = null;72int pos = 0;73int inject_ioe_after_line;7475MockLineReader(int cnt) {76this(cnt, cnt);77}7879MockLineReader(int cnt, int inject_ioe) {80line_count = cnt;81inject_ioe_after_line = inject_ioe;82}8384public void reset() {85synchronized(lock) {86line = null;87line_no = 0;88pos = 0;89closed = false;90}91}9293public void inject_ioe() {94inject_ioe_after_line = line_no;95}9697public int getLineNumber() {98synchronized(lock) {99return line_no;100}101}102103@Override104public void close() {105closed = true;106}107108@Override109public int read(char[] buf, int off, int len) throws IOException {110synchronized(lock) {111if (closed) {112throw new IOException("Stream is closed.");113}114115if (line == null) {116if (line_count > line_no) {117line_no += 1;118if (line_no > inject_ioe_after_line) {119throw new IOException("Failed to read line " + line_no);120}121line = "Line " + line_no + "\n";122pos = 0;123} else {124return -1; // EOS reached125}126}127128int cnt = line.length() - pos;129assert(cnt != 0);130// try to fill with remaining131if (cnt >= len) {132line.getChars(pos, pos + len, buf, off);133pos += len;134if (cnt == len) {135assert(pos == line.length());136line = null;137}138return len;139} else {140line.getChars(pos, pos + cnt, buf, off);141off += cnt;142len -= cnt;143line = null;144/* hold for next read, so we won't IOE during fill buffer145int more = read(buf, off, len);146return (more == -1) ? cnt : cnt + more;147*/148return cnt;149}150}151}152}153154private static void verify(Map.Entry<String, Integer> e) {155final String data = e.getKey();156final int total_lines = e.getValue();157try (BufferedReader br = new BufferedReader(158new StringReader(data))) {159assertEquals(br.lines()160.mapToInt(l -> 1).reduce(0, (x, y) -> x + y),161total_lines,162data + " should produce " + total_lines + " lines.");163} catch (IOException ioe) {164fail("Should not have any exception.");165}166}167168public void testLinesBasic() {169// Basic test cases170cases.entrySet().stream().forEach(Lines::verify);171// Similar test, also verify MockLineReader is correct172for (int i = 0; i < 10; i++) {173try (BufferedReader br = new BufferedReader(new MockLineReader(i))) {174assertEquals(br.lines()175.peek(l -> assertTrue(l.matches("^Line \\d+$")))176.mapToInt(l -> 1).reduce(0, (x, y) -> x + y),177i,178"MockLineReader(" + i + ") should produce " + i + " lines.");179} catch (IOException ioe) {180fail("Unexpected IOException.");181}182}183}184185public void testUncheckedIOException() throws IOException {186MockLineReader r = new MockLineReader(10, 3);187ArrayList<String> ar = new ArrayList<>();188try (BufferedReader br = new BufferedReader(r)) {189br.lines().limit(3L).forEach(ar::add);190assertEquals(ar.size(), 3, "Should be able to read 3 lines.");191} catch (UncheckedIOException uioe) {192fail("Unexpected UncheckedIOException");193}194r.reset();195try (BufferedReader br = new BufferedReader(r)) {196br.lines().forEach(ar::add);197fail("Should had thrown UncheckedIOException.");198} catch (UncheckedIOException uioe) {199assertEquals(r.getLineNumber(), 4, "should fail to read 4th line");200assertEquals(ar.size(), 6, "3 + 3 lines read");201}202for (int i = 0; i < ar.size(); i++) {203assertEquals(ar.get(i), "Line " + (i % 3 + 1));204}205}206207public void testIterator() throws IOException {208MockLineReader r = new MockLineReader(6);209BufferedReader br = new BufferedReader(r);210String line = br.readLine();211assertEquals(r.getLineNumber(), 1, "Read one line");212Stream<String> s = br.lines();213Iterator<String> it = s.iterator();214// Ensure iterate with only next works215for (int i = 0; i < 5; i++) {216String str = it.next();217assertEquals(str, "Line " + (i + 2), "Addtional five lines");218}219// NoSuchElementException220try {221it.next();222fail("Should have run out of lines.");223} catch (NoSuchElementException nsse) {}224}225226public void testPartialReadAndLineNo() throws IOException {227MockLineReader r = new MockLineReader(5);228LineNumberReader lr = new LineNumberReader(r);229char[] buf = new char[5];230lr.read(buf, 0, 5);231assertEquals(0, lr.getLineNumber(), "LineNumberReader start with line 0");232assertEquals(1, r.getLineNumber(), "MockLineReader start with line 1");233assertEquals(new String(buf), "Line ");234String l1 = lr.readLine();235assertEquals(l1, "1", "Remaining of the first line");236assertEquals(1, lr.getLineNumber(), "Line 1 is read");237assertEquals(1, r.getLineNumber(), "MockLineReader not yet go next line");238lr.read(buf, 0, 4);239assertEquals(1, lr.getLineNumber(), "In the middle of line 2");240assertEquals(new String(buf, 0, 4), "Line");241ArrayList<String> ar = lr.lines()242.peek(l -> assertEquals(lr.getLineNumber(), r.getLineNumber()))243.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);244assertEquals(ar.get(0), " 2", "Remaining in the second line");245for (int i = 1; i < ar.size(); i++) {246assertEquals(ar.get(i), "Line " + (i + 2), "Rest are full lines");247}248}249250public void testInterlacedRead() throws IOException {251MockLineReader r = new MockLineReader(10);252BufferedReader br = new BufferedReader(r);253char[] buf = new char[5];254Stream<String> s = br.lines();255Iterator<String> it = s.iterator();256257br.read(buf);258assertEquals(new String(buf), "Line ");259assertEquals(it.next(), "1");260try {261s.iterator().next();262fail("Should failed on second attempt to get iterator from s");263} catch (IllegalStateException ise) {}264br.read(buf, 0, 2);265assertEquals(new String(buf, 0, 2), "Li");266// Get stream again should continue from where left267// Only read remaining of the line268br.lines().limit(1L).forEach(line -> assertEquals(line, "ne 2"));269br.read(buf, 0, 2);270assertEquals(new String(buf, 0, 2), "Li");271br.read(buf, 0, 2);272assertEquals(new String(buf, 0, 2), "ne");273assertEquals(it.next(), " 3");274// Line 4275br.readLine();276// interator pick277assertEquals(it.next(), "Line 5");278// Another stream instantiated by lines()279AtomicInteger line_no = new AtomicInteger(6);280br.lines().forEach(l -> assertEquals(l, "Line " + line_no.getAndIncrement()));281// Read after EOL282assertFalse(it.hasNext());283}284285public void testCharacteristics() {286try (BufferedReader br = new BufferedReader(287new StringReader(""))) {288Spliterator<String> instance = br.lines().spliterator();289assertTrue(instance.hasCharacteristics(Spliterator.NONNULL));290assertTrue(instance.hasCharacteristics(Spliterator.ORDERED));291} catch (IOException ioe) {292fail("Should not have any exception.");293}294}295}296297298