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

The following examples show how to use okhttp3.mockwebserver.MockWebServer#shutdown() . 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: EmitterTest.java    From snowplow-android-tracker with Apache License 2.0 6 votes vote down vote up
public void testEmitSinglePostEvent() throws InterruptedException, IOException, JSONException {
    MockWebServer mockServer = getMockServer();
    EmittableEvents emittableEvents = getEmittableEvents(mockServer, 1);
    Emitter emitter = getEmitter(getMockServerURI(mockServer), HttpMethod.POST, BufferOption.DefaultGroup, RequestSecurity.HTTP);

    LinkedList<RequestResult> result = emitter.performAsyncEmit(emitter.buildRequests(emittableEvents));
    assertEquals(1, result.size());
    assertEquals(0, result.getFirst().getEventIds().getFirst().intValue());

    RecordedRequest req = mockServer.takeRequest(2, TimeUnit.SECONDS);
    JSONObject payload = assertPOSTRequest(req);

    JSONArray data = payload.getJSONArray("data");
    assertEquals(1, data.length());
    JSONObject event = data.getJSONObject(0);
    assertEquals(2, event.length());
    assertEquals(0, event.getInt("a"));

    mockServer.shutdown();
}
 
Example 2
Source File: ZooniverseClientTest.java    From android-galaxyzoo with GNU General Public License v3.0 6 votes vote down vote up
@Test
public void testMoreItemsWithBadResponseCode() throws IOException {
    final MockWebServer server = new MockWebServer();

    final MockResponse response = new MockResponse();
    response.setResponseCode(HttpURLConnection.HTTP_NOT_FOUND);
    response.setBody("test nonsense failure message");
    server.enqueue(response);
    server.start();

    final ZooniverseClient client = createZooniverseClient(server);

    //Mostly we want to check that it doesn't crash on a bad HTTP response.

    try {
        final List<ZooniverseClient.Subject> subjects = client.requestMoreItemsSync(TEST_GROUP_ID, 5);
        assertTrue((subjects == null) || (subjects.isEmpty()));
    } catch (final ZooniverseClient.RequestMoreItemsException e) {
        assertNotNull(e.getMessage());
        //assertTrue(e.getCause() instanceof ExecutionException);
    }

    server.shutdown();
}
 
Example 3
Source File: ZkClientFunctionalTest.java    From xio with Apache License 2.0 6 votes vote down vote up
@Test
public void testFromExhibitor() throws Exception {
  MockWebServer server = new MockWebServer();
  server.enqueue(
      new MockResponse()
          .setBody(
              "count=5&server0=10.10.1.1&server1=10.10.1.2&server2=10.10.1.3&server3=10.10.1.4&server4=10.10.1.5&port=2181")
          .setHeader("Content-Type", "application/x-www-form-urlencoded"));
  server.start();
  ZkClient client = ZkClient.fromExhibitor(Arrays.asList("127.0.0.1"), server.getPort());

  assertEquals(
      "10.10.1.1:2181,10.10.1.2:2181,10.10.1.3:2181,10.10.1.4:2181,10.10.1.5:2181",
      client.getConnectionString());
  server.shutdown();
}
 
Example 4
Source File: EmitterTest.java    From snowplow-android-tracker with Apache License 2.0 6 votes vote down vote up
public void testEmitTwoEventsPostAsGroup() throws InterruptedException, IOException, JSONException {
    MockWebServer mockServer = getMockServer();
    EmittableEvents emittableEvents = getEmittableEvents(mockServer, 2);
    Emitter emitter = getEmitter(getMockServerURI(mockServer), HttpMethod.POST, BufferOption.DefaultGroup, RequestSecurity.HTTP);

    LinkedList<RequestResult> result = emitter.performAsyncEmit(emitter.buildRequests(emittableEvents));
    assertEquals(1, result.size());
    assertEquals(0, result.getFirst().getEventIds().getFirst().intValue());
    assertEquals(1, result.getFirst().getEventIds().get(1).intValue());

    RecordedRequest req = mockServer.takeRequest(2, TimeUnit.SECONDS);
    JSONObject payload = assertPOSTRequest(req);

    JSONArray data = payload.getJSONArray("data");
    assertEquals(2, data.length());
    JSONObject event1 = data.getJSONObject(0);
    assertEquals(2, event1.length());
    assertEquals(0, event1.getInt("a"));
    JSONObject event2 = data.getJSONObject(1);
    assertEquals(2, event2.length());
    assertEquals(1, event2.getInt("a"));

    mockServer.shutdown();
}
 
Example 5
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 6
Source File: TrackerTest.java    From snowplow-android-tracker with Apache License 2.0 6 votes vote down vote up
public void testTrackWithoutDataCollection() throws Exception {
    MockWebServer mockWebServer = getMockServer(1);

    Emitter emitter = new Emitter.EmitterBuilder(getMockServerURI(mockWebServer), getContext())
            .option(BufferOption.Single)
            .build();
    emitter.waitForEventStore();

    Tracker tracker = new Tracker.TrackerBuilder(emitter, "myNamespace", "myAppId", getContext())
        .base64(false)
        .level(LogLevel.VERBOSE)
        .sessionContext(false)
        .mobileContext(false)
        .geoLocationContext(false)
        .build();

    tracker.pauseEventTracking();
    tracker.track(ScreenView.builder().build());
    RecordedRequest req = mockWebServer.takeRequest(2, TimeUnit.SECONDS);

    assertEquals(0, tracker.getEmitter().getEventStore().getSize());
    assertNull(req);

    mockWebServer.shutdown();
}
 
Example 7
Source File: TelemetryInterceptorTest.java    From auth0-java with MIT License 6 votes vote down vote up
@Test
public void shouldNotAddTelemetryHeaderIfDisabled() throws Exception {
    TelemetryInterceptor interceptor = new TelemetryInterceptor(telemetry);
    interceptor.setEnabled(false);
    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(nullValue()));

    server.shutdown();
}
 
Example 8
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 9
Source File: HttpZipkinTracerIntegrationTest.java    From zipkin-finagle with Apache License 2.0 5 votes vote down vote up
@Test public void compression() throws Exception {
  http.shutdown(); // shutdown the normal zipkin rule

  // create instructions to create a complete RPC span
  List<Record> records = asList(
      new Record(root, Time.fromMilliseconds(TODAY), new ServiceName("web"), none),
      new Record(root, Time.fromMilliseconds(TODAY), new Rpc("get"), none),
      new Record(root, Time.fromMilliseconds(TODAY), ClientSend$.MODULE$, none),
      new Record(root, Time.fromMilliseconds(TODAY + 1), ClientRecv$.MODULE$, none)
  );

  MockWebServer server = new MockWebServer();
  config = config.toBuilder().host("localhost:" + server.getPort()).build();
  try {
    List<RecordedRequest> requests = new ArrayList<>();
    for (boolean compressionEnabled : asList(true, false)) {
      // recreate the tracer with the compression configuration
      closeTracer();
      config = config.toBuilder().compressionEnabled(compressionEnabled).build();
      createTracer();

      // write a complete span so that it gets reported
      records.forEach(tracer::record);

      // block until the request arrived
      requests.add(server.takeRequest());
    }

    // we expect the first compressed request to be smaller than the uncompressed one.
    assertThat(requests.get(0).getBodySize())
        .isLessThan(requests.get(1).getBodySize());
  } finally {
    server.shutdown();
  }
}
 
Example 10
Source File: HttpZipkinTracerIntegrationTest.java    From zipkin-finagle with Apache License 2.0 5 votes vote down vote up
@Test public void tls() throws Exception {
  http.shutdown(); // shutdown the normal zipkin rule

  // create instructions to create a complete RPC span
  List<Record> records = asList(
      new Record(root, Time.fromMilliseconds(TODAY), new ServiceName("web"), none),
      new Record(root, Time.fromMilliseconds(TODAY), new Rpc("get"), none),
      new Record(root, Time.fromMilliseconds(TODAY), ClientSend$.MODULE$, none),
      new Record(root, Time.fromMilliseconds(TODAY + 1), ClientRecv$.MODULE$, none)
  );

  MockWebServer server = createMockWebServerWithTLS();

  config = config.toBuilder()
      .host("localhost:" + server.getPort())
      .tlsEnabled(true)
      .tlsValidationEnabled(false)
      .build();
  try {
    List<RecordedRequest> requests = new ArrayList<>();

    // recreate the tracer with the tls configuration
    closeTracer();
    createTracer();

    // write a complete span so that it gets reported
    records.forEach(tracer::record);

    // block until the request arrived
    requests.add(server.takeRequest());

    // we expect the request to have a TLS version specified
    assertNotNull(requests.get(0).getTlsVersion());
  } finally {
    server.shutdown();
  }
}
 
Example 11
Source File: StethoInterceptorTest.java    From stetho with MIT License 5 votes vote down vote up
@Test
public void testWithRequestCompression() throws IOException {
  AtomicReference<NetworkEventReporter.InspectorRequest> capturedRequest =
      hookAlmostRealRequestWillBeSent(mMockEventReporter);

  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse()
      .setBody("Success!"));

  final byte[] decompressed = "Request text".getBytes();
  final byte[] compressed = compress(decompressed);
  assertNotEquals(
      "Bogus test: decompressed and compressed lengths match",
      compressed.length, decompressed.length);

  RequestBody compressedBody = RequestBody.create(
      MediaType.parse("text/plain"),
      compress(decompressed));
  Request request = new Request.Builder()
      .url(server.url("/"))
      .addHeader("Content-Encoding", "gzip")
      .post(compressedBody)
      .build();
  Response response = mClientWithInterceptor.newCall(request).execute();

  // Force a read to complete the flow.
  response.body().string();

  assertArrayEquals(decompressed, capturedRequest.get().body());
  Mockito.verify(mMockEventReporter)
      .dataSent(
          anyString(),
          eq(decompressed.length),
          eq(compressed.length));

  server.shutdown();
}
 
Example 12
Source File: StethoInterceptorTest.java    From stetho with MIT License 5 votes vote down vote up
@Test
public void testWithResponseCompression() throws IOException {
  ByteArrayOutputStream capturedOutput = hookAlmostRealInterpretResponseStream(mMockEventReporter);

  byte[] uncompressedData = repeat(".", 1024).getBytes();
  byte[] compressedData = compress(uncompressedData);

  MockWebServer server = new MockWebServer();
  server.start();
  server.enqueue(new MockResponse()
      .setBody(new Buffer().write(compressedData))
      .addHeader("Content-Encoding: gzip"));

  Request request = new Request.Builder()
      .url(server.url("/"))
      .build();
  Response response = mClientWithInterceptor.newCall(request).execute();

  // Verify that the final output and the caller both saw the uncompressed stream.
  assertArrayEquals(uncompressedData, response.body().bytes());
  assertArrayEquals(uncompressedData, capturedOutput.toByteArray());

  // And verify that the StethoInterceptor was able to see both.
  Mockito.verify(mMockEventReporter)
      .dataReceived(
          anyString(),
          eq(compressedData.length),
          eq(uncompressedData.length));

  server.shutdown();
}
 
Example 13
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 14
Source File: ZooniverseClientTest.java    From android-galaxyzoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testProject() throws IOException, ZooniverseClient.RequestProjectException {
    final MockWebServer server = new MockWebServer();

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

    final ZooniverseClient client = createZooniverseClient(server);

    final ZooniverseClient.Project project = client.requestProjectSync("zookeeper/galaxy-zoo");
    assertNotNull(project);

    assertNotNull(project.id());
    assertEquals("5733", project.id());

    assertNotNull(project.displayName());
    assertEquals("Galaxy Zoo", project.displayName());

    final List<String> workflowIds = project.workflowIds();
    assertNotNull(workflowIds);
    assertEquals(5, workflowIds.size());

    final List<String> activeWorkflowIds = project.activeWorkflowIds();
    assertNotNull(activeWorkflowIds);
    assertEquals(1, activeWorkflowIds.size());

    final String activeWorkflowID = activeWorkflowIds.get(0);
    assertNotNull(activeWorkflowID);
    assertEquals("6122", activeWorkflowID);

    server.shutdown();
}
 
Example 15
Source File: EmitterTest.java    From snowplow-android-tracker with Apache License 2.0 5 votes vote down vote up
public void testEmitSingleGetEvent() throws InterruptedException, IOException {
    MockWebServer mockServer = getMockServer();
    EmittableEvents emittableEvents = getEmittableEvents(mockServer, 1);
    Emitter emitter = getEmitter(getMockServerURI(mockServer), HttpMethod.GET, BufferOption.Single, RequestSecurity.HTTP);

    LinkedList<RequestResult> result = emitter.performAsyncEmit(emitter.buildRequests(emittableEvents));
    assertEquals(1, result.size());
    assertEquals(0, result.getFirst().getEventIds().getFirst().intValue());

    RecordedRequest req = mockServer.takeRequest(2, TimeUnit.SECONDS);
    assertGETRequest(req);

    mockServer.shutdown();
}
 
Example 16
Source File: EmitterTest.java    From snowplow-android-tracker with Apache License 2.0 5 votes vote down vote up
public void testEmitTwoEventsPostAsSingles() throws InterruptedException, IOException, JSONException {
    MockWebServer mockServer = getMockServer();
    EmittableEvents emittableEvents = getEmittableEvents(mockServer, 2);
    Emitter emitter = getEmitter(getMockServerURI(mockServer), HttpMethod.POST, BufferOption.Single, RequestSecurity.HTTP);

    LinkedList<RequestResult> result = emitter.performAsyncEmit(emitter.buildRequests(emittableEvents));
    assertEquals(2, result.size());
    assertEquals(0, result.getFirst().getEventIds().getFirst().intValue());
    assertEquals(1, result.get(1).getEventIds().getFirst().intValue());

    // Process first request
    RecordedRequest req = mockServer.takeRequest(2, TimeUnit.SECONDS);
    JSONObject payload = assertPOSTRequest(req);

    JSONArray data1 = payload.getJSONArray("data");
    assertEquals(1, data1.length());
    JSONObject event1 = data1.getJSONObject(0);
    assertEquals(2, event1.length());

    // Process second request
    RecordedRequest req2 = mockServer.takeRequest(2, TimeUnit.SECONDS);
    JSONObject payload2 = assertPOSTRequest(req2);

    JSONArray data2 = payload2.getJSONArray("data");
    assertEquals(1, data2.length());
    JSONObject event2 = data2.getJSONObject(0);
    assertEquals(2, event2.length());

    mockServer.shutdown();
}
 
Example 17
Source File: TrackerTest.java    From snowplow-android-tracker with Apache License 2.0 5 votes vote down vote up
public void testTrackWithSession() throws Exception {
    MockWebServer mockWebServer = getMockServer(1);

    Emitter emitter = new Emitter.EmitterBuilder(getMockServerURI(mockWebServer), getContext())
            .option(BufferOption.Single)
            .build();
    emitter.waitForEventStore();

    Tracker tracker = new Tracker.TrackerBuilder(emitter, "myNamespace", "myAppId", getContext())
        .base64(false)
        .level(LogLevel.VERBOSE)
        .sessionContext(true)
        .mobileContext(false)
        .geoLocationContext(false)
        .foregroundTimeout(5)
        .backgroundTimeout(5)
        .sessionCheckInterval(1)
        .timeUnit(TimeUnit.SECONDS)
        .build();

    assertNotNull(tracker.getSession());
    tracker.resumeSessionChecking();
    Thread.sleep(2000);
    tracker.pauseSessionChecking();

    mockWebServer.shutdown();
}
 
Example 18
Source File: ZooniverseClientTest.java    From android-galaxyzoo with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testUploadWithSuccess() throws IOException, InterruptedException, ZooniverseClient.UploadException {
    final MockWebServer server = new MockWebServer();


    final MockResponse response = new MockResponse();
    response.setResponseCode(HttpURLConnection.HTTP_CREATED);
    response.setBody("TODO");
    server.enqueue(response);
    server.start();

    final ZooniverseClient client = createZooniverseClient(server);

    //SyncAdapter.doUploadSync() adds an "interface" parameter too,
    //but we are testing a more generic API here:
    final List<HttpUtils.NameValuePair> values = new ArrayList<>();
    values.add(new HttpUtils.NameValuePair("classification[subject_ids][]", "504e4a38c499611ea6010c6a"));
    values.add(new HttpUtils.NameValuePair("classification[favorite][]", "true"));
    values.add(new HttpUtils.NameValuePair("classification[annotations][0][sloan-0]", "a-0"));
    values.add(new HttpUtils.NameValuePair("classification[annotations][1][sloan-7]", "a-1"));
    values.add(new HttpUtils.NameValuePair("classification[annotations][2][sloan-5]", "a-0"));
    values.add(new HttpUtils.NameValuePair("classification[annotations][3][sloan-6]", "x-5"));

    final boolean result = client.uploadClassificationSync("testAuthName",
            "testAuthApiKey", TEST_GROUP_ID, values);
    assertTrue(result);

    assertEquals(1, server.getRequestCount());

    //This is really just a regression test,
    //so we notice if something changes unexpectedly:
    final RecordedRequest request = server.takeRequest();
    assertEquals("POST", request.getMethod());
    assertEquals("/workflows/" + TEST_GROUP_ID + "/classifications", request.getPath());
    assertNotNull(request.getHeader("Authorization"));
    assertEquals("application/x-www-form-urlencoded", request.getHeader("Content-Type"));

    final Buffer contents = request.getBody();
    final String strContents = contents.readUtf8();
    assertEquals("classification%5Bsubject_ids%5D%5B%5D=504e4a38c499611ea6010c6a&classification%5Bfavorite%5D%5B%5D=true&classification%5Bannotations%5D%5B0%5D%5Bsloan-0%5D=a-0&classification%5Bannotations%5D%5B1%5D%5Bsloan-7%5D=a-1&classification%5Bannotations%5D%5B2%5D%5Bsloan-5%5D=a-0&classification%5Bannotations%5D%5B3%5D%5Bsloan-6%5D=x-5",
            strContents);

    server.shutdown();
}
 
Example 19
Source File: EmitterTest.java    From snowplow-android-tracker with Apache License 2.0 4 votes vote down vote up
public void testUpdatingEmitterSettings() throws InterruptedException, IOException, JSONException {
    MockWebServer mockServer = getMockServer();
    Emitter emitter = new Emitter.EmitterBuilder(getMockServerURI(mockServer), getContext())
            .option(BufferOption.Single)
            .method(HttpMethod.POST)
            .security(RequestSecurity.HTTP)
            .tick(250)
            .emptyLimit(5)
            .sendLimit(200)
            .byteLimitGet(20000)
            .byteLimitPost(25000)
            .timeUnit(TimeUnit.MILLISECONDS)
            .build();
    emitter.waitForEventStore();
    emitter.getEventStore().removeAllEvents();

    assertFalse(emitter.getEmitterStatus());
    assertEquals(BufferOption.Single, emitter.getBufferOption());
    assertEquals("http://" + getMockServerURI(mockServer) + "/com.snowplowanalytics.snowplow/tp2", emitter.getEmitterUri());
    emitter.setHttpMethod(HttpMethod.GET);
    assertEquals("http://" + getMockServerURI(mockServer) + "/i", emitter.getEmitterUri());
    emitter.setRequestSecurity(RequestSecurity.HTTPS);
    assertEquals("https://" + getMockServerURI(mockServer) + "/i", emitter.getEmitterUri());
    emitter.setEmitterUri("com.acme");
    assertEquals("https://com.acme/i", emitter.getEmitterUri());
    emitter.setBufferOption(BufferOption.HeavyGroup);
    assertEquals(BufferOption.HeavyGroup, emitter.getBufferOption());

    emitter.flush();
    emitter.flush();
    Thread.sleep(500);

    assertTrue(emitter.getEmitterStatus());
    emitter.setHttpMethod(HttpMethod.POST);
    assertEquals("https://com.acme/i", emitter.getEmitterUri());
    emitter.setRequestSecurity(RequestSecurity.HTTP);
    assertEquals("https://com.acme/i", emitter.getEmitterUri());
    emitter.setEmitterUri("com/foo");
    assertEquals("https://com.acme/i", emitter.getEmitterUri());
    emitter.setBufferOption(BufferOption.DefaultGroup);
    assertEquals(BufferOption.HeavyGroup, emitter.getBufferOption());

    emitter.shutdown();

    Emitter customPathEmitter = new Emitter.EmitterBuilder(getMockServerURI(mockServer), getContext())
            .option(BufferOption.Single)
            .method(HttpMethod.POST)
            .security(RequestSecurity.HTTP)
            .tick(250)
            .emptyLimit(5)
            .sendLimit(200)
            .byteLimitGet(20000)
            .byteLimitPost(25000)
            .timeUnit(TimeUnit.MILLISECONDS)
            .customPostPath("com.acme.company/tpx")
            .build();
    assertEquals("com.acme.company/tpx", customPathEmitter.getCustomPostPath());
    assertEquals("http://" + getMockServerURI(mockServer) + "/com.acme.company/tpx", customPathEmitter.getEmitterUri());

    customPathEmitter.shutdown();

    mockServer.shutdown();
}
 
Example 20
Source File: ExternalVolumeTest.java    From marathon-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testExternalVolumes() throws Exception {
    final MockWebServer server = new MockWebServer();
    final String mockResponse = "{\"container\": {\"volumes\": [" +
            "{\"containerPath\":\"/data/db\",\"mode\":\"RW\",\"external\":" +
            "{\"name\":\"mongodb-testvol\",\"provider\":\"dvdi\",\"options\":" +
            "{\"dvdi/driver\":\"rexray\"}}}]}}";

    try {
        server.enqueue(new MockResponse().setBody(mockResponse));
        server.start();
        Marathon client = MarathonClient.getInstance(server.url("/").toString());

        App app = new App();
        app.setId("mongo");
        app.setCpus(1.0);
        app.setMem(256.0);
        app.setContainer(new Container());
        app.getContainer().setDocker(new Docker());
        app.getContainer().getDocker().setImage("mongo");
        app.getContainer().setVolumes(new ArrayList<Volume>());

        ExternalVolume externalVolume = new ExternalVolume();
        externalVolume.setName("mongodb-testvol");
        externalVolume.setMode("RW");
        externalVolume.setContainerPath("/data/db");
        externalVolume.setProvider("dvdi");
        externalVolume.setDriver("rexray");

        app.getContainer().getVolumes().add(externalVolume);

        final App appRes = client.createApp(app);
        assertFalse(appRes.getContainer().getVolumes().isEmpty());

        ExternalVolume responseVolume = (ExternalVolume) appRes.getContainer().getVolumes().iterator().next();
        assertEquals("mongodb-testvol", responseVolume.getExternalVolumeInfo().getName());

        RecordedRequest request = server.takeRequest();
        assertNotNull(request);

        final String requestBody = request.getBody().readUtf8();
        assertNotNull(requestBody);

        // request to JSON
        JsonObject requestPayload = new Gson().fromJson(requestBody, JsonObject.class);
        assertNotNull(requestPayload);
        JsonObject requestVolume = requestPayload.getAsJsonObject("container").getAsJsonArray("volumes").get(0).getAsJsonObject();
        assertNotNull(requestVolume);
        assertEquals("RW", requestVolume.get("mode").getAsString());
        assertEquals("/data/db", requestVolume.get("containerPath").getAsString());
    } finally {
        server.shutdown();
    }
}