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