1/*
2 * Copyright (C) 2014 Square, Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package okio;
17
18import java.io.ByteArrayInputStream;
19import java.io.ByteArrayOutputStream;
20import java.io.InputStream;
21import java.util.Arrays;
22import org.junit.Test;
23
24import static okio.Util.UTF_8;
25import static org.junit.Assert.assertEquals;
26import static org.junit.Assert.fail;
27
28public final class OkioTest {
29  @Test public void sinkFromOutputStream() throws Exception {
30    OkBuffer data = new OkBuffer();
31    data.writeUtf8("a");
32    data.writeUtf8(repeat('b', 9998));
33    data.writeUtf8("c");
34
35    ByteArrayOutputStream out = new ByteArrayOutputStream();
36    Sink sink = Okio.sink(out);
37    sink.write(data, 3);
38    assertEquals("abb", out.toString("UTF-8"));
39    sink.write(data, data.size());
40    assertEquals("a" + repeat('b', 9998) + "c", out.toString("UTF-8"));
41  }
42
43  @Test public void sourceFromInputStream() throws Exception {
44    InputStream in = new ByteArrayInputStream(
45        ("a" + repeat('b', Segment.SIZE * 2) + "c").getBytes(UTF_8));
46
47    // Source: ab...bc
48    Source source = Okio.source(in);
49    OkBuffer sink = new OkBuffer();
50
51    // Source: b...bc. Sink: abb.
52    assertEquals(3, source.read(sink, 3));
53    assertEquals("abb", sink.readUtf8(3));
54
55    // Source: b...bc. Sink: b...b.
56    assertEquals(Segment.SIZE, source.read(sink, 20000));
57    assertEquals(repeat('b', Segment.SIZE), sink.readUtf8(sink.size()));
58
59    // Source: b...bc. Sink: b...bc.
60    assertEquals(Segment.SIZE - 1, source.read(sink, 20000));
61    assertEquals(repeat('b', Segment.SIZE - 2) + "c", sink.readUtf8(sink.size()));
62
63    // Source and sink are empty.
64    assertEquals(-1, source.read(sink, 1));
65  }
66
67  @Test public void sourceFromInputStreamBounds() throws Exception {
68    Source source = Okio.source(new ByteArrayInputStream(new byte[100]));
69    try {
70      source.read(new OkBuffer(), -1);
71      fail();
72    } catch (IllegalArgumentException expected) {
73    }
74  }
75
76  private String repeat(char c, int count) {
77    char[] array = new char[count];
78    Arrays.fill(array, c);
79    return new String(array);
80  }
81}
82