Пример #1
0
 private HttpUrl urlWithIpAddress(MockWebServer server, String path) throws Exception {
   return server
       .url(path)
       .newBuilder()
       .host(InetAddress.getByName(server.getHostName()).getHostAddress())
       .build();
 }
Пример #2
0
  @Test
  public void proxySelector() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));

    ProxySelector proxySelector =
        new ProxySelector() {
          @Override
          public List<Proxy> select(URI uri) {
            return Collections.singletonList(socksProxy.proxy());
          }

          @Override
          public void connectFailed(URI uri, SocketAddress socketAddress, IOException e) {
            throw new AssertionError();
          }
        };

    OkHttpClient client = new OkHttpClient.Builder().setProxySelector(proxySelector).build();

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

    assertEquals(1, socksProxy.connectionCount());
  }
Пример #3
0
  @Test
  public void testNetscapeResponse() throws Exception {
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));
    MockWebServer server = new MockWebServer();
    server.start();

    HttpUrl urlWithIpAddress = urlWithIpAddress(server, "/path/foo");
    server.enqueue(
        new MockResponse()
            .addHeader(
                "Set-Cookie: a=android; "
                    + "expires=Fri, 31-Dec-9999 23:59:59 GMT; "
                    + "path=/path; "
                    + "domain="
                    + urlWithIpAddress.host()
                    + "; "
                    + "secure"));
    get(urlWithIpAddress);

    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    assertEquals(1, cookies.size());
    HttpCookie cookie = cookies.get(0);
    assertEquals("a", cookie.getName());
    assertEquals("android", cookie.getValue());
    assertEquals(null, cookie.getComment());
    assertEquals(null, cookie.getCommentURL());
    assertEquals(false, cookie.getDiscard());
    assertTrue(cookie.getMaxAge() > 100000000000L);
    assertEquals("/path", cookie.getPath());
    assertEquals(true, cookie.getSecure());
    assertEquals(0, cookie.getVersion());
  }
Пример #4
0
  @Test
  public void testRfc2109Response() throws Exception {
    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));
    MockWebServer server = new MockWebServer();
    server.start();

    HttpUrl urlWithIpAddress = urlWithIpAddress(server, "/path/foo");
    server.enqueue(
        new MockResponse()
            .addHeader(
                "Set-Cookie: a=android; "
                    + "Comment=this cookie is delicious; "
                    + "Domain="
                    + urlWithIpAddress.host()
                    + "; "
                    + "Max-Age=60; "
                    + "Path=/path; "
                    + "Secure; "
                    + "Version=1"));
    get(urlWithIpAddress);

    List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
    assertEquals(1, cookies.size());
    HttpCookie cookie = cookies.get(0);
    assertEquals("a", cookie.getName());
    assertEquals("android", cookie.getValue());
    assertEquals(null, cookie.getCommentURL());
    assertEquals(false, cookie.getDiscard());
    assertEquals(60.0, cookie.getMaxAge(), 1.0); // Converting to a fixed date can cause rounding!
    assertEquals("/path", cookie.getPath());
    assertEquals(true, cookie.getSecure());
  }
Пример #5
0
  @Test
  public void testCookiesSentIgnoresCase() throws Exception {
    client.setCookieJar(
        new JavaNetCookieJar(
            new CookieManager() {
              @Override
              public Map<String, List<String>> get(
                  URI uri, Map<String, List<String>> requestHeaders) throws IOException {
                Map<String, List<String>> result = new HashMap<>();
                result.put("COOKIE", Collections.singletonList("Bar=bar"));
                result.put("cooKIE2", Collections.singletonList("Baz=baz"));
                return result;
              }
            }));

    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.start();

    get(server.url("/"));

    RecordedRequest request = server.takeRequest();
    assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie"));
    assertNull(request.getHeader("Cookie2"));
    assertNull(request.getHeader("Quux"));
  }
  @Test
  public void anInterface() throws IOException, InterruptedException {
    server.enqueue(new MockResponse().setBody("{\"name\":\"value\"}"));

    Call<AnInterface> call = service.anInterface(new AnImplementation("value"));
    Response<AnInterface> response = call.execute();
    AnInterface body = response.body();
    assertThat(body.getName()).isEqualTo("value");

    RecordedRequest request = server.takeRequest();
    assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}");
    assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
  }
  @Test
  public void anImplementation() throws IOException, InterruptedException {
    server.enqueue(new MockResponse().setBody("{\"theName\":\"value\"}"));

    Call<AnImplementation> call = service.anImplementation(new AnImplementation("value"));
    Response<AnImplementation> response = call.execute();
    AnImplementation body = response.body();
    assertThat(body.theName).isEqualTo("value");

    RecordedRequest request = server.takeRequest();
    // TODO figure out how to get Jackson to stop using AnInterface's serializer here.
    assertThat(request.getBody().readUtf8()).isEqualTo("{\"name\":\"value\"}");
    assertThat(request.getHeader("Content-Type")).isEqualTo("application/json; charset=UTF-8");
  }
 @Test
 public void testEventBusIsNotPostedOn500Error() throws Exception {
   server.start();
   server.enqueue(
       new MockResponse()
           .setResponseCode(500)
           .setBody(
               getStringFromFile(
                   RuntimeEnvironment.application, "incorrect_success_response.json")));
   MainActivity.URL = server.url("/").toString();
   serviceHelper.setEventBus(eventBus);
   serviceHelper.getIndividualEpisodeData("Friends", "7");
   verifyNoMoreInteractions(eventBus);
 }
Пример #9
0
  @Test
  public void checkRemoteDNSResolve() throws Exception {
    // This testcase will fail if the target is resolved locally instead of through the proxy.
    server.enqueue(new MockResponse().setBody("abc"));

    OkHttpClient client = new OkHttpClient.Builder().setProxy(socksProxy.proxy()).build();

    HttpUrl url =
        server.url("/").newBuilder().host(socksProxy.HOSTNAME_THAT_ONLY_THE_PROXY_KNOWS).build();

    Request request = new Request.Builder().url(url).build();
    Response response1 = client.newCall(request).execute();
    assertEquals("abc", response1.body().string());

    assertEquals(1, socksProxy.connectionCount());
  }
Пример #10
0
  @Test
  public void proxy() throws Exception {
    server.enqueue(new MockResponse().setBody("abc"));
    server.enqueue(new MockResponse().setBody("def"));

    OkHttpClient client = new OkHttpClient.Builder().setProxy(socksProxy.proxy()).build();

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

    Request request2 = new Request.Builder().url(server.url("/")).build();
    Response response2 = client.newCall(request2).execute();
    assertEquals("def", response2.body().string());

    // The HTTP calls should share a single connection.
    assertEquals(1, socksProxy.connectionCount());
  }
 @Before
 public void setUp() {
   Retrofit retrofit =
       new Retrofit.Builder()
           .baseUrl(server.url("/"))
           .addConverterFactory(ScalarsConverterFactory.create())
           .build();
   service = retrofit.create(Service.class);
 }
 @Test
 public void testEventBusIsPostedWithNoDataOnServiceCallWithAnIncorrectResponse()
     throws Exception {
   server.start();
   server.enqueue(
       new MockResponse()
           .setResponseCode(200)
           .setBody(
               getStringFromFile(
                   RuntimeEnvironment.application, "incorrect_success_response.json")));
   MainActivity.URL = server.url("/").toString();
   serviceHelper.setEventBus(eventBus);
   serviceHelper.getIndividualEpisodeData("Friends", "7");
   verify(eventBus).post(anyObject());
   verify(eventBus).post(captor.capture());
   IndividualEpisodeResponseEvent episodeLists =
       (IndividualEpisodeResponseEvent) captor.getValue();
   assertNull(episodeLists.getEpisodesList());
 }
 @Test
 public void testEventBusIsPostedOnSuccessfulServiceCall() throws Exception {
   server.start();
   server.enqueue(
       new MockResponse()
           .setResponseCode(200)
           .setBody(
               getStringFromFile(RuntimeEnvironment.application, "episodes_list_success.json")));
   MainActivity.URL = server.url("/").toString();
   serviceHelper.setEventBus(eventBus);
   serviceHelper.getIndividualEpisodeData("Friends", "7");
   verify(eventBus).post(anyObject());
   verify(eventBus).post(captor.capture());
   IndividualEpisodeResponseEvent episodeLists =
       (IndividualEpisodeResponseEvent) captor.getValue();
   assertThat(
       "The One Where I am testing something",
       equalTo(episodeLists.getEpisodesList().get(0).getTitle()));
 }
Пример #14
0
  @Test
  public void testSendingCookiesFromStore() throws Exception {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse());
    server.start();

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookieA = new HttpCookie("a", "android");
    cookieA.setDomain(server.getHostName());
    cookieA.setPath("/");
    cookieManager.getCookieStore().add(server.url("/").uri(), cookieA);
    HttpCookie cookieB = new HttpCookie("b", "banana");
    cookieB.setDomain(server.getHostName());
    cookieB.setPath("/");
    cookieManager.getCookieStore().add(server.url("/").uri(), cookieB);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));

    get(server.url("/"));
    RecordedRequest request = server.takeRequest();

    assertEquals("a=android; b=banana", request.getHeader("Cookie"));
  }
  @Before
  public void setUp() {
    SimpleModule module = new SimpleModule();
    module.addSerializer(AnInterface.class, new AnInterfaceSerializer());
    module.addDeserializer(AnInterface.class, new AnInterfaceDeserializer());
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);
    mapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    mapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
    mapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
    mapper.setVisibilityChecker(
        mapper
            .getSerializationConfig()
            .getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY));

    Retrofit retrofit =
        new Retrofit.Builder()
            .baseUrl(server.url("/"))
            .addConverterFactory(JacksonConverterFactory.create(mapper))
            .build();
    service = retrofit.create(Service.class);
  }
 @After
 public void tearDown() throws Exception {
   server.shutdown();
 }
  @Test
  public void supportedResponseTypes() throws IOException, InterruptedException {
    server.enqueue(new MockResponse().setBody("test"));
    Response<String> stringResponse = service.stringObject().execute();
    assertThat(stringResponse.body()).isEqualTo("test");

    server.enqueue(new MockResponse().setBody("true"));
    Response<Boolean> booleanResponse = service.booleanObject().execute();
    assertThat(booleanResponse.body()).isTrue();

    server.enqueue(new MockResponse().setBody("5"));
    Response<Byte> byteResponse = service.byteObject().execute();
    assertThat(byteResponse.body()).isEqualTo((byte) 5);

    server.enqueue(new MockResponse().setBody("b"));
    Response<Character> characterResponse = service.charObject().execute();
    assertThat(characterResponse.body()).isEqualTo('b');

    server.enqueue(new MockResponse().setBody(""));
    try {
      service.charObject().execute();
    } catch (IOException e) {
      assertThat(e).hasMessage("Expected body of length 1 for Character conversion but was 0");
    }

    server.enqueue(new MockResponse().setBody("bb"));
    try {
      service.charObject().execute();
    } catch (IOException e) {
      assertThat(e).hasMessage("Expected body of length 1 for Character conversion but was 2");
    }

    server.enqueue(new MockResponse().setBody("13.13"));
    Response<Double> doubleResponse = service.doubleObject().execute();
    assertThat(doubleResponse.body()).isEqualTo(13.13);

    server.enqueue(new MockResponse().setBody("13.13"));
    Response<Float> floatResponse = service.floatObject().execute();
    assertThat(floatResponse.body()).isEqualTo(13.13f);

    server.enqueue(new MockResponse().setBody("13"));
    Response<Integer> integerResponse = service.integerObject().execute();
    assertThat(integerResponse.body()).isEqualTo(13);

    server.enqueue(new MockResponse().setBody("1347"));
    Response<Long> longResponse = service.longObject().execute();
    assertThat(longResponse.body()).isEqualTo(1347L);

    server.enqueue(new MockResponse().setBody("134"));
    Response<Short> shortResponse = service.shortObject().execute();
    assertThat(shortResponse.body()).isEqualTo((short) 134);
  }
Пример #18
0
 @Before
 public void setUp() throws Exception {
   server.start();
   socksProxy.play();
 }
  @Test
  public void supportedRequestTypes() throws IOException, InterruptedException {
    RecordedRequest request;

    server.enqueue(new MockResponse());
    service.stringObject("string").execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("6");
    assertThat(request.getBody().readUtf8()).isEqualTo("string");

    server.enqueue(new MockResponse());
    service.booleanPrimitive(true).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("4");
    assertThat(request.getBody().readUtf8()).isEqualTo("true");

    server.enqueue(new MockResponse());
    service.booleanObject(false).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("5");
    assertThat(request.getBody().readUtf8()).isEqualTo("false");

    server.enqueue(new MockResponse());
    service.bytePrimitive((byte) 0).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("1");
    assertThat(request.getBody().readUtf8()).isEqualTo("0");

    server.enqueue(new MockResponse());
    service.byteObject((byte) 1).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("1");
    assertThat(request.getBody().readUtf8()).isEqualTo("1");

    server.enqueue(new MockResponse());
    service.charPrimitive('a').execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("1");
    assertThat(request.getBody().readUtf8()).isEqualTo("a");

    server.enqueue(new MockResponse());
    service.charObject('b').execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("1");
    assertThat(request.getBody().readUtf8()).isEqualTo("b");

    server.enqueue(new MockResponse());
    service.doublePrimitive(2.2d).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("3");
    assertThat(request.getBody().readUtf8()).isEqualTo("2.2");

    server.enqueue(new MockResponse());
    service.doubleObject(3.3d).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("3");
    assertThat(request.getBody().readUtf8()).isEqualTo("3.3");

    server.enqueue(new MockResponse());
    service.floatPrimitive(4.4f).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("3");
    assertThat(request.getBody().readUtf8()).isEqualTo("4.4");

    server.enqueue(new MockResponse());
    service.floatObject(5.5f).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("3");
    assertThat(request.getBody().readUtf8()).isEqualTo("5.5");

    server.enqueue(new MockResponse());
    service.integerPrimitive(6).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("1");
    assertThat(request.getBody().readUtf8()).isEqualTo("6");

    server.enqueue(new MockResponse());
    service.integerObject(7).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("1");
    assertThat(request.getBody().readUtf8()).isEqualTo("7");

    server.enqueue(new MockResponse());
    service.longPrimitive(8L).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("1");
    assertThat(request.getBody().readUtf8()).isEqualTo("8");

    server.enqueue(new MockResponse());
    service.longObject(9L).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("1");
    assertThat(request.getBody().readUtf8()).isEqualTo("9");

    server.enqueue(new MockResponse());
    service.shortPrimitive((short) 10).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("2");
    assertThat(request.getBody().readUtf8()).isEqualTo("10");

    server.enqueue(new MockResponse());
    service.shortObject((short) 11).execute();
    request = server.takeRequest();
    assertThat(request.getHeader("Content-Type")).isEqualTo("text/plain; charset=UTF-8");
    assertThat(request.getHeader("Content-Length")).isEqualTo("2");
    assertThat(request.getBody().readUtf8()).isEqualTo("11");
  }
Пример #20
0
  @Test
  public void testRedirectsDoNotIncludeTooManyCookies() throws Exception {
    MockWebServer redirectTarget = new MockWebServer();
    redirectTarget.enqueue(new MockResponse().setBody("A"));
    redirectTarget.start();

    MockWebServer redirectSource = new MockWebServer();
    redirectSource.enqueue(
        new MockResponse()
            .setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP)
            .addHeader("Location: " + redirectTarget.url("/")));
    redirectSource.start();

    CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
    HttpCookie cookie = new HttpCookie("c", "cookie");
    cookie.setDomain(redirectSource.getHostName());
    cookie.setPath("/");
    String portList = Integer.toString(redirectSource.getPort());
    cookie.setPortlist(portList);
    cookieManager.getCookieStore().add(redirectSource.url("/").uri(), cookie);
    client.setCookieJar(new JavaNetCookieJar(cookieManager));

    get(redirectSource.url("/"));
    RecordedRequest request = redirectSource.takeRequest();

    assertEquals("c=cookie", request.getHeader("Cookie"));

    for (String header : redirectTarget.takeRequest().getHeaders().names()) {
      if (header.startsWith("Cookie")) {
        fail(header);
      }
    }
  }