Java Code Examples for okhttp3.mockwebserver.MockWebServer#enqueue()

The following examples show how to use okhttp3.mockwebserver.MockWebServer#enqueue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IndexTests.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Uses a mock web server to record a _find request using the specified options
 *
 * @param builder query to make
 * @return the JsonElement from the use_index property of the JsonObject POSTed with the request
 * @throws Exception
 */
private JsonElement getUseIndexFromRequest(QueryBuilder builder) throws Exception {
    JsonElement useIndexRequestProperty = null;
    MockWebServer mockWebServer = new MockWebServer();
    // Return 200 OK with empty array of docs (once for each request)
    mockWebServer.enqueue(new MockResponse().setBody("{ \"docs\" : []}"));
    mockWebServer.start();
    try {
        CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder
                (mockWebServer).build();
        Database db = client.database("mock", false);
        db.query(builder.build(), Movie.class);
        RecordedRequest request = mockWebServer.takeRequest(1, TimeUnit.SECONDS);
        JsonObject body = new Gson().fromJson(request.getBody().readUtf8(), JsonObject.class);
        useIndexRequestProperty = body.get("use_index");
    } finally {
        mockWebServer.shutdown();
    }
    return useIndexRequestProperty;
}
 
Example 2
Source File: StreamDecoderTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void simpleStreamTest() {
  MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse().setBody("foo\nbar"));

  StreamInterface api = Feign.builder()
      .decoder(StreamDecoder.create(
          (response, type) -> new BufferedReader(response.body().asReader(UTF_8)).lines()
              .iterator()))
      .doNotCloseAfterDecode()
      .target(StreamInterface.class, server.url("/").toString());

  try (Stream<String> stream = api.get()) {
    assertThat(stream.collect(Collectors.toList())).isEqualTo(Arrays.asList("foo", "bar"));
  }
}
 
Example 3
Source File: AsyncTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncClient() throws Exception {
    MockWebServer mockWebServer = new MockWebServer();
    URI uri = mockWebServer.url("/").uri();
    AsyncClient client = RestClientBuilder.newBuilder()
                                          .baseUri(uri)
                                          .connectTimeout(5, TimeUnit.SECONDS)
                                          .readTimeout(5, TimeUnit.SECONDS)
                                          .build(AsyncClient.class);
    assertNotNull(client);

    mockWebServer.enqueue(new MockResponse().setBody("Hello"));
    mockWebServer.enqueue(new MockResponse().setBody("World"));

    String combined = client.get().thenCombine(client.get(), (a, b) -> {
        return a + " " + b;
    }).toCompletableFuture().get(10, TimeUnit.SECONDS);

    assertTrue("Hello World".equals(combined) || "World Hello".equals(combined));
}
 
Example 4
Source File: TelemetryInterceptorTest.java    From auth0-java with MIT License 6 votes vote down vote up
@Test
public void shouldAddTelemetryHeaderIfEnabled() throws Exception {
    TelemetryInterceptor interceptor = new TelemetryInterceptor(telemetry);
    interceptor.setEnabled(true);
    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .build();

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

    Request request = new Request.Builder()
            .get()
            .url(server.url("/"))
            .build();
    client.newCall(request).execute();

    RecordedRequest finalRequest = server.takeRequest();
    assertThat(finalRequest.getHeader("Auth0-Client"), is("ClientInfo"));

    server.shutdown();
}
 
Example 5
Source File: SixpackTest.java    From sixpack-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testGetClientIdInterceptor() throws IOException {
    String clientId = "test-client-id";

    MockWebServer webServer = new MockWebServer();
    webServer.enqueue(new MockResponse());
    webServer.start();
    HttpUrl url = webServer.url("/");

    Interceptor clientIdInterceptor = Sixpack.getClientIdInterceptor(clientId);
    assertNotNull(clientIdInterceptor);

    OkHttpClient client = new OkHttpClient.Builder()
            .addInterceptor(clientIdInterceptor)
            .build();

    Response response = client.newCall(new Request.Builder().url(url).build()).execute();

    assertEquals(clientId, response.request().url().queryParameter("client_id"));
}
 
Example 6
Source File: NotificationScreenshots.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
@Before
public void setUpWebServer() throws IOException {
    webServer = new MockWebServer();

    // Test page
    webServer.enqueue(new MockResponse().setBody(TestHelper.readTestAsset("plain_test.html")));
}
 
Example 7
Source File: SettingsBlockToggleTest.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void beforeActivityLaunched() {
    super.beforeActivityLaunched();

    Context appContext = InstrumentationRegistry.getInstrumentation()
            .getTargetContext()
            .getApplicationContext();

    PreferenceManager.getDefaultSharedPreferences(appContext)
            .edit()
            .putBoolean(FIRSTRUN_PREF, true)
            .apply();

    // This test runs on both GV and WV.
    // Klar is used to test Geckoview. make sure it's set to Gecko
    TestHelper.selectGeckoForKlar();

    webServer = new MockWebServer();

    try {
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("plain_test.html")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("plain_test.html")));

        webServer.start();
    } catch (IOException e) {
        throw new AssertionError("Could not start web server", e);
    }
}
 
Example 8
Source File: OptionalDecoderTests.java    From feign with Apache License 2.0 5 votes vote down vote up
@Test
public void simple404OptionalTest() throws IOException, InterruptedException {
  final MockWebServer server = new MockWebServer();
  server.enqueue(new MockResponse().setResponseCode(404));
  server.enqueue(new MockResponse().setBody("foo"));

  final OptionalInterface api = Feign.builder()
      .decode404()
      .decoder(new OptionalDecoder(new Decoder.Default()))
      .target(OptionalInterface.class, server.url("/").toString());

  assertThat(api.getAsOptional().isPresent()).isFalse();
  assertThat(api.getAsOptional().get()).isEqualTo("foo");
}
 
Example 9
Source File: DownloadFileTest.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void beforeActivityLaunched() {
    super.beforeActivityLaunched();

    Context appContext = InstrumentationRegistry.getInstrumentation()
            .getTargetContext()
            .getApplicationContext();

    // This test is for webview only. Debug is defaulted to Webview, and Klar is used for GV testing.
    org.junit.Assume.assumeTrue(!AppConstants.INSTANCE.isGeckoBuild() && !AppConstants.INSTANCE.isKlarBuild());
    // This test is for API 25 and greater. see https://github.com/mozilla-mobile/focus-android/issues/2696
    org.junit.Assume.assumeTrue(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N);


    PreferenceManager.getDefaultSharedPreferences(appContext)
            .edit()
            .putBoolean(FIRSTRUN_PREF, true)
            .apply();

    webServer = new MockWebServer();

    try {
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("image_test.html"))
                .addHeader("Set-Cookie", "sphere=battery; Expires=Wed, 21 Oct 2035 07:28:00 GMT;"));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("rabbit.jpg")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("download.jpg")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("download.jpg")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("download.jpg")));

        webServer.start();
    } catch (IOException e) {
        throw new AssertionError("Could not start web server", e);
    }
}
 
Example 10
Source File: MultitaskingTest.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
@Before
public void startWebServer() throws Exception {
    webServer = new MockWebServer();

    webServer.enqueue(createMockResponseFromAsset("tab1.html"));
    webServer.enqueue(createMockResponseFromAsset("tab2.html"));
    webServer.enqueue(createMockResponseFromAsset("tab3.html"));
    webServer.enqueue(createMockResponseFromAsset("tab2.html"));

    webServer.start();

    loadingIdlingResource = new SessionLoadedIdlingResource();
    IdlingRegistry.getInstance().register(loadingIdlingResource);
}
 
Example 11
Source File: SteamDirectoryTest.java    From JavaSteam with MIT License 5 votes vote down vote up
@Test
public void load() throws IOException, InterruptedException {
    MockWebServer server = new MockWebServer();

    server.enqueue(new MockResponse().setBody(IOUtils.toString(
            WebAPITest.class.getClassLoader().getResource("testresponses/GetCMList.vdf"), "UTF-8")));

    server.start();

    final HttpUrl baseUrl = server.url("/");

    SteamConfiguration config = SteamConfiguration.create(new Consumer<ISteamConfigurationBuilder>() {
        @Override
        public void accept(ISteamConfigurationBuilder b) {
            b.withWebAPIBaseAddress(baseUrl.toString());
        }
    });

    List<ServerRecord> servers = SteamDirectory.load(config);

    assertEquals(200, servers.size());

    RecordedRequest request = server.takeRequest();
    assertEquals("/ISteamDirectory/GetCMList/v1?format=vdf&cellid=0", request.getPath());
    assertEquals("GET", request.getMethod());

    server.shutdown();
}
 
Example 12
Source File: OpenInExternalBrowserDialogueTest.java    From focus-android with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void beforeActivityLaunched() {
    super.beforeActivityLaunched();

    Context appContext = InstrumentationRegistry.getInstrumentation()
            .getTargetContext()
            .getApplicationContext();

    PreferenceManager.getDefaultSharedPreferences(appContext)
            .edit()
            .putBoolean(FIRSTRUN_PREF, true)
            .apply();

    // This test runs on both GV and WV.
    // Klar is used to test Geckoview. make sure it's set to Gecko
    TestHelper.selectGeckoForKlar();

    webServer = new MockWebServer();

    try {
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("plain_test.html")));
        webServer.enqueue(new MockResponse()
                .setBody(TestHelper.readTestAsset("plain_test.html")));

        webServer.start();
    } catch (IOException e) {
        throw new AssertionError("Could not start web server", e);
    }
}
 
Example 13
Source File: AccountServiceTest.java    From africastalking-android with MIT License 5 votes vote down vote up
@Test
public void getUser() throws Exception {
    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setBody("{\"UserData\": {\"balance\": \"2000\" } }"));
    server.start();
    assertNotNull("GetUser: Response is null", account.getUser());
    assertEquals("GetUser: Balance is not 2000", "2000", account.getUser().userData.balance.trim());
}
 
Example 14
Source File: ServerTest.java    From java-stellar-sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testNextPage() throws IOException, URISyntaxException {
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(operationsPageResponse));
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody(operationsPageResponse));
    mockWebServer.start();
    HttpUrl baseUrl = mockWebServer.url("");
    Server server = new Server(baseUrl.toString());

    Page<OperationResponse> page = server.operations().execute();
    assertEquals(1, page.getRecords().size());
    assertEquals("dd9d10c80a344f4464df3ecaa63705a5ef4a0533ff2f2099d5ef371ab5e1c046", page.getRecords().get(0).getTransactionHash());
    Page<OperationResponse> nextPage = page.getNextPage(server.getHttpClient());
    assertEquals(1, page.getRecords().size());
}
 
Example 15
Source File: CliProxyEnvVarIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
private void assertCliUsesProxy(Map<String, String> env, MockWebServer server, HttpProxyRequestTracker proxyRequestTracker)
{
    String endpoint = server.url("/").toString();
    logger.info("server endpoint: {}, env: {}", endpoint, env);
    server.enqueue(VERSION_RESPONSE);
    CommandStatus versionStatus = main(env, "version", "-c", "/dev/null", "-e", endpoint, "--disable-cert-validation");
    assertThat(versionStatus.errUtf8(), versionStatus.code(), is(0));
    assertThat(server.getRequestCount(), is(1));
    assertThat(proxyRequestTracker.clientRequestsReceived.get(), is(1));
    assertThat(versionStatus.outUtf8(), Matchers.containsString("Server version: " + buildVersion()));
}
 
Example 16
Source File: EmitterTest.java    From snowplow-android-tracker with Apache License 2.0 5 votes vote down vote up
public EmittableEvents getEmittableEvents(MockWebServer mockServer, int count) {
    ArrayList<Payload> events = new ArrayList<>();
    LinkedList<Long> eventIds = new LinkedList<>();
    for (int i = 0; i < count; i++) {
        TrackerPayload payload = new TrackerPayload();
        payload.add("a", String.valueOf(i));

        events.add(payload);
        eventIds.add((long) i);

        mockServer.enqueue(new MockResponse());
    }
    return new EmittableEvents(events, eventIds);
}
 
Example 17
Source File: CacheListTest.java    From Forage with Mozilla Public License 2.0 5 votes vote down vote up
public void queueNetworkRequest(final MockWebServer mockWebServer) {
    String jsonResponse = "{\n" +
            "  \"CACHE1\":{\n" +
            "    \"code\":\"CACHE1\",\n" +
            "    \"name\":\"Cache Name 1\",\n" +
            "    \"location\":\"45|45\",\n" +
            "    \"type\":\"Traditional\",\n" +
            "    \"status\":\"Available\",\n" +
            "    \"terrain\":1,\n" +
            "    \"difficulty\":2.5,\n" +
            "    \"size2\":\"micro\",\n" +
            "    \"description\":\"<p>Cache Description 1<\\/p>\"\n" +
            "  },\n" +
            "  \"CACHE2\":{\n" +
            "    \"code\":\"CACHE2\",\n" +
            "    \"name\":\"Cache Name 2\",\n" +
            "    \"location\":\"0|0\",\n" +
            "    \"type\":\"Virtual\",\n" +
            "    \"status\":\"Available\",\n" +
            "    \"terrain\":1,\n" +
            "    \"difficulty\":1,\n" +
            "    \"size2\":\"none\",\n" +
            "    \"description\":\"<p>Cache Description 2<\\/p>\"\n" +
            "  }\n" +
            "}";
    mockWebServer.enqueue(new MockResponse().setBody(jsonResponse));

}
 
Example 18
Source File: EventSendingTest.java    From snowplow-android-tracker with Apache License 2.0 5 votes vote down vote up
private MockWebServer getMockServer(int count) throws IOException {
    EventStore eventStore = new EventStore(getContext(), 10);
    eventStore.removeAllEvents();

    MockWebServer mockServer = new MockWebServer();
    mockServer.start();

    MockResponse mockResponse = new MockResponse().setResponseCode(200);
    for (int i = 0; i < count; i++) {
        mockServer.enqueue(mockResponse);
    }

    return mockServer;
}
 
Example 19
Source File: CreatePrivacyGroupHandlerTest.java    From orion with Apache License 2.0 4 votes vote down vote up
FakePeer(final MockResponse response) throws IOException {
  server = new MockWebServer();
  publicKey = memoryKeyStore.generateKeyPair();
  server.enqueue(response);
  server.start();
}
 
Example 20
Source File: ZooniverseClientTest.java    From android-galaxyzoo with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testMoreItems() throws IOException, InterruptedException, ZooniverseClient.RequestMoreItemsException {
    final MockWebServer server = new MockWebServer();

    final String strResponse = getStringFromStream(
            MoreItemsJsonParserTest.class.getClassLoader().getResourceAsStream("test_more_items_response.json"));
    assertNotNull(strResponse);
    server.enqueue(new MockResponse().setBody(strResponse));
    server.start();

    final ZooniverseClient client = createZooniverseClient(server);

    final int COUNT = 10;
    final List<ZooniverseClient.Subject> subjects = client.requestMoreItemsSync(TEST_GROUP_ID, COUNT);
    assertNotNull(subjects);
    assertEquals(COUNT, subjects.size());

    final ZooniverseClient.Subject subject = subjects.get(0);
    assertNotNull(subject);

    assertNotNull(subject.getId());
    assertEquals("16216418", subject.getId());

    // This is apparently always null in the JSON.
    // assertNotNull(subject.getZooniverseId());
    // assertEquals("AGZ00081ls", subject.getZooniverseId());

    // TODO
    // assertNotNull(subject.getGroupId());
    // assertEquals(TEST_GROUP_ID, subject.getGroupId());

    assertNotNull(subject.getLocationStandard());
    assertEquals("https://panoptes-uploads.zooniverse.org/production/subject_location/772f8b1b-b0fe-4dac-9afe-472f3e8d381a.jpeg",
            subject.getLocationStandard());
    /* TODO:
    assertNotNull(subject.getLocationThumbnail());
    assertEquals("http://www.galaxyzoo.org.s3.amazonaws.com/subjects/thumbnail/goods_full_n_27820_thumbnail.jpg",
            subject.getLocationThumbnail());
    assertNotNull(subject.getLocationInverted());
    assertEquals("http://www.galaxyzoo.org.s3.amazonaws.com/subjects/inverted/goods_full_n_27820_inverted.jpg",
            subject.getLocationInverted());
    */


    //Test what the server received:
    assertEquals(1, server.getRequestCount());
    final RecordedRequest request = server.takeRequest();
    assertEquals("GET", request.getMethod());

    //ZooniverseClient uses one of several possible group IDs at random:
    //See com.murrayc.galaxyzoo.app.provider.Config
    // TODO: Use more.  /subjects/queued?http_cache=true&workflow_id=5853fab395ad361930000003&limit=5
    final String possiblePath1 = "/subjects/queued?http_cache=true&workflow_id=" + TEST_GROUP_ID + "&limit=5";
    final String possiblePath2 = "/subjects/queued?http_cache=true&workflow_id=" + Config.SUBJECT_GROUP_ID_GAMA_15 + "&limit=5";

    //TODO: Can we use this?
    // assertThat(request.getPath(), anyOf(is(possiblePath1), is(possiblePath2)));
    final String path = request.getPath();
    assertEquals(possiblePath1, path);
    assertTrue( path.equals(possiblePath1) || path.equals(possiblePath2));

    server.shutdown();
}