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.IOException;
19import java.util.ArrayList;
20import java.util.Arrays;
21import java.util.LinkedHashMap;
22import java.util.List;
23import java.util.Map;
24
25import static org.junit.Assert.assertEquals;
26import static org.junit.Assert.assertTrue;
27
28/** A scriptable sink. Like Mockito, but worse and requiring less configuration. */
29class MockSink implements Sink {
30  private final List<String> log = new ArrayList<String>();
31  private final Map<Integer, IOException> callThrows = new LinkedHashMap<Integer, IOException>();
32
33  public void assertLog(String... messages) {
34    assertEquals(Arrays.asList(messages), log);
35  }
36
37  public void assertLogContains(String message) {
38    assertTrue(log.contains(message));
39  }
40
41  public void scheduleThrow(int call, IOException e) {
42    callThrows.put(call, e);
43  }
44
45  private void throwIfScheduled() throws IOException {
46    IOException exception = callThrows.get(log.size() - 1);
47    if (exception != null) throw exception;
48  }
49
50  @Override public void write(OkBuffer source, long byteCount) throws IOException {
51    log.add("write(" + source + ", " + byteCount + ")");
52    source.skip(byteCount);
53    throwIfScheduled();
54  }
55
56  @Override public void flush() throws IOException {
57    log.add("flush()");
58    throwIfScheduled();
59  }
60
61  @Override public Sink deadline(Deadline deadline) {
62    log.add("deadline()");
63    return this;
64  }
65
66  @Override public void close() throws IOException {
67    log.add("close()");
68    throwIfScheduled();
69  }
70}
71