Java Code Examples for okhttp3.mockwebserver.RecordedRequest

The following examples show how to use okhttp3.mockwebserver.RecordedRequest. These examples are extracted from open source projects. 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
@Test
void getTransaction() throws InterruptedException {
  // Mock response
  TransactionMessage expectedMessage = createTransactionMessage();
  String mockResponse = "{\n"
      + "    'type': 'in-pool',\n"
      + "    'message': '" + toHex(expectedMessage) + "'\n"
      + "}";
  server.enqueue(new MockResponse().setBody(mockResponse));

  // Call
  HashCode id = HashCode.fromInt(0x00);
  Optional<TransactionResponse> response = exonumClient.getTransaction(id);

  // Assert response
  assertTrue(response.isPresent());
  TransactionResponse actualResponse = response.get();
  assertThat(actualResponse.getStatus(), is(TransactionStatus.IN_POOL));
  assertThat(actualResponse.getMessage(), is(expectedMessage));

  // Assert request params
  RecordedRequest recordedRequest = server.takeRequest();
  assertThat(recordedRequest.getMethod(), is("GET"));
  assertThat(recordedRequest, hasPath("api/explorer/v1/transactions"));
  assertThat(recordedRequest, hasQueryParam("hash", id));
}
 
Example 2
Source Project: auth0-java   Source File: UsersEntityTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldListUsersByEmail() throws Exception {
    Request<List<User>> request = api.users().listByEmail("[email protected]", null);
    assertThat(request, is(notNullValue()));

    server.jsonResponse(MGMT_USERS_LIST, 200);
    List<User> response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();

    assertThat(recordedRequest, hasMethodAndPath("GET", "/api/v2/users-by-email"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));
    assertThat(recordedRequest, hasQueryParameter("email", "[email protected]"));

    assertThat(response, is(notNullValue()));
    assertThat(response, hasSize(2));
}
 
Example 3
@Test
public void testReplaceWithLock() throws Exception {
  server.expect().put().withPath("/api/v1/namespaces/test/configmaps/map1").andReturn(200, new ConfigMapBuilder()
    .withNewMetadata().withResourceVersion("1001").and().build()).once();

  KubernetesClient client = server.getClient();
  ConfigMap map = client.configMaps().withName("map1")
    .lockResourceVersion("900")
    .replace(new ConfigMapBuilder().withNewMetadata().withName("map1").and().build());
  assertNotNull(map);
  assertEquals("1001", map.getMetadata().getResourceVersion());

  RecordedRequest request = server.getLastRequest();
  ConfigMap replacedMap = new ObjectMapper().readerFor(ConfigMap.class).readValue(request.getBody().inputStream());
  assertEquals("900", replacedMap.getMetadata().getResourceVersion());
}
 
Example 4
Source Project: auth0-java   Source File: LogEventsEntityTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldListLogEventsWithPage() throws Exception {
    LogEventFilter filter = new LogEventFilter().withPage(23, 5);
    Request<LogEventsPage> request = api.logEvents().list(filter);
    assertThat(request, is(notNullValue()));

    server.jsonResponse(MGMT_LOG_EVENTS_LIST, 200);
    LogEventsPage response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();

    assertThat(recordedRequest, hasMethodAndPath("GET", "/api/v2/logs"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));
    assertThat(recordedRequest, hasQueryParameter("page", "23"));
    assertThat(recordedRequest, hasQueryParameter("per_page", "5"));

    assertThat(response, is(notNullValue()));
    assertThat(response.getItems(), hasSize(2));
}
 
Example 5
Source Project: auth0-java   Source File: AuthAPITest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldCreateLogInWithAuthorizationCodeGrantRequest() throws Exception {
    AuthRequest request = api.exchangeCode("code123", "https://domain.auth0.com/callback");
    assertThat(request, is(notNullValue()));

    server.jsonResponse(AUTH_TOKENS, 200);
    TokenHolder response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();

    assertThat(recordedRequest, hasMethodAndPath("POST", "/oauth/token"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));

    Map<String, Object> body = bodyFromRequest(recordedRequest);
    assertThat(body, hasEntry("code", (Object) "code123"));
    assertThat(body, hasEntry("redirect_uri", (Object) "https://domain.auth0.com/callback"));
    assertThat(body, hasEntry("grant_type", (Object) "authorization_code"));
    assertThat(body, hasEntry("client_id", (Object) CLIENT_ID));
    assertThat(body, hasEntry("client_secret", (Object) CLIENT_SECRET));

    assertThat(response, is(notNullValue()));
    assertThat(response.getAccessToken(), not(isEmptyOrNullString()));
    assertThat(response.getIdToken(), not(isEmptyOrNullString()));
    assertThat(response.getRefreshToken(), not(isEmptyOrNullString()));
    assertThat(response.getTokenType(), not(isEmptyOrNullString()));
    assertThat(response.getExpiresIn(), is(notNullValue()));
}
 
Example 6
@Test
public void testReplaceWithUserNamesAndGroupsAndOverwriteSubjects() throws Exception {
  server.expect().get().withPath("/apis/authorization.openshift.io/v1/namespaces/test/rolebindings/testrb").andReturn(200, expectedRoleBinding).once();
  server.expect().put().withPath("/apis/authorization.openshift.io/v1/namespaces/test/rolebindings/testrb").andReturn(200, expectedRoleBinding).once();

  NamespacedOpenShiftClient client = server.getOpenshiftClient();

  RoleBinding response = client.roleBindings().withName("testrb").replace(
    new RoleBindingBuilder()
      .withNewMetadata().endMetadata()
      .addToUserNames("testuser1", "testuser2", "system:serviceaccount:test:svcacct")
      .addToGroupNames("testgroup")
      .addNewSubject().withKind("User").withName("unexpected").endSubject()
    .build()
  );
  assertEquals(expectedRoleBinding, response);

  RecordedRequest request = server.getLastRequest();
  assertEquals(expectedRoleBinding, new ObjectMapper().readerFor(RoleBinding.class).readValue(request.getBody().inputStream()));
}
 
Example 7
Source Project: appcenter-plugin   Source File: EnvInterpolationTest.java    License: MIT License 6 votes vote down vote up
@Test
public void should_InterpolateEnv_InReleaseNotes() throws Exception {
    // Given
    MockWebServerUtil.enqueueSuccessWithSymbols(mockWebServer);

    // When
    final FreeStyleBuild freeStyleBuild = freeStyleProject.scheduleBuild2(0).get();

    // Then
    jenkinsRule.assertBuildStatus(Result.SUCCESS, freeStyleBuild);
    mockWebServer.takeRequest();
    mockWebServer.takeRequest();
    mockWebServer.takeRequest();
    mockWebServer.takeRequest();
    mockWebServer.takeRequest();
    mockWebServer.takeRequest();
    final RecordedRequest recordedRequest = mockWebServer.takeRequest();
    assertThat(recordedRequest.getBody().readUtf8()).contains("\"release_notes\":\"I miss you my dear Xiola\\n\\nI prepared the room tonight with Christmas lights.\"");
}
 
Example 8
Source Project: auth0-java   Source File: ClientGrantsEntityTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldUpdateClientGrant() throws Exception {
    Request<ClientGrant> request = api.clientGrants().update("1", new String[]{"openid", "profile"});
    assertThat(request, is(notNullValue()));

    server.jsonResponse(MGMT_CLIENT_GRANT, 200);
    ClientGrant response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();

    assertThat(recordedRequest, hasMethodAndPath("PATCH", "/api/v2/client-grants/1"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));

    Map<String, Object> body = bodyFromRequest(recordedRequest);
    assertThat(body.size(), is(1));
    assertThat((ArrayList<String>) body.get("scope"), contains("openid", "profile"));

    assertThat(response, is(notNullValue()));
}
 
Example 9
Source Project: brave   Source File: RequestSamplingTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before public void setup() {
  server.setDispatcher(new TracingDispatcher(httpTracing, new Dispatcher() {
    OkHttpClient tracedClient = client.newBuilder()
      .addNetworkInterceptor(new TracingInterceptor(httpTracing)).build();

    @Override public MockResponse dispatch(RecordedRequest request) {
      if (request.getPath().equals("/next")) return new MockResponse().setBody("next");
      Call next = tracedClient.newCall(new Request.Builder().url(server.url("/next")).build());
      try (ResponseBody responseBody = next.execute().body()) {
        return new MockResponse().setBody(responseBody.string());
      } catch (IOException e) {
        return new MockResponse().setBody(e.getMessage()).setResponseCode(500);
      }
    }
  }));
}
 
Example 10
Source Project: appcenter-plugin   Source File: DistributeResourceTaskTest.java    License: MIT License 6 votes vote down vote up
@Test
public void should_NotNotifyTesters_When_NotConfigured() throws Exception {
    // Given
    final UploadRequest request = baseRequest.newBuilder().setNotifyTesters(false).build();
    mockWebServer.enqueue(new MockResponse().setResponseCode(200).setBody("{\n" +
        "  \"release_notes\": \"string\"\n" +
        "}"));

    final UploadRequest actual = task.execute(request).get();

    // When
    final RecordedRequest recordedRequest = mockWebServer.takeRequest();

    // Then
    assertThat(recordedRequest.getBody().readUtf8())
        .contains("\"notify_testers\":false");
}
 
Example 11
Source Project: java-sdk   Source File: SpeechToTextTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test get corpus.
 *
 * @throws InterruptedException the interrupted exception
 * @throws FileNotFoundException the file not found exception
 */
@Test
public void testGetCorpus() throws InterruptedException, FileNotFoundException {
  String id = "foo";
  String corpus = "cName";

  server.enqueue(
      new MockResponse().addHeader(CONTENT_TYPE, HttpMediaType.APPLICATION_JSON).setBody("{}"));

  GetCorpusOptions getOptions =
      new GetCorpusOptions.Builder().customizationId(id).corpusName(corpus).build();
  service.getCorpus(getOptions).execute().getResult();
  final RecordedRequest request = server.takeRequest();

  assertEquals("GET", request.getMethod());
  assertEquals(String.format(PATH_CORPUS, id, corpus), request.getPath());
}
 
Example 12
Source Project: auth0-java   Source File: UsersEntityTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldLinkUserIdentityWithConnectionId() throws Exception {
    Request<List<Identity>> request = api.users().linkIdentity("1", "2", "auth0", "123456790");
    assertThat(request, is(notNullValue()));

    server.jsonResponse(MGMT_IDENTITIES_LIST, 200);
    List<Identity> response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();

    assertThat(recordedRequest, hasMethodAndPath("POST", "/api/v2/users/1/identities"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));

    Map<String, Object> body = bodyFromRequest(recordedRequest);
    assertThat(body.size(), is(3));
    assertThat(body, hasEntry("provider", (Object) "auth0"));
    assertThat(body, hasEntry("user_id", (Object) "2"));
    assertThat(body, hasEntry("connection_id", (Object) "123456790"));

    assertThat(response, is(notNullValue()));
}
 
Example 13
Source Project: java-sdk   Source File: DiscoveryServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Delete credentials is successful.
 *
 * @throws InterruptedException the interrupted exception
 */
@Test
public void deleteCredentialsIsSuccessful() throws InterruptedException {
  server.enqueue(jsonResponse(deleteCredentialsResp));

  DeleteCredentialsOptions options =
      new DeleteCredentialsOptions.Builder()
          .environmentId(environmentId)
          .credentialId("credential_id")
          .build();
  DeleteCredentials response = discoveryService.deleteCredentials(options).execute().getResult();
  RecordedRequest request = server.takeRequest();

  assertEquals(DELETE_CREDENTIALS_PATH, request.getPath());
  assertEquals(DELETE, request.getMethod());
  assertEquals(deleteCredentialsResp.getCredentialId(), response.getCredentialId());
  assertEquals(deleteCredentialsResp.getStatus(), response.getStatus());
}
 
Example 14
Source Project: auth0-java   Source File: RulesEntityTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldNotListRulesWithTotals() throws Exception {
    RulesFilter filter = new RulesFilter().withTotals(true);
    Request<List<Rule>> request = api.rules().list(filter);
    assertThat(request, is(notNullValue()));

    server.jsonResponse(MGMT_RULES_LIST, 200);
    List<Rule> response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();

    assertThat(recordedRequest, hasMethodAndPath("GET", "/api/v2/rules"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));
    assertThat(recordedRequest, not(hasQueryParameter("include_totals")));

    assertThat(response, is(notNullValue()));
    assertThat(response, hasSize(2));
}
 
Example 15
Source Project: auth0-java   Source File: ResourceServerEntityTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldCreateResourceServer() throws Exception {
    Request<ResourceServer> request = api.resourceServers()
            .create(new ResourceServer("https://api.my-company.com/api/v2/"));
    assertThat(request, is(notNullValue()));

    server.jsonResponse(MGMT_RESOURCE_SERVER, 200);
    ResourceServer response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();

    assertThat(recordedRequest, hasMethodAndPath("POST", "/api/v2/resource-servers"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));

    Map<String, Object> body = bodyFromRequest(recordedRequest);
    assertThat(body.size(), is(1));
    assertThat(body, hasEntry("identifier", (Object) "https://api.my-company.com/api/v2/"));

    assertThat(response.getIdentifier(), is("https://api.my-company.com/api/v2/"));
}
 
Example 16
@Test
void getTransactionNotFound() throws InterruptedException {
  // Mock response
  server.enqueue(new MockResponse().setResponseCode(HTTP_NOT_FOUND));

  // Call
  HashCode id = HashCode.fromInt(0x00);
  Optional<TransactionResponse> response = exonumClient.getTransaction(id);

  // Assert response
  assertFalse(response.isPresent());

  // Assert request params
  RecordedRequest recordedRequest = server.takeRequest();
  assertThat(recordedRequest.getMethod(), is("GET"));
  assertThat(recordedRequest, hasPath("api/explorer/v1/transactions"));
  assertThat(recordedRequest, hasQueryParam("hash", id));
}
 
Example 17
Source Project: java-sdk   Source File: LanguageTranslatorTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test get document status.
 *
 * @throws InterruptedException the interrupted exception
 */
@Test
public void testGetDocumentStatus() throws InterruptedException {
  server.enqueue(jsonResponse(documentStatus));
  GetDocumentStatusOptions options =
      new GetDocumentStatusOptions.Builder().documentId("documentId").build();
  DocumentStatus response = service.getDocumentStatus(options).execute().getResult();
  RecordedRequest request = server.takeRequest();

  assertEquals(GET, request.getMethod());
  assertEquals(documentStatus.getWordCount(), response.getWordCount());
  assertEquals(documentStatus.getTarget(), response.getTarget());
  assertEquals(documentStatus.getStatus(), response.getStatus());
  assertEquals(documentStatus.getSource(), response.getSource());
  assertEquals(documentStatus.getModelId(), response.getModelId());
  assertEquals(documentStatus.getFilename(), response.getFilename());
  assertEquals(documentStatus.getCreated(), response.getCreated());
  assertEquals(documentStatus.getCompleted(), response.getCompleted());
  assertEquals(documentStatus.getCharacterCount(), response.getCharacterCount());
  assertEquals(documentStatus.getBaseModelId(), response.getBaseModelId());
  assertEquals(documentStatus.getDocumentId(), response.getDocumentId());
}
 
Example 18
Source Project: auth0-java   Source File: UsersEntityTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldGetUserWithFields() throws Exception {
    UserFilter filter = new UserFilter().withFields("some,random,fields", true);
    Request<User> request = api.users().get("1", filter);
    assertThat(request, is(notNullValue()));

    server.jsonResponse(MGMT_USER, 200);
    User response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();

    assertThat(recordedRequest, hasMethodAndPath("GET", "/api/v2/users/1"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));
    assertThat(recordedRequest, hasQueryParameter("fields", "some,random,fields"));
    assertThat(recordedRequest, hasQueryParameter("include_fields", "true"));

    assertThat(response, is(notNullValue()));
}
 
Example 19
Source Project: tutorials   Source File: EmployeeServiceIntegrationTest.java    License: MIT License 6 votes vote down vote up
@Test
void getEmployeeById() throws Exception {

    Employee mockEmployee = new Employee(100, "Adam", "Sandler", 32, Role.LEAD_ENGINEER);
    mockBackEnd.enqueue(new MockResponse().setBody(MAPPER.writeValueAsString(mockEmployee))
            .addHeader("Content-Type", "application/json"));

    Mono<Employee> employeeMono = employeeService.getEmployeeById(100);

    StepVerifier.create(employeeMono)
            .expectNextMatches(employee -> employee.getRole().equals(Role.LEAD_ENGINEER))
            .verifyComplete();

    RecordedRequest recordedRequest = mockBackEnd.takeRequest();
    assertEquals("GET", recordedRequest.getMethod());
    assertEquals("/employee/100", recordedRequest.getPath());
}
 
Example 20
Source Project: vault   Source File: SyncTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test public void testAssetsInDraft() throws Exception {
  enqueue("assets/locales.json");
  enqueue("assets/types.json");
  enqueue("assets/empty.json");
  sync();

  server.takeRequest(); // ignore locales request
  server.takeRequest(); // ignore content types request
  RecordedRequest request = server.takeRequest(); // analyse empty asset response
  assertThat(request.getPath()).isEqualTo("/spaces/space/environments/master/sync?initial=true");


  List<Asset> assets = vault.fetch(Asset.class).all();

  assertThat(assets).isNotNull();
  assertThat(assets).hasSize(1);

  Asset asset = assets.get(0);
  assertThat(asset).isNotNull();
  assertThat(asset.file()).isNull();
}
 
Example 21
@Test
public void testPatchWithUserNamesAndGroupsAndOverwriteSubjects() throws Exception {
  server.expect().get().withPath("/apis/authorization.openshift.io/v1/namespaces/test/rolebindings/testrb").andReturn(200, new RoleBindingBuilder().addToUserNames("unexpected").build()).once();
  server.expect().patch().withPath("/apis/authorization.openshift.io/v1/namespaces/test/rolebindings/testrb").andReturn(200, expectedRoleBinding).once();

  NamespacedOpenShiftClient client = server.getOpenshiftClient();

  RoleBinding response = client.roleBindings().withName("testrb").patch(
    new RoleBindingBuilder()
      .withNewMetadata().endMetadata()
      .addToUserNames("testuser1", "testuser2", "system:serviceaccount:test:svcacct")
      .addToGroupNames("testgroup")
      .addNewSubject().withKind("User").withName("unexpected").endSubject()
    .build()
  );
  assertEquals(expectedRoleBinding, response);

  RecordedRequest request = server.getLastRequest();
  assertEquals(
    "[{\"op\":\"replace\",\"path\":\"/userNames/0\",\"value\":\"testuser1\"},{\"op\":\"add\",\"path\":\"/userNames/1\",\"value\":\"testuser2\"},{\"op\":\"add\",\"path\":\"/userNames/2\",\"value\":\"system:serviceaccount:test:svcacct\"},{\"op\":\"add\",\"path\":\"/metadata\",\"value\":{}},{\"op\":\"add\",\"path\":\"/groupNames\",\"value\":[\"testgroup\"]},{\"op\":\"add\",\"path\":\"/subjects\",\"value\":[{\"kind\":\"User\",\"name\":\"testuser1\"},{\"kind\":\"User\",\"name\":\"testuser2\"},{\"kind\":\"ServiceAccount\",\"name\":\"svcacct\",\"namespace\":\"test\"},{\"kind\":\"Group\",\"name\":\"testgroup\"}]}]",
    request.getBody().readUtf8()
  );
}
 
Example 22
Source Project: auth0-java   Source File: RecordedRequestMatcher.java    License: MIT License 6 votes vote down vote up
private boolean hasQueryParameter(RecordedRequest item, Description mismatchDescription) {
    String path = item.getPath();
    boolean hasQuery = path.indexOf("?") > 0;
    if (!hasQuery) {
        mismatchDescription.appendText(" query was empty");
        return false;
    }

    String query = path.substring(path.indexOf("?") + 1, path.length());
    String[] parameters = query.split("&");
    for (String p : parameters) {
        if (p.startsWith(String.format("%s=", first))) {
            return true;
        }
    }
    mismatchDescription.appendValueList("Query parameters were {", ", ", "}.", parameters);
    return false;
}
 
Example 23
Source Project: adaptive-alerting   Source File: NotifierTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void message_invokesWebhook() throws Exception {
    // Given a running notifier
    notifier.onApplicationEvent(mock(ApplicationReadyEvent.class));
    // ... and a webhook that responds
    webhook.enqueue(new MockResponse());

    // When a mapped metric is sent in json to the kafka topic
    String json = notifierConfig.objectMapper().writeValueAsString(newMappedMetricData());
    kafka.helper().produceStrings(notifierConfig.getKafkaTopic(), json);

    // Then, the notifier POSTs the json from the message into the webhook
    RecordedRequest webhookRequest = webhook.takeRequest();
    Assertions.assertThat(webhookRequest.getMethod())
            .isEqualTo("POST");
    Assertions.assertThat(webhookRequest.getBody().readUtf8())
            .isEqualTo(json);
}
 
Example 24
Source Project: auth0-java   Source File: UserBlocksEntityTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldGetUserBlocksByIdentifier() throws Exception {
    Request<UserBlocks> request = api.userBlocks().getByIdentifier("username");
    assertThat(request, is(notNullValue()));

    server.jsonResponse(MGMT_USER_BLOCKS, 200);
    UserBlocks response = request.execute();
    RecordedRequest recordedRequest = server.takeRequest();

    assertThat(recordedRequest, hasMethodAndPath("GET", "/api/v2/user-blocks"));
    assertThat(recordedRequest, hasHeader("Content-Type", "application/json"));
    assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken"));
    assertThat(recordedRequest, hasQueryParameter("identifier", "username"));

    assertThat(response, is(notNullValue()));
}
 
Example 25
@Test
@DisplayName("Should update image based in single argument")
void testRolloutUpdateSingleImage() throws InterruptedException {
  // Given
  String imageToUpdate = "nginx:latest";
  server.expect().get().withPath("/api/v1/namespaces/ns1/replicationcontrollers/replicationcontroller1")
    .andReturn(HttpURLConnection.HTTP_OK, getReplicationControllerBuilder().build()).times(3);
  server.expect().patch().withPath("/api/v1/namespaces/ns1/replicationcontrollers/replicationcontroller1")
    .andReturn(HttpURLConnection.HTTP_OK, getReplicationControllerBuilder()
      .editSpec().editTemplate().editSpec().editContainer(0)
      .withImage(imageToUpdate)
      .endContainer().endSpec().endTemplate().endSpec()
      .build()).once();
  KubernetesClient client = server.getClient();

  // When
  ReplicationController replicationController = client.replicationControllers().inNamespace("ns1").withName("replicationcontroller1")
    .rolling().updateImage(imageToUpdate);

  // Then
  assertNotNull(replicationController);
  assertEquals(imageToUpdate, replicationController.getSpec().getTemplate().getSpec().getContainers().get(0).getImage());
  RecordedRequest recordedRequest = server.getLastRequest();
  assertEquals("PATCH", recordedRequest.getMethod());
  assertTrue(recordedRequest.getBody().readUtf8().contains(imageToUpdate));
}
 
Example 26
Source Project: inception   Source File: LappsRecommenderIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
private Dispatcher buildDispatcher()
{
    return new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) {
            try {
                String url = request.getPath();
                String body = request.getBody().readUtf8();

                if (request.getPath().equals("/pos/predict")) {
                    String response = "";
                    return new MockResponse().setResponseCode(200).setBody(response);
                } else {
                    throw new RuntimeException("Invalid URL called: " + url);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    };
}
 
Example 27
Source Project: line-bot-sdk-java   Source File: LineMessagingClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void relativeRequestTest() throws Exception {
    final UserProfileResponse profileResponseMock = UserProfileResponse
            .builder()
            .displayName("name")
            .userId("userId")
            .pictureUrl(URI.create("https://line.me/picture_url"))
            .statusMessage("Status message")
            .language("en")
            .build();

    mockWebServer.enqueue(new MockResponse()
                                  .setResponseCode(200)
                                  .setBody(new ObjectMapper()
                                                   .writeValueAsString(profileResponseMock)));

    // Do
    final UserProfileResponse actualResponse =
            target.getProfile("USER_TOKEN").get();

    // Verify
    final RecordedRequest recordedRequest = mockWebServer.takeRequest();
    assertThat(recordedRequest.getPath())
            .isEqualTo("/CanContainsRelative/v2/bot/profile/USER_TOKEN");
    assertThat(actualResponse).isEqualTo(profileResponseMock);
}
 
Example 28
Source Project: java-sdk   Source File: SpeechToTextTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test list acoustic models.
 *
 * @throws InterruptedException the interrupted exception
 * @throws FileNotFoundException the file not found exception
 */
@Test
public void testListAcousticModels() throws InterruptedException, FileNotFoundException {
  String acousticModelsAsString =
      getStringFromInputStream(
          new FileInputStream("src/test/resources/speech_to_text/acoustic-models.json"));
  JsonObject acousticModels = new JsonParser().parse(acousticModelsAsString).getAsJsonObject();

  server.enqueue(
      new MockResponse()
          .addHeader(CONTENT_TYPE, HttpMediaType.APPLICATION_JSON)
          .setBody(acousticModelsAsString));

  ListAcousticModelsOptions listOptions =
      new ListAcousticModelsOptions.Builder().language("en-us").build();
  AcousticModels result = service.listAcousticModels(listOptions).execute().getResult();
  final RecordedRequest request = server.takeRequest();

  assertEquals("GET", request.getMethod());
  assertEquals(PATH_ACOUSTIC_CUSTOMIZATIONS + "?language=en-us", request.getPath());
  assertEquals(
      acousticModels.get("customizations").getAsJsonArray().size(),
      result.getCustomizations().size());
  assertEquals(acousticModels.get("customizations"), GSON.toJsonTree(result.getCustomizations()));
}
 
Example 29
Source Project: RESTMock   Source File: RequestVerificationException.java    License: Apache License 2.0 6 votes vote down vote up
protected static void appendHistoryRequests(Matcher<RecordedRequest> matcher, List<RecordedRequest> requestHistory, StringBuilder sb) {
    sb.append("\n\nAll invocations: (\"#\" at the beginning means the request was matched)\n[");
    if (!requestHistory.isEmpty()) {
        sb.append("\n");
    }
    for (RecordedRequest recordedRequest : requestHistory) {
        sb.append("\t");
        if (matcher.matches(recordedRequest)) {
            sb.append("# ");
        }
        sb.append(recordedRequest.getRequestLine());
        if (matcher.matches(recordedRequest)) {
            sb.append(" \t| #MATCH");
        }
        sb.append("\n");
    }
    sb.append("]");
}
 
Example 30
Source Project: digdag   Source File: HttpCallIT.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSubTasksByYaml()
        throws Exception
{
    Config bodyConfig = loadYamlResource("acceptance/http_call/child.dig");
    httpMockWebServer.enqueue(
            new MockResponse()
            .addHeader("Content-Type: application/x-yaml")
            .setBody(formatYaml(bodyConfig)));
    String uri = "http://localhost:" + httpMockWebServer.getPort() + "/test";
    runWorkflow(folder, "acceptance/http_call/http_call.dig", ImmutableMap.of(
                "test_uri", uri,
                "outdir", root().toString(),
                "name", "child"));
    assertThat(httpMockWebServer.getRequestCount(), is(1));
    assertThat(Files.exists(root().resolve("child.out")), is(true));
    RecordedRequest request = httpMockWebServer.takeRequest();
    assertThat(request.getMethod(), is("GET"));
}