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