1 /* 2 * Copyright (C) 2013 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 com.squareup.okhttp; 17 18 import java.io.IOException; 19 import java.util.ArrayList; 20 import java.util.Iterator; 21 import java.util.List; 22 import java.util.concurrent.TimeUnit; 23 24 /** 25 * Records received HTTP responses so they can be later retrieved by tests. 26 */ 27 public class RecordingCallback implements Callback { 28 public static final long TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(10); 29 30 private final List<RecordedResponse> responses = new ArrayList<>(); 31 onFailure(Request request, IOException e)32 @Override public synchronized void onFailure(Request request, IOException e) { 33 responses.add(new RecordedResponse(request, null, null, null, e)); 34 notifyAll(); 35 } 36 onResponse(Response response)37 @Override public synchronized void onResponse(Response response) throws IOException { 38 String body = response.body().string(); 39 responses.add(new RecordedResponse(response.request(), response, null, body, null)); 40 notifyAll(); 41 } 42 43 /** 44 * Returns the recorded response triggered by {@code request}. Throws if the 45 * response isn't enqueued before the timeout. 46 */ await(HttpUrl url)47 public synchronized RecordedResponse await(HttpUrl url) throws Exception { 48 long timeoutMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) + TIMEOUT_MILLIS; 49 while (true) { 50 for (Iterator<RecordedResponse> i = responses.iterator(); i.hasNext(); ) { 51 RecordedResponse recordedResponse = i.next(); 52 if (recordedResponse.request.httpUrl().equals(url)) { 53 i.remove(); 54 return recordedResponse; 55 } 56 } 57 58 long nowMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime()); 59 if (nowMillis >= timeoutMillis) break; 60 wait(timeoutMillis - nowMillis); 61 } 62 63 throw new AssertionError("Timed out waiting for response to " + url); 64 } 65 assertNoResponse(HttpUrl url)66 public synchronized void assertNoResponse(HttpUrl url) throws Exception { 67 for (RecordedResponse recordedResponse : responses) { 68 if (recordedResponse.request.httpUrl().equals(url)) { 69 throw new AssertionError("Expected no response for " + url); 70 } 71 } 72 } 73 } 74