aboutsummaryrefslogtreecommitdiff
path: root/guava-tests/test/com/google/common/io/CharSourceTest.java
blob: 787d744b7e4896fe6f8c11ec604571cea5826ab2 (plain)
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
 * Copyright (C) 2012 The Guava Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.common.io;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.io.TestOption.CLOSE_THROWS;
import static com.google.common.io.TestOption.OPEN_THROWS;
import static com.google.common.io.TestOption.READ_THROWS;
import static com.google.common.io.TestOption.WRITE_THROWS;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.io.Closer.LoggingSuppressor;
import com.google.common.testing.TestLogHandler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.EnumSet;
import java.util.List;
import java.util.stream.Stream;
import junit.framework.TestSuite;

/**
 * Tests for the default implementations of {@code CharSource} methods.
 *
 * @author Colin Decker
 */
public class CharSourceTest extends IoTestCase {

  @AndroidIncompatible // Android doesn't understand suites whose tests lack default constructors.
  public static TestSuite suite() {
    TestSuite suite = new TestSuite();
    for (boolean asByteSource : new boolean[] {false, true}) {
      suite.addTest(
          CharSourceTester.tests(
              "CharSource.wrap[CharSequence]",
              SourceSinkFactories.stringCharSourceFactory(),
              asByteSource));
      suite.addTest(
          CharSourceTester.tests(
              "CharSource.empty[]", SourceSinkFactories.emptyCharSourceFactory(), asByteSource));
    }
    suite.addTestSuite(CharSourceTest.class);
    return suite;
  }

  private static final String STRING = ASCII + I18N;
  private static final String LINES = "foo\nbar\r\nbaz\rsomething";
  private static final ImmutableList<String> SPLIT_LINES =
      ImmutableList.of("foo", "bar", "baz", "something");

  private TestCharSource source;

  @Override
  public void setUp() {
    source = new TestCharSource(STRING);
  }

  public void testOpenBufferedStream() throws IOException {
    BufferedReader reader = source.openBufferedStream();
    assertTrue(source.wasStreamOpened());
    assertFalse(source.wasStreamClosed());

    StringWriter writer = new StringWriter();
    char[] buf = new char[64];
    int read;
    while ((read = reader.read(buf)) != -1) {
      writer.write(buf, 0, read);
    }
    reader.close();
    writer.close();

    assertTrue(source.wasStreamClosed());
    assertEquals(STRING, writer.toString());
  }

  public void testLines() throws IOException {
    source = new TestCharSource(LINES);

    ImmutableList<String> lines;
    try (Stream<String> linesStream = source.lines()) {
      assertTrue(source.wasStreamOpened());
      assertFalse(source.wasStreamClosed());

      lines = linesStream.collect(toImmutableList());
    }

    assertTrue(source.wasStreamClosed());
    assertEquals(SPLIT_LINES, lines);
  }

  public void testCopyTo_appendable() throws IOException {
    StringBuilder builder = new StringBuilder();

    assertEquals(STRING.length(), source.copyTo(builder));
    assertTrue(source.wasStreamOpened() && source.wasStreamClosed());

    assertEquals(STRING, builder.toString());
  }

  public void testCopyTo_charSink() throws IOException {
    TestCharSink sink = new TestCharSink();

    assertFalse(sink.wasStreamOpened() || sink.wasStreamClosed());

    assertEquals(STRING.length(), source.copyTo(sink));
    assertTrue(source.wasStreamOpened() && source.wasStreamClosed());
    assertTrue(sink.wasStreamOpened() && sink.wasStreamClosed());

    assertEquals(STRING, sink.getString());
  }

  public void testRead_toString() throws IOException {
    assertEquals(STRING, source.read());
    assertTrue(source.wasStreamOpened() && source.wasStreamClosed());
  }

  public void testReadFirstLine() throws IOException {
    TestCharSource lines = new TestCharSource(LINES);
    assertEquals("foo", lines.readFirstLine());
    assertTrue(lines.wasStreamOpened() && lines.wasStreamClosed());
  }

  public void testReadLines_toList() throws IOException {
    TestCharSource lines = new TestCharSource(LINES);
    assertEquals(ImmutableList.of("foo", "bar", "baz", "something"), lines.readLines());
    assertTrue(lines.wasStreamOpened() && lines.wasStreamClosed());
  }

  public void testReadLines_withProcessor() throws IOException {
    TestCharSource lines = new TestCharSource(LINES);
    List<String> list =
        lines.readLines(
            new LineProcessor<List<String>>() {
              List<String> list = Lists.newArrayList();

              @Override
              public boolean processLine(String line) throws IOException {
                list.add(line);
                return true;
              }

              @Override
              public List<String> getResult() {
                return list;
              }
            });
    assertEquals(ImmutableList.of("foo", "bar", "baz", "something"), list);
    assertTrue(lines.wasStreamOpened() && lines.wasStreamClosed());
  }

  public void testReadLines_withProcessor_stopsOnFalse() throws IOException {
    TestCharSource lines = new TestCharSource(LINES);
    List<String> list =
        lines.readLines(
            new LineProcessor<List<String>>() {
              List<String> list = Lists.newArrayList();

              @Override
              public boolean processLine(String line) throws IOException {
                list.add(line);
                return false;
              }

              @Override
              public List<String> getResult() {
                return list;
              }
            });
    assertEquals(ImmutableList.of("foo"), list);
    assertTrue(lines.wasStreamOpened() && lines.wasStreamClosed());
  }

  public void testForEachLine() throws IOException {
    source = new TestCharSource(LINES);

    ImmutableList.Builder<String> builder = ImmutableList.builder();
    source.forEachLine(builder::add);

    assertEquals(SPLIT_LINES, builder.build());
    assertTrue(source.wasStreamOpened());
    assertTrue(source.wasStreamClosed());
  }

  public void testCopyToAppendable_doesNotCloseIfWriter() throws IOException {
    TestWriter writer = new TestWriter();
    assertFalse(writer.closed());
    source.copyTo(writer);
    assertFalse(writer.closed());
  }

  public void testClosesOnErrors_copyingToCharSinkThatThrows() {
    for (TestOption option : EnumSet.of(OPEN_THROWS, WRITE_THROWS, CLOSE_THROWS)) {
      TestCharSource okSource = new TestCharSource(STRING);
      try {
        okSource.copyTo(new TestCharSink(option));
        fail();
      } catch (IOException expected) {
      }
      // ensure reader was closed IF it was opened (depends on implementation whether or not it's
      // opened at all if sink.newWriter() throws).
      assertTrue(
          "stream not closed when copying to sink with option: " + option,
          !okSource.wasStreamOpened() || okSource.wasStreamClosed());
    }
  }

  public void testClosesOnErrors_whenReadThrows() {
    TestCharSource failSource = new TestCharSource(STRING, READ_THROWS);
    try {
      failSource.copyTo(new TestCharSink());
      fail();
    } catch (IOException expected) {
    }
    assertTrue(failSource.wasStreamClosed());
  }

  public void testClosesOnErrors_copyingToWriterThatThrows() {
    TestCharSource okSource = new TestCharSource(STRING);
    try {
      okSource.copyTo(new TestWriter(WRITE_THROWS));
      fail();
    } catch (IOException expected) {
    }
    assertTrue(okSource.wasStreamClosed());
  }

  public void testConcat() throws IOException {
    CharSource c1 = CharSource.wrap("abc");
    CharSource c2 = CharSource.wrap("");
    CharSource c3 = CharSource.wrap("de");

    String expected = "abcde";

    assertEquals(expected, CharSource.concat(ImmutableList.of(c1, c2, c3)).read());
    assertEquals(expected, CharSource.concat(c1, c2, c3).read());
    assertEquals(expected, CharSource.concat(ImmutableList.of(c1, c2, c3).iterator()).read());
    assertFalse(CharSource.concat(c1, c2, c3).isEmpty());

    CharSource emptyConcat = CharSource.concat(CharSource.empty(), CharSource.empty());
    assertTrue(emptyConcat.isEmpty());
  }

  public void testConcat_infiniteIterable() throws IOException {
    CharSource source = CharSource.wrap("abcd");
    Iterable<CharSource> cycle = Iterables.cycle(ImmutableList.of(source));
    CharSource concatenated = CharSource.concat(cycle);

    String expected = "abcdabcd";

    // read the first 8 chars manually, since there's no equivalent to ByteSource.slice
    // TODO(cgdecker): Add CharSource.slice?
    StringBuilder builder = new StringBuilder();
    Reader reader = concatenated.openStream(); // no need to worry about closing
    for (int i = 0; i < 8; i++) {
      builder.append((char) reader.read());
    }
    assertEquals(expected, builder.toString());
  }

  static final CharSource BROKEN_READ_SOURCE = new TestCharSource("ABC", READ_THROWS);
  static final CharSource BROKEN_CLOSE_SOURCE = new TestCharSource("ABC", CLOSE_THROWS);
  static final CharSource BROKEN_OPEN_SOURCE = new TestCharSource("ABC", OPEN_THROWS);
  static final CharSink BROKEN_WRITE_SINK = new TestCharSink(WRITE_THROWS);
  static final CharSink BROKEN_CLOSE_SINK = new TestCharSink(CLOSE_THROWS);
  static final CharSink BROKEN_OPEN_SINK = new TestCharSink(OPEN_THROWS);

  private static final ImmutableSet<CharSource> BROKEN_SOURCES =
      ImmutableSet.of(BROKEN_CLOSE_SOURCE, BROKEN_OPEN_SOURCE, BROKEN_READ_SOURCE);
  private static final ImmutableSet<CharSink> BROKEN_SINKS =
      ImmutableSet.of(BROKEN_CLOSE_SINK, BROKEN_OPEN_SINK, BROKEN_WRITE_SINK);

  public void testCopyExceptions() {
    if (Closer.create().suppressor instanceof LoggingSuppressor) {
      // test that exceptions are logged

      TestLogHandler logHandler = new TestLogHandler();
      Closeables.logger.addHandler(logHandler);
      try {
        for (CharSource in : BROKEN_SOURCES) {
          runFailureTest(in, newNormalCharSink());
          assertTrue(logHandler.getStoredLogRecords().isEmpty());

          runFailureTest(in, BROKEN_CLOSE_SINK);
          assertEquals((in == BROKEN_OPEN_SOURCE) ? 0 : 1, getAndResetRecords(logHandler));
        }

        for (CharSink out : BROKEN_SINKS) {
          runFailureTest(newNormalCharSource(), out);
          assertTrue(logHandler.getStoredLogRecords().isEmpty());

          runFailureTest(BROKEN_CLOSE_SOURCE, out);
          assertEquals(1, getAndResetRecords(logHandler));
        }

        for (CharSource in : BROKEN_SOURCES) {
          for (CharSink out : BROKEN_SINKS) {
            runFailureTest(in, out);
            assertTrue(getAndResetRecords(logHandler) <= 1);
          }
        }
      } finally {
        Closeables.logger.removeHandler(logHandler);
      }
    } else {
      // test that exceptions are suppressed

      for (CharSource in : BROKEN_SOURCES) {
        int suppressed = runSuppressionFailureTest(in, newNormalCharSink());
        assertEquals(0, suppressed);

        suppressed = runSuppressionFailureTest(in, BROKEN_CLOSE_SINK);
        assertEquals((in == BROKEN_OPEN_SOURCE) ? 0 : 1, suppressed);
      }

      for (CharSink out : BROKEN_SINKS) {
        int suppressed = runSuppressionFailureTest(newNormalCharSource(), out);
        assertEquals(0, suppressed);

        suppressed = runSuppressionFailureTest(BROKEN_CLOSE_SOURCE, out);
        assertEquals(1, suppressed);
      }

      for (CharSource in : BROKEN_SOURCES) {
        for (CharSink out : BROKEN_SINKS) {
          int suppressed = runSuppressionFailureTest(in, out);
          assertTrue(suppressed <= 1);
        }
      }
    }
  }

  private static int getAndResetRecords(TestLogHandler logHandler) {
    int records = logHandler.getStoredLogRecords().size();
    logHandler.clear();
    return records;
  }

  private static void runFailureTest(CharSource in, CharSink out) {
    try {
      in.copyTo(out);
      fail();
    } catch (IOException expected) {
    }
  }

  /** @return the number of exceptions that were suppressed on the expected thrown exception */
  private static int runSuppressionFailureTest(CharSource in, CharSink out) {
    try {
      in.copyTo(out);
      fail();
    } catch (IOException expected) {
      return CloserTest.getSuppressed(expected).length;
    }
    throw new AssertionError(); // can't happen
  }

  private static CharSource newNormalCharSource() {
    return CharSource.wrap("ABC");
  }

  private static CharSink newNormalCharSink() {
    return new CharSink() {
      @Override
      public Writer openStream() {
        return new StringWriter();
      }
    };
  }
}