okhttp3.mockwebserver.RecordedRequest Java Examples

The following examples show how to use okhttp3.mockwebserver.RecordedRequest. 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: OpenshiftRoleBindingTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: OpenshiftRoleBindingTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@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 File: EnvInterpolationTest.java    From appcenter-plugin with 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 #5
Source File: UsersEntityTest.java    From auth0-java with 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 #6
Source File: SpeechToTextTest.java    From java-sdk with 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 #7
Source File: UsersEntityTest.java    From auth0-java with 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 #8
Source File: DiscoveryServiceTest.java    From java-sdk with 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 #9
Source File: RulesEntityTest.java    From auth0-java with 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 #10
Source File: ResourceServerEntityTest.java    From auth0-java with 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 #11
Source File: ExonumHttpClientIntegrationTest.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: LanguageTranslatorTest.java    From java-sdk with 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 #13
Source File: UsersEntityTest.java    From auth0-java with 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 #14
Source File: EmployeeServiceIntegrationTest.java    From tutorials with 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 #15
Source File: SyncTest.java    From vault with 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 #16
Source File: ExonumHttpClientIntegrationTest.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
@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 #17
Source File: RecordedRequestMatcher.java    From auth0-java with 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 #18
Source File: NotifierTest.java    From adaptive-alerting with 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 #19
Source File: UserBlocksEntityTest.java    From auth0-java with 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 #20
Source File: ReplicationControllerTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@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 #21
Source File: LappsRecommenderIntegrationTest.java    From inception with 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 #22
Source File: LineMessagingClientTest.java    From line-bot-sdk-java with 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 #23
Source File: SpeechToTextTest.java    From java-sdk with 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 #24
Source File: RequestVerificationException.java    From RESTMock with 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 #25
Source File: HttpCallIT.java    From digdag with 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"));
}
 
Example #26
Source File: OpenshiftRoleBindingTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testReplaceWithOnlySubjects() 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()
      .addNewSubject().withKind("User").withName("testuser1").endSubject()
      .addNewSubject().withKind("User").withName("testuser2").endSubject()
      .addNewSubject().withKind("ServiceAccount").withName("svcacct").endSubject()
      .addNewSubject().withKind("Group").withName("testgroup").endSubject()
      .build()
  );
  assertEquals(expectedRoleBinding, response);

  RecordedRequest request = server.getLastRequest();
  assertEquals(expectedRoleBinding, new ObjectMapper().readerFor(RoleBinding.class).readValue(request.getBody().inputStream()));
}
 
Example #27
Source File: ApacheHttp5ClientTest.java    From feign with Apache License 2.0 6 votes vote down vote up
@Test
public void queryParamsAreRespectedWhenBodyIsEmpty() throws InterruptedException {
  final HttpClient httpClient = HttpClientBuilder.create().build();
  final JaxRsTestInterface testInterface = Feign.builder()
      .contract(new JAXRSContract())
      .client(new ApacheHttp5Client(httpClient))
      .target(JaxRsTestInterface.class, "http://localhost:" + server.getPort());

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

  assertEquals("foo", testInterface.withBody("foo", "bar"));
  final RecordedRequest request1 = server.takeRequest();
  assertEquals("/withBody?foo=foo", request1.getPath());
  assertEquals("bar", request1.getBody().readString(StandardCharsets.UTF_8));

  assertEquals("foo", testInterface.withoutBody("foo"));
  final RecordedRequest request2 = server.takeRequest();
  assertEquals("/withoutBody?foo=foo", request2.getPath());
  assertEquals("", request2.getBody().readString(StandardCharsets.UTF_8));
}
 
Example #28
Source File: TestHttpNotificationServiceCommon.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartNotification() throws ParserConfigurationException, SAXException, IOException, InterruptedException {
    mockWebServer.enqueue(new MockResponse().setResponseCode(200));

    NotificationServiceManager notificationServiceManager = new NotificationServiceManager();
    notificationServiceManager.setMaxNotificationAttempts(1);
    notificationServiceManager.loadNotificationServices(new File(tempConfigFilePath));
    notificationServiceManager.registerNotificationService(NotificationType.NIFI_STARTED, "http-notification");
    notificationServiceManager.notify(NotificationType.NIFI_STARTED, "Subject", "Message");

    RecordedRequest recordedRequest = mockWebServer.takeRequest(2, TimeUnit.SECONDS);
    assertNotNull(recordedRequest);
    assertEquals(NotificationType.NIFI_STARTED.name(), recordedRequest.getHeader(NOTIFICATION_TYPE_KEY));
    assertEquals("Subject", recordedRequest.getHeader(NOTIFICATION_SUBJECT_KEY));
    assertEquals("testing", recordedRequest.getHeader("testProp"));

    Buffer bodyBuffer = recordedRequest.getBody();
    String bodyString =new String(bodyBuffer.readByteArray(), UTF_8);
    assertEquals("Message", bodyString);
}
 
Example #29
Source File: VisualRecognitionTest.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Test delete classifier.
 *
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws InterruptedException the interrupted exception
 */
@Test
public void testDeleteClassifier() throws IOException, InterruptedException {
  server.enqueue(new MockResponse().setBody(""));

  String class1 = "class1";
  DeleteClassifierOptions options = new DeleteClassifierOptions.Builder(class1).build();
  service.deleteClassifier(options).execute();

  // first request
  RecordedRequest request = server.takeRequest();
  String path = String.format(PATH_CLASSIFIER + "?" + VERSION_KEY + "=" + VERSION, class1);

  assertEquals(path, request.getPath());
  assertEquals("DELETE", request.getMethod());
}
 
Example #30
Source File: SpeechToTextTest.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Test train acoustic model.
 *
 * @throws InterruptedException the interrupted exception
 * @throws FileNotFoundException the file not found exception
 */
@Test
public void testTrainAcousticModel() throws InterruptedException, FileNotFoundException {
  server.enqueue(
      new MockResponse().addHeader(CONTENT_TYPE, HttpMediaType.APPLICATION_JSON).setBody("{}"));
  String id = "foo";
  String languageModelId = "bar";

  TrainAcousticModelOptions trainOptions =
      new TrainAcousticModelOptions.Builder()
          .customizationId(id)
          .customLanguageModelId(languageModelId)
          .build();
  service.trainAcousticModel(trainOptions).execute().getResult();
  final RecordedRequest request = server.takeRequest();

  assertEquals("POST", request.getMethod());
  assertEquals(
      String.format(PATH_ACOUSTIC_TRAIN, id) + "?custom_language_model_id=bar",
      request.getPath());
}