Java Code Examples for okhttp3.mockwebserver.MockResponse

The following are top voted examples for showing how to use okhttp3.mockwebserver.MockResponse. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: retrofit-xmlrpc   File: MockedTest.java   Source Code and License 7 votes vote down vote up
@Test
public void listMethods() throws IOException, InterruptedException {
    server.enqueue(new MockResponse()
            .addHeader("Content-Type", "application/xml; charset=UTF-8")
            .setBody("<?xml version=\"1.0\"?>\n" +
                    "<methodResponse>\n" +
                    "  <params>\n" +
                    "    <param>\n" +
                    "        <value>" +
                    "            <array>" +
                    "                <data>" +
                    "                    <value><string>system.listMethods</string></value>\n" +
                    "                    <value><string>multiply</string></value>\n" +
                    "                </data>" +
                    "            </array>" +
                    "        </value>" +
                    "    </param>\n" +
                    "  </params>\n" +
                    "</methodResponse>"));

    TestService service = retrofit.create(TestService.class);
    String[] execute = service.listMethods(NOTHING).execute().body();
    server.takeRequest();
    assertThat(execute).isNotEmpty();
}
 
Example 2
Project: GitHub   File: CacheTest.java   Source Code and License 6 votes vote down vote up
private void temporaryRedirectCachedWithCachingHeader(
    int responseCode, String headerName, String headerValue) throws Exception {
  server.enqueue(new MockResponse()
      .setResponseCode(responseCode)
      .addHeader(headerName, headerValue)
      .addHeader("Location", "/a"));
  server.enqueue(new MockResponse()
      .addHeader(headerName, headerValue)
      .setBody("a"));
  server.enqueue(new MockResponse()
      .setBody("b"));
  server.enqueue(new MockResponse()
      .setBody("c"));

  HttpUrl url = server.url("/");
  assertEquals("a", get(url).body().string());
  assertEquals("a", get(url).body().string());
}
 
Example 3
Project: GitHub   File: CacheTest.java   Source Code and License 6 votes vote down vote up
@Test public void varyMultipleFieldValuesWithMatch() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Cache-Control: max-age=60")
      .addHeader("Vary: Accept-Language")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  HttpUrl url = server.url("/");
  Request request1 = new Request.Builder()
      .url(url)
      .addHeader("Accept-Language", "fr-CA, fr-FR")
      .addHeader("Accept-Language", "en-US")
      .build();
  Response response1 = client.newCall(request1).execute();
  assertEquals("A", response1.body().string());

  Request request2 = new Request.Builder()
      .url(url)
      .addHeader("Accept-Language", "fr-CA, fr-FR")
      .addHeader("Accept-Language", "en-US")
      .build();
  Response response2 = client.newCall(request2).execute();
  assertEquals("A", response2.body().string());
}
 
Example 4
Project: GitHub   File: FlowableThrowingTest.java   Source Code and License 6 votes vote down vote up
@Test public void bodyThrowingInOnCompleteDeliveredToPlugin() {
  server.enqueue(new MockResponse());

  final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
  RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override public void accept(Throwable throwable) throws Exception {
      if (!throwableRef.compareAndSet(null, throwable)) {
        throw Exceptions.propagate(throwable);
      }
    }
  });

  RecordingSubscriber<String> subscriber = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.body().subscribe(new ForwardingSubscriber<String>(subscriber) {
    @Override public void onComplete() {
      throw e;
    }
  });

  subscriber.assertAnyValue();
  assertThat(throwableRef.get()).isSameAs(e);

}
 
Example 5
Project: GitHub   File: URLConnectionTest.java   Source Code and License 6 votes vote down vote up
@Test public void connectViaHttpsWithSSLFallbackFailuresRecorded() throws Exception {
  server.useHttps(sslClient.socketFactory, false);
  server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE));
  server.enqueue(new MockResponse().setSocketPolicy(FAIL_HANDSHAKE));

  urlFactory.setClient(urlFactory.client().newBuilder()
      .dns(new SingleInetAddressDns())
      .connectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS, ConnectionSpec.COMPATIBLE_TLS))
      .hostnameVerifier(new RecordingHostnameVerifier())
      .sslSocketFactory(suppressTlsFallbackClientSocketFactory(), sslClient.trustManager)
      .build());
  connection = urlFactory.open(server.url("/foo").url());

  try {
    connection.getResponseCode();
    fail();
  } catch (IOException expected) {
    assertEquals(1, expected.getSuppressed().length);
  }
}
 
Example 6
Project: GitHub   File: CallTest.java   Source Code and License 6 votes vote down vote up
@Test public void get_Async() throws Exception {
  server.enqueue(new MockResponse()
      .setBody("abc")
      .addHeader("Content-Type: text/plain"));

  Request request = new Request.Builder()
      .url(server.url("/"))
      .header("User-Agent", "AsyncApiTest")
      .build();
  client.newCall(request).enqueue(callback);

  callback.await(request.url())
      .assertCode(200)
      .assertHeader("Content-Type", "text/plain")
      .assertBody("abc");

  assertEquals("AsyncApiTest", server.takeRequest().getHeader("User-Agent"));
}
 
Example 7
Project: XXXX   File: FeignTest.java   Source Code and License 6 votes vote down vote up
/**
 * The type of a parameter value may not be the desired type to encode as. Prefer the interface
 * type.
 */
@Test
public void bodyTypeCorrespondsWithParameterType() throws Exception {
  server.enqueue(new MockResponse().setBody("foo"));

  final AtomicReference<Type> encodedType = new AtomicReference<Type>();
  TestInterface api = new TestInterfaceBuilder()
      .encoder(new Encoder.Default() {
        @Override
        public void encode(Object object, Type bodyType, RequestTemplate template) {
          encodedType.set(bodyType);
        }
      })
      .target("http://localhost:" + server.getPort());

  api.body(Arrays.asList("netflix", "denominator", "password"));

  server.takeRequest();

  assertThat(encodedType.get()).isEqualTo(new TypeToken<List<String>>() {
  }.getType());
}
 
Example 8
Project: GitHub   File: URLConnectionTest.java   Source Code and License 6 votes vote down vote up
@Test public void doesNotAttemptAuthorization21Times() throws Exception {
  for (int i = 0; i < 21; i++) {
    server.enqueue(new MockResponse().setResponseCode(401));
  }

  String credential = Credentials.basic("jesse", "peanutbutter");
  urlFactory.setClient(urlFactory.client().newBuilder()
      .authenticator(new RecordingOkAuthenticator(credential))
      .build());

  connection = urlFactory.open(server.url("/").url());
  try {
    connection.getInputStream();
    fail();
  } catch (ProtocolException expected) {
    assertEquals(401, connection.getResponseCode());
    assertEquals("Too many follow-up requests: 21", expected.getMessage());
  }
}
 
Example 9
Project: GitHub   File: MaybeThrowingTest.java   Source Code and License 6 votes vote down vote up
@Test public void responseThrowingInOnSuccessDeliveredToPlugin() {
  server.enqueue(new MockResponse());

  final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
  RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override public void accept(Throwable throwable) throws Exception {
      if (!throwableRef.compareAndSet(null, throwable)) {
        throw Exceptions.propagate(throwable);
      }
    }
  });

  RecordingMaybeObserver<Response<String>> observer = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.response().subscribe(new ForwardingObserver<Response<String>>(observer) {
    @Override public void onSuccess(Response<String> value) {
      throw e;
    }
  });

  assertThat(throwableRef.get()).isSameAs(e);
}
 
Example 10
Project: GitHub   File: MaybeThrowingTest.java   Source Code and License 6 votes vote down vote up
@Test public void responseThrowingInOnSuccessDeliveredToPlugin() {
  server.enqueue(new MockResponse());

  final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
  RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
    @Override public void accept(Throwable throwable) throws Exception {
      if (!throwableRef.compareAndSet(null, throwable)) {
        throw Exceptions.propagate(throwable);
      }
    }
  });

  RecordingMaybeObserver<Response<String>> observer = subscriberRule.create();
  final RuntimeException e = new RuntimeException();
  service.response().subscribe(new ForwardingObserver<Response<String>>(observer) {
    @Override public void onSuccess(Response<String> value) {
      throw e;
    }
  });

  assertThat(throwableRef.get()).isSameAs(e);
}
 
Example 11
Project: GitHub   File: HttpLoggingInterceptorTest.java   Source Code and License 6 votes vote down vote up
@Test public void basicPost() throws IOException {
  setLevel(Level.BASIC);

  server.enqueue(new MockResponse());
  client.newCall(request().post(RequestBody.create(PLAIN, "Hi?")).build()).execute();

  applicationLogs
      .assertLogEqual("--> POST " + url + " (3-byte body)")
      .assertLogMatch("<-- 200 OK " + url + " \\(\\d+ms, 0-byte body\\)")
      .assertNoMoreLogs();

  networkLogs
      .assertLogEqual("--> POST " + url + " http/1.1 (3-byte body)")
      .assertLogMatch("<-- 200 OK " + url + " \\(\\d+ms, 0-byte body\\)")
      .assertNoMoreLogs();
}
 
Example 12
Project: GitHub   File: CacheTest.java   Source Code and License 6 votes vote down vote up
@Test public void requestMaxStaleNotHonoredWithMustRevalidate() throws IOException {
  server.enqueue(new MockResponse()
      .setBody("A")
      .addHeader("Cache-Control: max-age=120, must-revalidate")
      .addHeader("Date: " + formatDate(-4, TimeUnit.MINUTES)));
  server.enqueue(new MockResponse()
      .setBody("B"));

  assertEquals("A", get(server.url("/")).body().string());

  Request request = new Request.Builder()
      .url(server.url("/"))
      .header("Cache-Control", "max-stale=180")
      .build();
  Response response = client.newCall(request).execute();
  assertEquals("B", response.body().string());
}
 
Example 13
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 6 votes vote down vote up
@Test public void secureResponseCaching() throws IOException {
  assumeFalse(getPlatform().equals("jdk9"));

  server.useHttps(sslClient.socketFactory, false);
  server.enqueue(new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
      .setBody("ABC"));

  HttpsURLConnection c1 = (HttpsURLConnection) openConnection(server.url("/").url());
  c1.setSSLSocketFactory(sslClient.socketFactory);
  c1.setHostnameVerifier(hostnameVerifier);
  assertEquals("ABC", readAscii(c1));

  // OpenJDK 6 fails on this line, complaining that the connection isn't open yet
  String suite = c1.getCipherSuite();
  List<Certificate> localCerts = toListOrNull(c1.getLocalCertificates());
  List<Certificate> serverCerts = toListOrNull(c1.getServerCertificates());
  Principal peerPrincipal = c1.getPeerPrincipal();
  Principal localPrincipal = c1.getLocalPrincipal();

  HttpsURLConnection c2 = (HttpsURLConnection) openConnection(server.url("/").url()); // cached!
  c2.setSSLSocketFactory(sslClient.socketFactory);
  c2.setHostnameVerifier(hostnameVerifier);
  assertEquals("ABC", readAscii(c2));

  assertEquals(suite, c2.getCipherSuite());
  assertEquals(localCerts, toListOrNull(c2.getLocalCertificates()));
  assertEquals(serverCerts, toListOrNull(c2.getServerCertificates()));
  assertEquals(peerPrincipal, c2.getPeerPrincipal());
  assertEquals(localPrincipal, c2.getLocalPrincipal());
}
 
Example 14
Project: GitHub   File: CallTest.java   Source Code and License 6 votes vote down vote up
@Test public void reusedSourcesGetIndependentTimeoutInstances() throws Exception {
  server.enqueue(new MockResponse().setBody("abc"));
  server.enqueue(new MockResponse().setBody("def"));

  // Call 1: set a deadline on the response body.
  Request request1 = new Request.Builder().url(server.url("/")).build();
  Response response1 = client.newCall(request1).execute();
  BufferedSource body1 = response1.body().source();
  assertEquals("abc", body1.readUtf8());
  body1.timeout().deadline(5, TimeUnit.SECONDS);

  // Call 2: check for the absence of a deadline on the request body.
  Request request2 = new Request.Builder().url(server.url("/")).build();
  Response response2 = client.newCall(request2).execute();
  BufferedSource body2 = response2.body().source();
  assertEquals("def", body2.readUtf8());
  assertFalse(body2.timeout().hasDeadline());

  // Use sequence numbers to confirm the connection was pooled.
  assertEquals(0, server.takeRequest().getSequenceNumber());
  assertEquals(1, server.takeRequest().getSequenceNumber());
}
 
Example 15
Project: GitHub   File: HttpOverHttp2Test.java   Source Code and License 6 votes vote down vote up
@Test public void noDefaultContentLengthOnStreamingPost() throws Exception {
  final byte[] postBytes = "FGHIJ".getBytes(Util.UTF_8);

  server.enqueue(new MockResponse().setBody("ABCDE"));

  Call call = client.newCall(new Request.Builder()
      .url(server.url("/foo"))
      .post(new RequestBody() {
        @Override public MediaType contentType() {
          return MediaType.parse("text/plain; charset=utf-8");
        }

        @Override public void writeTo(BufferedSink sink) throws IOException {
          sink.write(postBytes);
        }
      })
      .build());

  Response response = call.execute();
  assertEquals("ABCDE", response.body().string());

  RecordedRequest request = server.takeRequest();
  assertEquals("POST /foo HTTP/1.1", request.getRequestLine());
  assertArrayEquals(postBytes, request.getBody().readByteArray());
  assertNull(request.getHeader("Content-Length"));
}
 
Example 16
Project: GitHub   File: CacheTest.java   Source Code and License 6 votes vote down vote up
@Test public void varyMatchesUnchangedRequestHeaderField() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Cache-Control: max-age=60")
      .addHeader("Vary: Accept-Language")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  HttpUrl url = server.url("/");
  Request request = new Request.Builder()
      .url(url)
      .header("Accept-Language", "fr-CA")
      .build();
  Response response1 = client.newCall(request).execute();
  assertEquals("A", response1.body().string());
  Request request1 = new Request.Builder()
      .url(url)
      .header("Accept-Language", "fr-CA")
      .build();
  Response response2 = client.newCall(request1).execute();
  assertEquals("A", response2.body().string());
}
 
Example 17
Project: GitHub   File: URLConnectionTest.java   Source Code and License 6 votes vote down vote up
@Test public void redirectedPostStripsRequestBodyHeaders() throws Exception {
  server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
      .addHeader("Location: /page2"));
  server.enqueue(new MockResponse().setBody("Page 2"));

  connection = urlFactory.open(server.url("/page1").url());
  connection.setDoOutput(true);
  connection.addRequestProperty("Content-Length", "4");
  connection.addRequestProperty("Content-Type", "text/plain; charset=utf-8");
  connection.addRequestProperty("Transfer-Encoding", "identity");
  OutputStream outputStream = connection.getOutputStream();
  outputStream.write("ABCD".getBytes("UTF-8"));
  outputStream.close();
  assertEquals("Page 2", readAscii(connection.getInputStream(), Integer.MAX_VALUE));

  assertEquals("POST /page1 HTTP/1.1", server.takeRequest().getRequestLine());

  RecordedRequest page2 = server.takeRequest();
  assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
  assertNull(page2.getHeader("Content-Length"));
  assertNull(page2.getHeader("Content-Type"));
  assertNull(page2.getHeader("Transfer-Encoding"));
}
 
Example 18
Project: GitHub   File: HttpOverHttp2Test.java   Source Code and License 6 votes vote down vote up
@Test public void readAfterLastByte() throws Exception {
  server.enqueue(new MockResponse().setBody("ABC"));

  Call call = client.newCall(new Request.Builder()
      .url(server.url("/"))
      .build());
  Response response = call.execute();

  InputStream in = response.body().byteStream();
  assertEquals('A', in.read());
  assertEquals('B', in.read());
  assertEquals('C', in.read());
  assertEquals(-1, in.read());
  assertEquals(-1, in.read());

  in.close();
}
 
Example 19
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 6 votes vote down vote up
/**
 * Equivalent to {@code CacheTest.postInvalidatesCacheWithUncacheableResponse()} but demonstrating
 * that {@link ResponseCache} provides no mechanism for cache invalidation as the result of
 * locally-made requests. In reality invalidation could take place from other clients at any
 * time.
 */
@Test public void postInvalidatesCacheWithUncacheableResponse() throws Exception {
  // 1. seed the cache
  // 2. invalidate it with uncacheable response
  // 3. the cache to return the original value
  server.enqueue(new MockResponse()
      .setBody("A")
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)));
  server.enqueue(new MockResponse()
      .setBody("B")
      .setResponseCode(500));

  URL url = server.url("/").url();

  assertEquals("A", readAscii(openConnection(url)));

  HttpURLConnection invalidate = openConnection(url);
  invalidate.setRequestMethod("POST");
  addRequestBodyIfNecessary("POST", invalidate);
  assertEquals("B", readAscii(invalidate));

  assertEquals("A", readAscii(openConnection(url)));
}
 
Example 20
Project: GitHub   File: EventListenerTest.java   Source Code and License 6 votes vote down vote up
@Test public void failedCallEventSequence() throws IOException {
  server.enqueue(new MockResponse().setBodyDelay(2, TimeUnit.SECONDS));

  client = client.newBuilder().readTimeout(250, TimeUnit.MILLISECONDS).build();

  Call call = client.newCall(new Request.Builder()
      .url(server.url("/"))
      .build());
  try {
    call.execute();
    fail();
  } catch (IOException expected) {
    assertThat(expected.getMessage(), either(equalTo("timeout")).or(equalTo("Read timed out")));
  }

  List<String> expectedEvents = Arrays.asList("CallStart", "DnsStart", "DnsEnd",
      "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart",
      "RequestHeadersEnd", "ResponseHeadersStart", "ConnectionReleased", "CallFailed");
  assertEquals(expectedEvents, listener.recordedEventTypes());
}
 
Example 21
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 6 votes vote down vote up
@Test public void varyMatchesChangedRequestHeaderField() throws Exception {
  server.enqueue(new MockResponse()
      .addHeader("Cache-Control: max-age=60")
      .addHeader("Vary: Accept-Language")
      .setBody("A"));
  server.enqueue(new MockResponse()
      .setBody("B"));

  URL url = server.url("/").url();
  HttpURLConnection frenchConnection = openConnection(url);
  frenchConnection.setRequestProperty("Accept-Language", "fr-CA");
  assertEquals("A", readAscii(frenchConnection));

  HttpURLConnection englishConnection = openConnection(url);
  englishConnection.setRequestProperty("Accept-Language", "en-US");
  assertEquals("B", readAscii(englishConnection));
}
 
Example 22
Project: XXXX   File: FeignBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testProvideInvocationHandlerFactory() throws Exception {
  server.enqueue(new MockResponse().setBody("response data"));

  String url = "http://localhost:" + server.getPort();

  final AtomicInteger callCount = new AtomicInteger();
  InvocationHandlerFactory factory = new InvocationHandlerFactory() {
    private final InvocationHandlerFactory delegate = new Default();

    @Override
    public InvocationHandler create(Target target, Map<Method, MethodHandler> dispatch) {
      callCount.incrementAndGet();
      return delegate.create(target, dispatch);
    }
  };

  TestInterface api =
      Feign.builder().invocationHandlerFactory(factory).target(TestInterface.class, url);
  Response response = api.codecPost("request data");
  assertEquals("response data", Util.toString(response.body().asReader()));
  assertEquals(1, callCount.get());

  assertThat(server.takeRequest())
      .hasBody("request data");
}
 
Example 23
Project: GitHub   File: HttpOverHttp2Test.java   Source Code and License 6 votes vote down vote up
@Test public void recoverFromOneRefusedStreamReusesConnection() throws Exception {
  server.enqueue(new MockResponse()
      .setSocketPolicy(SocketPolicy.RESET_STREAM_AT_START)
      .setHttp2ErrorCode(ErrorCode.REFUSED_STREAM.httpCode));
  server.enqueue(new MockResponse()
      .setBody("abc"));

  Call call = client.newCall(new Request.Builder()
      .url(server.url("/"))
      .build());
  Response response = call.execute();
  assertEquals("abc", response.body().string());

  assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection.
  assertEquals(1, server.takeRequest().getSequenceNumber()); // Reused connection.
}
 
Example 24
Project: civify-app   File: RewardsFragmentTest.java   Source Code and License 6 votes vote down vote up
private Award mockAward() throws ParseException {
    String dateString = "2016-12-21T20:08:11.000Z";
    DateFormat dateFormat =
            new SimpleDateFormat(ServiceGenerator.RAILS_DATE_FORMAT, Locale.getDefault());
    Date date = dateFormat.parse(dateString);

    Picture picture =
            new Picture("picture-file-name", "picture-content-type", "picture-content");
    picture.setBaseUrl(MOCK_BASE_URL);
    picture.setSmallUrl(MOCK_IMAGE_URL);
    picture.setMedUrl(MOCK_IMAGE_URL);
    picture.setLargeUrl(MOCK_IMAGE_URL);

    MockResponse mockResponse = new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);
    sMockWebServer.enqueue(mockResponse);

    return new Award("award-title", "award-description", 35, date, date, "award-auth-token",
            "commerce-name", picture);
}
 
Example 25
Project: GitHub   File: URLConnectionTest.java   Source Code and License 6 votes vote down vote up
/**
 * We had a bug where we weren't closing Gzip streams on redirects.
 * https://github.com/square/okhttp/issues/441
 */
@Test public void gzipWithRedirectAndConnectionReuse() throws Exception {
  server.enqueue(new MockResponse()
      .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
      .addHeader("Location: /foo")
      .addHeader("Content-Encoding: gzip")
      .setBody(gzip("Moved! Moved! Moved!")));
  server.enqueue(new MockResponse().setBody("This is the new page!"));

  HttpURLConnection connection = urlFactory.open(server.url("/").url());
  assertContent("This is the new page!", connection);

  RecordedRequest requestA = server.takeRequest();
  assertEquals(0, requestA.getSequenceNumber());

  RecordedRequest requestB = server.takeRequest();
  assertEquals(1, requestB.getSequenceNumber());
}
 
Example 26
Project: GitHub   File: ConnectionReuseTest.java   Source Code and License 6 votes vote down vote up
@Test public void connectionsReusedWithRedirectEvenIfPoolIsSizeZero() throws Exception {
  client = client.newBuilder()
      .connectionPool(new ConnectionPool(0, 5, TimeUnit.SECONDS))
      .build();
  server.enqueue(new MockResponse()
      .setResponseCode(301)
      .addHeader("Location: /b")
      .setBody("a"));
  server.enqueue(new MockResponse().setBody("b"));

  Request request = new Request.Builder()
      .url(server.url("/"))
      .build();
  Response response = client.newCall(request).execute();
  assertEquals("b", response.body().string());
  assertEquals(0, server.takeRequest().getSequenceNumber());
  assertEquals(1, server.takeRequest().getSequenceNumber());
}
 
Example 27
Project: GitHub   File: CallTest.java   Source Code and License 6 votes vote down vote up
@Test public void post() throws Exception {
  server.enqueue(new MockResponse().setBody("abc"));

  Request request = new Request.Builder()
      .url(server.url("/"))
      .post(RequestBody.create(MediaType.parse("text/plain"), "def"))
      .build();

  executeSynchronously(request)
      .assertCode(200)
      .assertBody("abc");

  RecordedRequest recordedRequest = server.takeRequest();
  assertEquals("POST", recordedRequest.getMethod());
  assertEquals("def", recordedRequest.getBody().readUtf8());
  assertEquals("3", recordedRequest.getHeader("Content-Length"));
  assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type"));
}
 
Example 28
Project: GitHub   File: WebSocketHttpTest.java   Source Code and License 6 votes vote down vote up
@Test public void closeReasonTooLong() throws IOException {
  webServer.enqueue(new MockResponse().withWebSocketUpgrade(serverListener));

  WebSocket webSocket = newWebSocket();
  WebSocket server = serverListener.assertOpen();

  clientListener.assertOpen();
  String reason = repeat('X', 124);
  try {
    webSocket.close(1000, reason);
    fail();
  } catch (IllegalArgumentException expected) {
    assertEquals("reason.size() > 123: " + reason, expected.getMessage());
  }

  webSocket.close(1000, null);
  serverListener.assertClosing(1000, "");

  server.close(1000, null);
  clientListener.assertClosing(1000, "");
  clientListener.assertClosed(1000, "");

  serverListener.assertClosed(1000, "");
}
 
Example 29
Project: java-okhttp   File: AbstractOkHttpTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testParentSpanSource() throws IOException {
    {
        Scope parent = mockTracer.buildSpan("parent")
                .startActive(true);

        mockWebServer.enqueue(new MockResponse()
                .setResponseCode(203));

        Request request = new Request.Builder()
                .url(mockWebServer.url("bar"))
                .tag(new TagWrapper(parent.span().context()))
                .get()
                .build();

        client.newCall(request).execute();
        parent.close();
    }

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    assertOnErrors(mockSpans);
    Assert.assertEquals(3, mockSpans.size());
    Assert.assertEquals(mockSpans.get(2).context().traceId(), mockSpans.get(1).context().traceId());
    Assert.assertEquals(mockSpans.get(2).context().spanId(), mockSpans.get(1).parentId());
}
 
Example 30
Project: XXXX   File: SetterFactoryTest.java   Source Code and License 6 votes vote down vote up
@Test
  public void customSetter() {
    thrown.expect(HystrixRuntimeException.class);
    thrown.expectMessage("POST / failed and no fallback available.");

    server.enqueue(new MockResponse().setResponseCode(500));

SetterFactory commandKeyIsRequestLine = (target, method) -> {
  String groupKey = target.name();
  String commandKey = method.getAnnotation(RequestLine.class).value();
  return HystrixCommand.Setter
      .withGroupKey(HystrixCommandGroupKey.Factory.asKey(groupKey))
      .andCommandKey(HystrixCommandKey.Factory.asKey(commandKey));
};

    TestInterface api = HystrixFeign.builder()
        .setterFactory(commandKeyIsRequestLine)
        .target(TestInterface.class, "http://localhost:" + server.getPort());

    api.invoke();
  }
 
Example 31
Project: GitHub   File: FlowableTest.java   Source Code and License 6 votes vote down vote up
@Test public void resultRespectsBackpressure() {
  server.enqueue(new MockResponse().setBody("Hi"));

  RecordingSubscriber<Result<String>> subscriber = subscriberRule.createWithInitialRequest(0);
  Flowable<Result<String>> o = service.result();

  o.subscribe(subscriber);
  assertThat(server.getRequestCount()).isEqualTo(1);
  subscriber.assertNoEvents();

  subscriber.request(1);
  subscriber.assertAnyValue().assertComplete();

  subscriber.request(Long.MAX_VALUE); // Subsequent requests do not trigger HTTP or notifications.
  assertThat(server.getRequestCount()).isEqualTo(1);
}
 
Example 32
Project: XXXX   File: HystrixBuilderTest.java   Source Code and License 6 votes vote down vote up
@Test
public void rxSingleListFallback() {
  server.enqueue(new MockResponse().setResponseCode(500));

  TestInterface api = target();

  Single<List<String>> single = api.listSingle();

  assertThat(single).isNotNull();
  assertThat(server.getRequestCount()).isEqualTo(0);

  TestSubscriber<List<String>> testSubscriber = new TestSubscriber<List<String>>();
  single.subscribe(testSubscriber);
  testSubscriber.awaitTerminalEvent();
  assertThat(testSubscriber.getOnNextEvents().get(0)).containsExactly("fallback");
}
 
Example 33
Project: GitHub   File: URLConnectionTest.java   Source Code and License 6 votes vote down vote up
@Test public void redirectedFromHttpsToHttpFollowingProtocolRedirects() throws Exception {
  server2.enqueue(new MockResponse().setBody("This is insecure HTTP!"));

  server.useHttps(sslClient.socketFactory, false);
  server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
      .addHeader("Location: " + server2.url("/").url())
      .setBody("This page has moved!"));

  urlFactory.setClient(urlFactory.client().newBuilder()
      .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
      .hostnameVerifier(new RecordingHostnameVerifier())
      .followSslRedirects(true)
      .build());
  HttpsURLConnection connection = (HttpsURLConnection) urlFactory.open(server.url("/").url());
  assertContent("This is insecure HTTP!", connection);
  assertNull(connection.getCipherSuite());
  assertNull(connection.getLocalCertificates());
  assertNull(connection.getServerCertificates());
  assertNull(connection.getPeerPrincipal());
  assertNull(connection.getLocalPrincipal());
}
 
Example 34
Project: LoginEligibility.Android   File: LEServiceHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_policyCheckerTask_error() throws Exception {
    testResult = null;
    testResultError = null;
    String complies = "{\"errorCode\":\"some error info\"}";

    server.enqueue(new MockResponse()
            .setResponseCode(400)
            .addHeader("Content-Type", "application/json; charset=utf-8")
            .addHeader("Cache-Control", "no-cache")
            .setBody(complies));
    LEService leService= new LEService();
    leService.init(goodConfig);
    leService.checkLoginWithToken("abcdefghijk", taskHandler);
    signal.await();
    server.shutdown();
    assertNull(testResult);
    assertTrue(testResultError.has("errorCode"));
    assertEquals("some error info", testResultError.getString("errorCode"));

}
 
Example 35
Project: GitHub   File: VolleyStreamFetcherServerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testHandlesRedirect301s() throws Exception {
  String expected = "fakedata";
  mockWebServer.enqueue(new MockResponse().setResponseCode(301)
      .setHeader("Location", mockWebServer.url("/redirect").toString()));
  mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(expected));
  getFetcher().loadData(Priority.LOW, callback);
  waitForResponseLatch.await();
  verify(callback).onDataReady(streamCaptor.capture());
  assertStreamOf(expected, streamCaptor.getValue());
}
 
Example 36
Project: GitHub   File: ResponseCacheTest.java   Source Code and License 5 votes vote down vote up
@Test public void maxAgeInThePastWithDateAndLastModifiedHeaders() throws Exception {
  String lastModifiedDate = formatDate(-2, TimeUnit.HOURS);
  RecordedRequest conditionalRequest = assertConditionallyCached(new MockResponse()
      .addHeader("Date: " + formatDate(-120, TimeUnit.SECONDS))
      .addHeader("Last-Modified: " + lastModifiedDate)
      .addHeader("Cache-Control: max-age=60"));
  assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since"));
}
 
Example 37
Project: GitHub   File: CacheTest.java   Source Code and License 5 votes vote down vote up
@Test public void secureResponseCachingAndRedirects() throws IOException {
  server.useHttps(sslClient.socketFactory, false);
  server.enqueue(new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
      .setResponseCode(HttpURLConnection.HTTP_MOVED_PERM)
      .addHeader("Location: /foo"));
  server.enqueue(new MockResponse()
      .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
      .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
      .setBody("ABC"));
  server.enqueue(new MockResponse()
      .setBody("DEF"));

  client = client.newBuilder()
      .sslSocketFactory(sslClient.socketFactory, sslClient.trustManager)
      .hostnameVerifier(NULL_HOSTNAME_VERIFIER)
      .build();

  Response response1 = get(server.url("/"));
  assertEquals("ABC", response1.body().string());
  assertNotNull(response1.handshake().cipherSuite());

  // Cached!
  Response response2 = get(server.url("/"));
  assertEquals("ABC", response2.body().string());
  assertNotNull(response2.handshake().cipherSuite());

  assertEquals(4, cache.requestCount()); // 2 direct + 2 redirect = 4
  assertEquals(2, cache.hitCount());
  assertEquals(response1.handshake().cipherSuite(), response2.handshake().cipherSuite());
}
 
Example 38
Project: GitHub   File: UrlConnectionCacheTest.java   Source Code and License 5 votes vote down vote up
@Test public void defaultExpirationDateConditionallyCached() throws Exception {
  //      last modified: 115 seconds ago
  //             served:  15 seconds ago
  //   default lifetime: (115 - 15) / 10 = 10 seconds
  //            expires:  10 seconds from served date = 5 seconds ago
  String lastModifiedDate = formatDate(-115, TimeUnit.SECONDS);
  RecordedRequest conditionalRequest = assertConditionallyCached(
      new MockResponse().addHeader("Last-Modified: " + lastModifiedDate)
          .addHeader("Date: " + formatDate(-15, TimeUnit.SECONDS)));
  assertEquals(lastModifiedDate, conditionalRequest.getHeader("If-Modified-Since"));
}
 
Example 39
Project: GitHub   File: VolleyStreamFetcherServerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAppliesHeadersInGlideUrl() throws Exception {
  mockWebServer.enqueue(new MockResponse().setResponseCode(200));
  String headerField = "field";
  String headerValue = "value";
  Map<String, String> headersMap = new HashMap<>();
  headersMap.put(headerField, headerValue);
  Headers headers = mock(Headers.class);
  when(headers.getHeaders()).thenReturn(headersMap);

  getFetcher(headers).loadData(Priority.HIGH, callback);
  waitForResponseLatch.await();

  assertThat(mockWebServer.takeRequest().getHeader(headerField)).isEqualTo(headerValue);
}
 
Example 40
Project: nifi-android-s2s   File: PeerTrackerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testUnsuccessfulResponseCode() throws IOException {
    expectedException.expect(IOException.class);
    expectedException.expectMessage(new StringStartsWith(RECEIVED_RESPONSE_CODE));

    mockNiFiS2SServer.getMockWebServer().enqueue(new MockResponse().setResponseCode(400));

    new HttpSiteToSiteClient(siteToSiteClientConfig, siteToSiteRemoteCluster);
}