java类okhttp3.mockwebserver.Dispatcher的实例源码

CallTest.java 文件源码 项目:GitHub 阅读 47 收藏 0 点赞 0 评论 0
@Test public void canceledBeforeResponseReadSignalsOnFailure() throws Exception {
  Request requestA = new Request.Builder().url(server.url("/a")).build();
  final Call call = client.newCall(requestA);
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      call.cancel();
      return new MockResponse().setBody("A");
    }
  });

  call.enqueue(callback);
  assertEquals("/a", server.takeRequest().getPath());

  callback.await(requestA.url()).assertFailure("Canceled", "stream was reset: CANCEL",
      "Socket closed");
}
WebSocketHttpTest.java 文件源码 项目:GitHub 阅读 19 收藏 0 点赞 0 评论 0
/**
 * There's no read timeout when reading the first byte of a new frame. But as soon as we start
 * reading a frame we enable the read timeout. In this test we have the server returning the first
 * byte of a frame but no more frames.
 */
@Test public void readTimeoutAppliesWithinFrames() throws IOException {
  webServer.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      return upgradeResponse(request)
          .setBody(new Buffer().write(ByteString.decodeHex("81"))) // Truncated frame.
          .removeHeader("Content-Length")
          .setSocketPolicy(SocketPolicy.KEEP_OPEN);
    }
  });

  WebSocket webSocket = newWebSocket();
  clientListener.assertOpen();

  clientListener.assertFailure(SocketTimeoutException.class, "timeout");
  assertFalse(webSocket.close(1000, null));
}
Benchmark.java 文件源码 项目:GitHub 阅读 29 收藏 0 点赞 0 评论 0
private MockWebServer startServer() throws IOException {
  Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);
  MockWebServer server = new MockWebServer();

  if (tls) {
    SslClient sslClient = SslClient.localhost();
    server.useHttps(sslClient.socketFactory, false);
    server.setProtocols(protocols);
  }

  final MockResponse response = newResponse();
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      return response;
    }
  });

  server.start();
  return server;
}
CallTest.java 文件源码 项目:GitHub 阅读 31 收藏 0 点赞 0 评论 0
@Test public void canceledBeforeResponseReadSignalsOnFailure() throws Exception {
  Request requestA = new Request.Builder().url(server.url("/a")).build();
  final Call call = client.newCall(requestA);
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      call.cancel();
      return new MockResponse().setBody("A");
    }
  });

  call.enqueue(callback);
  assertEquals("/a", server.takeRequest().getPath());

  callback.await(requestA.url()).assertFailure("Canceled", "stream was reset: CANCEL",
      "Socket closed");
}
WebSocketHttpTest.java 文件源码 项目:GitHub 阅读 23 收藏 0 点赞 0 评论 0
/**
 * There's no read timeout when reading the first byte of a new frame. But as soon as we start
 * reading a frame we enable the read timeout. In this test we have the server returning the first
 * byte of a frame but no more frames.
 */
@Test public void readTimeoutAppliesWithinFrames() throws IOException {
  webServer.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      return upgradeResponse(request)
          .setBody(new Buffer().write(ByteString.decodeHex("81"))) // Truncated frame.
          .removeHeader("Content-Length")
          .setSocketPolicy(SocketPolicy.KEEP_OPEN);
    }
  });

  WebSocket webSocket = newWebSocket();
  clientListener.assertOpen();

  clientListener.assertFailure(SocketTimeoutException.class, "timeout", "Read timed out");
  assertFalse(webSocket.close(1000, null));
}
Benchmark.java 文件源码 项目:GitHub 阅读 25 收藏 0 点赞 0 评论 0
private MockWebServer startServer() throws IOException {
  Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);
  MockWebServer server = new MockWebServer();

  if (tls) {
    SslClient sslClient = SslClient.localhost();
    server.useHttps(sslClient.socketFactory, false);
    server.setProtocols(protocols);
  }

  final MockResponse response = newResponse();
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      return response;
    }
  });

  server.start();
  return server;
}
CallTest.java 文件源码 项目:PriorityOkHttp 阅读 54 收藏 0 点赞 0 评论 0
/**
 * This test puts a request in front of one that is to be canceled, so that it is canceled before
 * I/O takes place.
 */
@Test public void canceledBeforeIOSignalsOnFailure() throws Exception {
  client.dispatcher().setMaxRequests(1); // Force requests to be executed serially.

  Request requestA = new Request.Builder().url(server.url("/a")).build();
  Request requestB = new Request.Builder().url(server.url("/b")).build();
  final Call callA = client.newCall(requestA);
  final Call callB = client.newCall(requestB);

  server.setDispatcher(new Dispatcher() {
    char nextResponse = 'A';

    @Override public MockResponse dispatch(RecordedRequest request) {
      callB.cancel();
      return new MockResponse().setBody(Character.toString(nextResponse++));
    }
  });

  callA.enqueue(callback);
  callB.enqueue(callback);
  assertEquals("/a", server.takeRequest().getPath());

  callback.await(requestA.url()).assertBody("A");
  // At this point we know the callback is ready, and that it will receive a cancel failure.
  callback.await(requestB.url()).assertFailure("Canceled");
}
CallTest.java 文件源码 项目:PriorityOkHttp 阅读 29 收藏 0 点赞 0 评论 0
@Test public void canceledBeforeResponseReadSignalsOnFailure() throws Exception {
  Request requestA = new Request.Builder().url(server.url("/a")).build();
  final Call call = client.newCall(requestA);
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      call.cancel();
      return new MockResponse().setBody("A");
    }
  });

  call.enqueue(callback);
  assertEquals("/a", server.takeRequest().getPath());

  callback.await(requestA.url()).assertFailure("Canceled", "stream was reset: CANCEL",
      "Socket closed");
}
Benchmark.java 文件源码 项目:PriorityOkHttp 阅读 23 收藏 0 点赞 0 评论 0
private MockWebServer startServer() throws IOException {
  Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);
  MockWebServer server = new MockWebServer();

  if (tls) {
    SSLContext sslContext = SslContextBuilder.localhost();
    server.useHttps(sslContext.getSocketFactory(), false);
    server.setProtocols(protocols);
  }

  final MockResponse response = newResponse();
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      return response;
    }
  });

  server.start();
  return server;
}
CommonBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 16 收藏 0 点赞 0 评论 0
/**
 * This test show how to create CallAdapter.Factory without adding a reaction for errors.
 * <br>
 * Test created by Robert Zagorski on 19.10.2016
 */
@Test
public void testCompletes1() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return MockWebServerUtils.getSuccessfulResponse();
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .setLoggingEnabled(true)
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestObserver testObserver = observable.test();
    testObserver.awaitTerminalEvent();
    testObserver.assertComplete();
}
CommonBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 16 收藏 0 点赞 0 评论 0
/**
 * Test shows, that when the server responds with different error
 * {@link retrofit2.HttpException} than
 * {@link com.rzagorski.retrofitrx2errorhandler.backoff.BackoffStrategy backoff strategies} react to
 * ({@link java.net.SocketTimeoutException}) the execution ends immediately.
 * <br>
 * Test created by Robert Zagorski on 19.10.2016
 */
@Test
public void testCompletes2() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            switch (mockWebServer.getRequestCount()) {
                case 1:
                    return new MockResponse().setResponseCode(500);
                case 2:
                    return new MockResponse().setResponseCode(404);
                case 3:
                    return MockWebServerUtils.getSuccessfulResponse();
                default:
                    return new MockResponse().setResponseCode(500);
            }
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Exponential.init()
                    .addThrowable(SocketTimeoutException.class)
                    .setBase(2)
                    .setMaxRetries(3).build())
            .addBackoffStrategy(Simple.init()
                    .addThrowable(SocketTimeoutException.class)
                    .setMaxRetries(3).build())
            .setLoggingEnabled(true)
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    long startTime = System.currentTimeMillis();
    Observable observable = github.repos("square");
    TestObserver testObserver = observable.test();
    testObserver.awaitTerminalEvent();
    long endTime = System.currentTimeMillis();
    System.out.println((endTime - startTime));
    //four SocketTimeoutExceptions and 3 exponential backoff's
    assertTrue((endTime - startTime) <= (1) * MockWebServerUtils.ONE_SEC);
}
SimpleBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 15 收藏 0 点赞 0 评论 0
/**
 * Test demonstrates the simple usage of {@link com.rzagorski.retrofitrx2errorhandler.backoff.strategies.Simple}
 * backoff strategy. The server does not responds (every time {@link java.net.SocketTimeoutException}
 * occurrs). The backoff strategy is executed immediately after each error, so there should be
 * 4 times 10 second timeout.
 * <br>
 * Test created by Robert Zagorski on 19.10.2016
 */
@Test
public void testBackoffError1() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE);
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Simple.init()
                    .addThrowable(SocketTimeoutException.class)
                    .setMaxRetries(3).build())
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    long startTime = System.currentTimeMillis();
    Observable observable = github.repos("square");
    TestObserver testObserver = observable.test();
    testObserver.awaitTerminalEvent();
    long endTime = System.currentTimeMillis();
    System.out.println((endTime - startTime));
    //four SocketTimeoutExceptions
    assertTrue((endTime - startTime) >= 4 * 10 * MockWebServerUtils.ONE_SEC);
}
SimpleBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 16 收藏 0 点赞 0 评论 0
/**
 * Test demonstrates the usage of {@link com.rzagorski.retrofitrx2errorhandler.backoff.strategies.Simple}
 * backoff strategy. The server responds with 500 server error every time. The backoff strategy
 * is executed and after {@link com.rzagorski.retrofitrx2errorhandler.backoff.strategies.Simple.Builder#setMaxRetries(int)}
 * is run out, the appropriate error is passed to client.
 * 4 times 10 second timeout.
 * <br>
 * Test created by Robert Zagorski on 19.10.2016
 */
@Test
public void testBackoffCompletes1() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse().setResponseCode(500);
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Simple.init()
                    .addHttpCode(500)
                    .setMaxRetries(300).build())
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestObserver testObserver = observable.test();
    testObserver.awaitTerminalEvent();
    testObserver.assertError(HttpException.class);
}
SimpleBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 16 收藏 0 点赞 0 评论 0
/**
 * The same as {@link #testBackoffCompletes1()} but with different assertion.
 * Test created by Robert Zagorski on 19.10.2016
 */
@Test
public void testBackoffCompletes2() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse().setResponseCode(500);
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Simple.init()
                    .addHttpCode(500)
                    .setMaxRetries(300).build())
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestObserver testObserver = observable.test();
    testObserver.awaitTerminalEvent();
    assertEquals(1, testObserver.errorCount());
}
ExponentialBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 14 收藏 0 点赞 0 评论 0
@Test
public void testBackoffOneTime1() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            if (mockWebServer.getRequestCount() == 1) {
                return new MockResponse().setResponseCode(500);
            } else if (mockWebServer.getRequestCount() == 2) {
                return MockWebServerUtils.getSuccessfulResponse();
            }
            return new MockResponse().setResponseCode(404);
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Exponential.init()
                    .addThrowable(HttpException.class)
                    .setMaxRetries(3).build())
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestObserver testObserver = observable.test();
    testObserver.awaitTerminalEvent();
    assertEquals(1, testObserver.valueCount());
}
ExponentialBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 16 收藏 0 点赞 0 评论 0
@Test
public void testBackoffTwoTimes() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            if (mockWebServer.getRequestCount() < 3) {
                return new MockResponse().setResponseCode(500);
            } else if (mockWebServer.getRequestCount() == 3) {
                return MockWebServerUtils.getSuccessfulResponse();
            }
            return new MockResponse().setResponseCode(404);
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Exponential.init()
                    .addThrowable(HttpException.class)
                    .setMaxRetries(3).build())
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestObserver testObserver = observable.test();
    testObserver.awaitTerminalEvent();
    assertEquals(1, testObserver.valueCount());
}
ExponentialBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 15 收藏 0 点赞 0 评论 0
@Test
public void testBackoffCompletes() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return MockWebServerUtils.getSuccessfulResponse();
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Exponential.init()
                    .addThrowable(HttpException.class)
                    .setMaxRetries(3).build())
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestObserver testSubscriber = observable.test();
    testSubscriber.awaitTerminalEvent();
    testSubscriber.assertComplete();
}
ExponentialBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 14 收藏 0 点赞 0 评论 0
@Test
public void testBackoffError1() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse().setResponseCode(500);
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Exponential.init()
                    .addThrowable(HttpException.class)
                    .setMaxRetries(3).build())
            .setLoggingEnabled(true)
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestObserver testObserver = observable.test();
    testObserver.awaitTerminalEvent();
    assertEquals(1, testObserver.errorCount());
}
ExponentialBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 18 收藏 0 点赞 0 评论 0
@Test
public void testBackoffError2() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse().setResponseCode(500);
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Exponential.init()
                    .addThrowable(HttpException.class)
                    .setMaxRetries(3).build())
            .setLoggingEnabled(true)
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    long startTime = System.currentTimeMillis();
    Observable observable = github.repos("square");
    TestObserver testObserver = observable.test();
    testObserver.awaitTerminalEvent();
    long endTime = System.currentTimeMillis();
    System.out.println((endTime - startTime));
    assertTrue((endTime - startTime) >= 13 * MockWebServerUtils.ONE_SEC);
}
CommonBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 22 收藏 0 点赞 0 评论 0
/**
 * This test show how to create CallAdapter.Factory without adding a reaction for errors.
 * <br></br>
 * Test created by Robert Zagorski on 19.10.2016
 */
@Test
public void testCompletes1() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return MockWebServerUtils.getSuccessfulResponse();
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .setLoggingEnabled(true)
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestSubscriber testSubscriber = new TestSubscriber();
    observable.subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent();
    testSubscriber.assertCompleted();
}
SimpleBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 16 收藏 0 点赞 0 评论 0
/**
 * Test demonstrates the usage of {@link com.rzagorski.retrofitrxerrorhandler.backoff.strategies.Simple}
 * backoff strategy. The server responds with 500 server error every time. The backoff strategy
 * is executed and after {@link com.rzagorski.retrofitrxerrorhandler.backoff.strategies.Simple.Builder#setMaxRetries(int)}
 * is run out, the appropriate error is passed to client.
 * 4 times 10 second timeout.
 * <br></br>
 * Test created by Robert Zagorski on 19.10.2016
 */
@Test
public void testBackoffCompletes1() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse().setResponseCode(500);
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Simple.init()
                    .addHttpCode(500)
                    .setMaxRetries(300).build())
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestSubscriber testSubscriber = new TestSubscriber();
    observable.subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent();
    testSubscriber.assertError(HttpException.class);
}
SimpleBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 17 收藏 0 点赞 0 评论 0
/**
 * The same as {@link #testBackoffCompletes1()} but with different assertion.
 * Test created by Robert Zagorski on 19.10.2016
 */
@Test
public void testBackoffCompletes2() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse().setResponseCode(500);
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Simple.init()
                    .addHttpCode(500)
                    .setMaxRetries(300).build())
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestSubscriber testSubscriber = new TestSubscriber();
    observable.subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent();
    assertEquals(testSubscriber.getOnErrorEvents().size(), 1);
}
ExponentialBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 15 收藏 0 点赞 0 评论 0
@Test
public void testBackoffCompletes() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return MockWebServerUtils.getSuccessfulResponse();
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Exponential.init()
                    .addThrowable(HttpException.class)
                    .setMaxRetries(3).build())
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestSubscriber testSubscriber = new TestSubscriber();
    observable.subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent();
    testSubscriber.assertCompleted();
}
ExponentialBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 15 收藏 0 点赞 0 评论 0
@Test
public void testBackoffError1() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse().setResponseCode(500);
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Exponential.init()
                    .addThrowable(HttpException.class)
                    .setMaxRetries(3).build())
            .setLoggingEnabled(true)
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    Observable observable = github.repos("square");
    TestSubscriber testSubscriber = new TestSubscriber();
    observable.subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent();
    assertTrue(testSubscriber.getOnErrorEvents().size() == 1);
}
ExponentialBackoffTest.java 文件源码 项目:RetrofitRxErrorHandler 阅读 16 收藏 0 点赞 0 评论 0
@Test
public void testBackoffError2() throws Exception {
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            return new MockResponse().setResponseCode(500);
        }
    });
    RxCallAdapter rxCallAdapter = new RxCallAdapter.Builder()
            .addBackoffStrategy(Exponential.init()
                    .addThrowable(HttpException.class)
                    .setMaxRetries(3).build())
            .setLoggingEnabled(true)
            .build();
    GitHub github = createRetrofitInstance(mockWebServer.url("/").toString(),
            new RxErrorHandingFactory(rxCallAdapter));

    long startTime = System.currentTimeMillis();
    Observable observable = github.repos("square");
    TestSubscriber testSubscriber = new TestSubscriber();
    observable.subscribe(testSubscriber);
    testSubscriber.awaitTerminalEvent();
    long endTime = System.currentTimeMillis();
    System.out.println((endTime - startTime));
    assertTrue((endTime - startTime) >= 13 * MockWebServerUtils.ONE_SEC);
}
CallTest.java 文件源码 项目:Okhttp 阅读 30 收藏 0 点赞 0 评论 0
@Test public void canceledBeforeResponseReadSignalsOnFailure() throws Exception {
  Request requestA = new Request.Builder().url(server.url("/a")).build();
  final Call call = client.newCall(requestA);
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      call.cancel();
      return new MockResponse().setBody("A");
    }
  });

  call.enqueue(callback);
  assertEquals("/a", server.takeRequest().getPath());

  callback.await(requestA.url()).assertFailure("Canceled", "stream was reset: CANCEL",
      "Socket closed");
}
Benchmark.java 文件源码 项目:Okhttp 阅读 21 收藏 0 点赞 0 评论 0
private MockWebServer startServer() throws IOException {
  Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);
  MockWebServer server = new MockWebServer();

  if (tls) {
    SslClient sslClient = SslClient.localhost();
    server.useHttps(sslClient.socketFactory, false);
    server.setProtocols(protocols);
  }

  final MockResponse response = newResponse();
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      return response;
    }
  });

  server.start();
  return server;
}
RoomApiTest.java 文件源码 项目:lazybot 阅读 49 收藏 0 点赞 0 评论 0
@Test
public void sendMessage() throws IOException {
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            final String body = request.getBody().readUtf8();
            receivedNotification = JacksonUtils.deserialize(body, Notification.class);
            return new MockResponse();
        }
    });
    server.start();

    final RoomApiHttp http = getRoomApi(server, (oauthId, oauthSecret) -> getValidOAuthToken());
    http.sendMessage("hello", null);
    assertThat(receivedNotification, is(new Notification("hello", null)));
}
OAuthApiTest.java 文件源码 项目:lazybot 阅读 16 收藏 0 点赞 0 评论 0
@Test
public void requestToken() throws IOException {
    final RequestTokenResponse fakeResponse = new RequestTokenResponse();
    fakeResponse.setAccessToken("token!");
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            final String body = request.getBody().readUtf8();
            assertThat(body, is("grant_type=client_credentials&scope=scope1+scope2"));
            return new MockResponse().setResponseCode(200).setBody(JacksonUtils.serialize(fakeResponse));
        }
    });
    server.start();

    final OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build();
    final HipChatConfig hipChatConfig = new HipChatConfig();
    hipChatConfig.setHipChatApiUrl(server.url("").toString());
    hipChatConfig.setScopes(new HashSet<>(Arrays.asList("scope1", "scope2")));
    final OAuthApiHttp http = new OAuthApiHttp(client, hipChatConfig);
    final RequestTokenResponse response = http.requestToken("id", "secret");

    assertThat(response, is(fakeResponse));
}
Benchmark.java 文件源码 项目:jus 阅读 23 收藏 0 点赞 0 评论 0
private MockWebServer startServer(States.GenericState state) throws IOException {
  Logger.getLogger(MockWebServer.class.getName()).setLevel(Level.WARNING);
  MockWebServer server = new MockWebServer();

  if (state.tls) {
    SslClient sslClient = SslClient.localhost();
    server.useHttps(sslClient.socketFactory, false);
    server.setProtocols(state.protocols);
  }

  final MockResponse response = newResponse(state);
  server.setDispatcher(new Dispatcher() {
    @Override public MockResponse dispatch(RecordedRequest request) {
      return response;
    }
  });

  server.start();
  return server;
}


问题


面经


文章

微信
公众号

扫码关注公众号