com.github.tomakehurst.wiremock.stubbing.Scenario Java Examples
The following examples show how to use
com.github.tomakehurst.wiremock.stubbing.Scenario.
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: ChecksumResetsOnRetryTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
private void stubSuccessAfterOneRetry(Consumer<ResponseDefinitionBuilder> successfulResponseModifier) { WireMock.reset(); String scenario = "stubSuccessAfterOneRetry"; stubFor(any(anyUrl()) .willReturn(aResponse().withStatus(500).withBody("<xml></xml>")) .inScenario(scenario) .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("200")); ResponseDefinitionBuilder successfulResponse = aResponse().withStatus(200).withBody("<xml></xml>"); successfulResponseModifier.accept(successfulResponse); stubFor(any(anyUrl()) .willReturn(successfulResponse) .inScenario(scenario) .whenScenarioStateIs("200")); }
Example #2
Source File: ConfigServerRestExecutorImplTest.java From vespa with Apache License 2.0 | 6 votes |
private void stubRequests(String path) { String retryScenario = "Retry scenario"; String retryRequest = "Retry request 1"; String retryRequestAgain = "Retry request 2"; wireMock.stubFor(get(urlEqualTo(path)).inScenario(retryScenario) .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo(retryRequest) .willReturn(aResponse().withStatus(500))); wireMock.stubFor(get(urlEqualTo(path)).inScenario(retryScenario) .whenScenarioStateIs(retryRequest) .willSetStateTo(retryRequestAgain) .willReturn(aResponse().withStatus(500))); wireMock.stubFor(get(urlEqualTo(path)).inScenario(retryScenario) .whenScenarioStateIs(retryRequestAgain) .willReturn(aResponse().withBody("OK"))); }
Example #3
Source File: InstanceMetadataServiceResourceFetcherTest.java From ibm-cos-sdk-java with Apache License 2.0 | 6 votes |
private void generateRetrySucceedTokenStub() { stubFor( put(urlPathEqualTo(TOKEN_PATH)) .withHeader("User-Agent", equalTo(VersionInfoUtils.getUserAgent())) .inScenario("retry at 503") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(503))); stubFor( put(urlPathEqualTo(TOKEN_PATH)) .withHeader("User-Agent", equalTo(VersionInfoUtils.getUserAgent())) .inScenario("retry at 503") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody(TOKEN))); }
Example #4
Source File: AwsJsonRetryTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void shouldRetryOnAwsThrottlingErrorCode() { stubFor(post(urlEqualTo(PATH)) .inScenario("retry at SlowDown") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(400) .withHeader("x-amzn-ErrorType", "SlowDown") .withBody("\"{\"__type\":\"SlowDown\",\"message\":\"Blah " + "error\"}\""))); stubFor(post(urlEqualTo(PATH)) .inScenario("retry at SlowDown") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody(JSON_BODY))); AllTypesResponse allTypesResponse = client.allTypes(AllTypesRequest.builder().build()); assertThat(allTypesResponse).isNotNull(); }
Example #5
Source File: AwsJsonRetryTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void shouldRetryOnRetryableAwsErrorCode() { stubFor(post(urlEqualTo(PATH)) .inScenario("retry at PriorRequestNotComplete") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(400) .withHeader("x-amzn-ErrorType", "PriorRequestNotComplete") .withBody("\"{\"__type\":\"PriorRequestNotComplete\",\"message\":\"Blah " + "error\"}\""))); stubFor(post(urlEqualTo(PATH)) .inScenario("retry at PriorRequestNotComplete") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody(JSON_BODY))); AllTypesResponse allTypesResponse = client.allTypes(AllTypesRequest.builder().build()); assertThat(allTypesResponse).isNotNull(); }
Example #6
Source File: AwsJsonRetryTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void shouldRetryOn500() { stubFor(post(urlEqualTo(PATH)) .inScenario("retry at 500") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(500))); stubFor(post(urlEqualTo(PATH)) .inScenario("retry at 500") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody(JSON_BODY))); AllTypesResponse allTypesResponse = client.allTypes(AllTypesRequest.builder().build()); assertThat(allTypesResponse).isNotNull(); }
Example #7
Source File: AsyncAwsJsonRetryTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void shouldRetryOnAwsThrottlingErrorCode() { stubFor(post(urlEqualTo(PATH)) .inScenario("retry at SlowDown") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(400) .withHeader("x-amzn-ErrorType", "SlowDown") .withBody("\"{\"__type\":\"SlowDown\",\"message\":\"Blah " + "error\"}\""))); stubFor(post(urlEqualTo(PATH)) .inScenario("retry at SlowDown") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody(JSON_BODY))); AllTypesResponse allTypesResponse = client.allTypes(AllTypesRequest.builder().build()).join(); assertThat(allTypesResponse).isNotNull(); }
Example #8
Source File: AsyncAwsJsonRetryTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void shouldRetryOnRetryableAwsErrorCode() { stubFor(post(urlEqualTo(PATH)) .inScenario("retry at PriorRequestNotComplete") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(400) .withHeader("x-amzn-ErrorType", "PriorRequestNotComplete") .withBody("\"{\"__type\":\"PriorRequestNotComplete\",\"message\":\"Blah " + "error\"}\""))); stubFor(post(urlEqualTo(PATH)) .inScenario("retry at PriorRequestNotComplete") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody(JSON_BODY))); AllTypesResponse allTypesResponse = client.allTypes(AllTypesRequest.builder().build()).join(); assertThat(allTypesResponse).isNotNull(); }
Example #9
Source File: AsyncAwsJsonRetryTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void shouldRetryOn500() { stubFor(post(urlEqualTo(PATH)) .inScenario("retry at 500") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(500))); stubFor(post(urlEqualTo(PATH)) .inScenario("retry at 500") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody(JSON_BODY))); AllTypesResponse allTypesResponse = client.allTypes(AllTypesRequest.builder().build()).join(); assertThat(allTypesResponse).isNotNull(); }
Example #10
Source File: BaseApiCallTimeoutTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void nonstreamingOperation_retryWouldSucceed_notFinishedWithinTime_shouldTimeout() { stubFor(post(anyUrl()) .inScenario("retry at 500") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(500).withFixedDelay(DELAY_BEFORE_TIMEOUT))); stubFor(post(anyUrl()) .inScenario("retry at 500") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody("{}").withFixedDelay(DELAY_AFTER_TIMEOUT))); verifyRetryableTimeout(); verifyRequestCount(2, wireMock()); }
Example #11
Source File: BaseApiCallTimeoutTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void nonstreamingOperation_retrySucceeded_FinishedWithinTime_shouldNotTimeout() throws Exception { stubFor(post(anyUrl()) .inScenario("retry at 500") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(500).withFixedDelay(DELAY_BEFORE_TIMEOUT))); stubFor(post(anyUrl()) .inScenario("retry at 500") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody("{}").withFixedDelay(DELAY_BEFORE_TIMEOUT))); assertThat(retryableCallable().call()).isNotNull(); }
Example #12
Source File: ClockSkewAdjustmentTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
private void stubForClockSkewFailureThenSuccess(Instant serviceTime, int statusCode, String errorCode) { WireMock.reset(); stubFor(post(urlEqualTo(PATH)) .inScenario(SCENARIO) .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("1") .willReturn(aResponse() .withStatus(statusCode) .withHeader("x-amzn-ErrorType", errorCode) .withHeader("Date", DateUtils.formatRfc1123Date(serviceTime)) .withBody("{}"))); stubFor(post(urlEqualTo(PATH)) .inScenario(SCENARIO) .whenScenarioStateIs("1") .willSetStateTo("2") .willReturn(aResponse() .withStatus(200) .withBody(JSON_BODY))); }
Example #13
Source File: BaseApiCallAttemptTimeoutTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void allAttemtsNotFinishedWithinTime_shouldTimeout() { stubFor(post(anyUrl()) .inScenario("timed out in both attempts") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(200).withFixedDelay(DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT))); stubFor(post(anyUrl()) .inScenario("timed out in both attempts") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody("{}") .withFixedDelay(DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT))); verifyRetryableTimeout(); }
Example #14
Source File: BaseApiCallAttemptTimeoutTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void firstAttemptTimeout_retryFinishWithInTime500_shouldNotTimeout() throws Exception { stubFor(post(anyUrl()) .inScenario("timed out in the first attempt") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(200).withFixedDelay(DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT))); stubFor(post(anyUrl()) .inScenario("timed out in the first attempt") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(500) .withFixedDelay(DELAY_BEFORE_API_CALL_ATTEMPT_TIMEOUT))); verifyRetraybleFailedResponseNotTimedOut(); }
Example #15
Source File: BaseApiCallAttemptTimeoutTest.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
@Test public void firstAttemptTimeout_retryFinishWithInTime_shouldNotTimeout() throws Exception { stubFor(post(anyUrl()) .inScenario("timed out in the first attempt") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(200).withFixedDelay(DELAY_AFTER_API_CALL_ATTEMPT_TIMEOUT))); stubFor(post(anyUrl()) .inScenario("timed out in the first attempt") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody("{}") .withFixedDelay(DELAY_BEFORE_API_CALL_ATTEMPT_TIMEOUT))); assertThat(retryableCallable().call()).isNotNull(); verifyRequestCount(2, wireMock()); }
Example #16
Source File: WireMockScenarioExampleIntegrationTest.java From tutorials with MIT License | 5 votes |
@Test public void changeStateOnEachCallTest() throws IOException { createWireMockStub(Scenario.STARTED, SECOND_STATE, TIP_01); createWireMockStub(SECOND_STATE, THIRD_STATE, TIP_02); createWireMockStub(THIRD_STATE, Scenario.STARTED, TIP_03); assertEquals(TIP_01, nextTip()); assertEquals(TIP_02, nextTip()); assertEquals(TIP_03, nextTip()); assertEquals(TIP_01, nextTip()); }
Example #17
Source File: GitHubSCMSourceTest.java From github-branch-source-plugin with MIT License | 5 votes |
@Test public void fetchSmokesUnknownFork() throws Exception { // make it so PR-2 always returns mergeable = null githubApi.stubFor( get(urlEqualTo("/repos/cloudbeers/yolo/pulls/4")) .inScenario("Pull Request from Deleted Fork") .whenScenarioStateIs(Scenario.STARTED) .willReturn( aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-yolo-pulls-4-deleted-fork.json"))); githubApi.stubFor( get(urlMatching("(/api/v3)?/repos/cloudbeers/yolo/pulls\\?state=open")) .inScenario("Pull Request from Deleted Fork") .whenScenarioStateIs(Scenario.STARTED) .willReturn( aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-yolo-pulls-deleted-fork.json"))); SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch(new SCMSourceCriteria() { @Override public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; } }, collector, null, null); Map<String,SCMHead> byName = new HashMap<>(); Map<String,SCMRevision> revByName = new HashMap<>(); for (Map.Entry<SCMHead, SCMRevision> h: collector.result().entrySet()) { byName.put(h.getKey().getName(), h.getKey()); revByName.put(h.getKey().getName(), h.getValue()); } assertThat(byName.keySet(), hasItem("PR-4")); assertThat(byName.get("PR-4"), instanceOf(PullRequestSCMHead.class)); assertThat(((SCMHeadOrigin.Fork) byName.get("PR-4").getOrigin()).getName(), nullValue()); }
Example #18
Source File: GitHubSCMSourceTest.java From github-branch-source-plugin with MIT License | 5 votes |
@Before public void prepareMockGitHubStubs() throws Exception { new File("src/test/resources/api/mappings").mkdirs(); new File("src/test/resources/api/__files").mkdirs(); githubApi.enableRecordMappings(new SingleRootFileSource("src/test/resources/api/mappings"), new SingleRootFileSource("src/test/resources/api/__files")); githubApi.stubFor( get(urlEqualTo("/repos/cloudbeers/yolo/pulls/2")) .inScenario("Pull Request Merge Hash") .whenScenarioStateIs(Scenario.STARTED) .willReturn( aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-yolo-pulls-2-mergeable-null.json")) .willSetStateTo("Pull Request Merge Hash - retry 1")); githubApi.stubFor( get(urlEqualTo("/repos/cloudbeers/yolo/pulls/2")) .inScenario("Pull Request Merge Hash") .whenScenarioStateIs("Pull Request Merge Hash - retry 1") .willReturn( aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-yolo-pulls-2-mergeable-null.json")) .willSetStateTo("Pull Request Merge Hash - retry 2")); githubApi.stubFor( get(urlEqualTo("/repos/cloudbeers/yolo/pulls/2")) .inScenario("Pull Request Merge Hash") .whenScenarioStateIs("Pull Request Merge Hash - retry 2") .willReturn( aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-yolo-pulls-2-mergeable-true.json")) .willSetStateTo("Pull Request Merge Hash - retry 2")); }
Example #19
Source File: ApiRateLimitCheckerTest.java From github-branch-source-plugin with MIT License | 5 votes |
private void setupStubs(List<RateLimit> scenarios) { String scenarioName = UUID.randomUUID().toString(); for (int i = 0; i < scenarios.size(); i++) { String state = (i == 0) ? Scenario.STARTED : Integer.toString(i); String nextState = Integer.toString(i + 1); RateLimit scenarioResponse = scenarios.get(i); String limit = Integer.toString(scenarioResponse.limit); String remaining = Integer.toString(scenarioResponse.remaining); String reset = Long.toString(scenarioResponse.reset.toInstant().getEpochSecond()); String body = "{" + String.format(" \"rate\": { \"limit\": %s, \"remaining\": %s, \"reset\": %s },", limit, remaining, reset) + " \"resources\": {" + String.format(" \"core\": { \"limit\": %s, \"remaining\": %s, \"reset\": %s },", limit, remaining, reset) + String.format(" \"search\": { \"limit\": %s, \"remaining\": %s, \"reset\": %s },", limit, remaining, reset) + String.format(" \"graphql\": { \"limit\": %s, \"remaining\": %s, \"reset\": %s },", limit, remaining, reset) + String.format(" \"integration_manifest\": { \"limit\": %s, \"remaining\": %s, \"reset\": %s }", limit, remaining, reset) + " } }"; ScenarioMappingBuilder scenario = get(urlEqualTo("/rate_limit")) .inScenario(scenarioName) .whenScenarioStateIs(state) .willReturn(aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withHeader("X-RateLimit-Limit", limit) .withHeader("X-RateLimit-Remaining", remaining) .withHeader("X-RateLimit-Reset", reset) .withBody(body) ); if (i != scenarios.size() - 1) { scenario = scenario.willSetStateTo(nextState); } githubApi.stubFor(scenario); } }
Example #20
Source File: RestSwaggerConnectorIntegrationTest.java From syndesis with Apache License 2.0 | 5 votes |
@Test public void shouldRefreshOAuthTokenOnHttpStatus() throws Exception { wiremock.givenThat(post("/oauth/authorize").inScenario("oauth-retry") .withRequestBody(equalTo("refresh_token=refresh-token&grant_type=refresh_token")) .willReturn(ok() .withBody("{\"access_token\":\"refreshed-token\"}")) .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("Expecting request")); wiremock.givenThat(get("/v2/pet/123").inScenario("oauth-retry") .withHeader("Authorization", equalTo("Bearer refreshed-token")) .willReturn(status(401)) .whenScenarioStateIs("Expecting request") .willSetStateTo("Expecting retry")); wiremock.givenThat(post("/oauth/authorize").inScenario("oauth-retry") .withRequestBody(equalTo("refresh_token=refresh-token&grant_type=refresh_token")) .willReturn(ok() .withBody("{\"access_token\":\"new-token\"}")) .whenScenarioStateIs("Expecting retry") .willSetStateTo("Retried")); wiremock.givenThat(get("/v2/pet/123").inScenario("oauth-retry") .withHeader("Authorization", equalTo("Bearer new-token")) .willReturn(ok(DOGGIE) .withHeader("Content-Type", "application/json")) .whenScenarioStateIs("Retried")); assertThat(context.createProducerTemplate().requestBody("direct:oauth-retry", "{\"parameters\":{\"petId\":\"123\"}}", String.class)) .isEqualTo(DOGGIE); wiremock.verify(getRequestedFor(urlEqualTo("/v2/pet/123")) .withHeader("Authorization", equalTo("Bearer new-token")) .withRequestBody(WireMock.equalTo(""))); }
Example #21
Source File: BatchGetTestUtils.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
static void stubResponseWithUnprocessedKeys() { stubFor(post(anyUrl()) .inScenario("unprocessed keys") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse().withStatus(200) .withBody(RESPONSE_WITH_UNPROCESSED_KEYS))); stubFor(post(anyUrl()) .inScenario("unprocessed keys") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse().withStatus(200) .withBody(RESPONSE_WITH_UNPROCESSED_KEYS_PROCESSED))); }
Example #22
Source File: AwsJsonRetryTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test public void retryPolicyNone_shouldNotRetry() { stubFor(post(urlEqualTo(PATH)) .inScenario("retry at 500") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(500))); stubFor(post(urlEqualTo(PATH)) .inScenario("retry at 500") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody(JSON_BODY))); ProtocolJsonRpcClient clientWithNoRetry = ProtocolJsonRpcClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .overrideConfiguration(c -> c.retryPolicy(RetryPolicy.none())) .build(); assertThatThrownBy(() -> clientWithNoRetry.allTypes(AllTypesRequest.builder().build())).isInstanceOf(ProtocolJsonRpcException.class); }
Example #23
Source File: AsyncAwsJsonRetryTest.java From aws-sdk-java-v2 with Apache License 2.0 | 5 votes |
@Test public void retryPolicyNone_shouldNotRetry() { stubFor(post(urlEqualTo(PATH)) .inScenario("retry at 500") .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("first attempt") .willReturn(aResponse() .withStatus(500))); stubFor(post(urlEqualTo(PATH)) .inScenario("retry at 500") .whenScenarioStateIs("first attempt") .willSetStateTo("second attempt") .willReturn(aResponse() .withStatus(200) .withBody(JSON_BODY))); ProtocolJsonRpcAsyncClient clientWithNoRetry = ProtocolJsonRpcAsyncClient.builder() .credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create("akid", "skid"))) .region(Region.US_EAST_1) .endpointOverride(URI.create("http://localhost:" + wireMock.port())) .overrideConfiguration(c -> c.retryPolicy(RetryPolicy.none())) .build(); assertThatThrownBy(() -> clientWithNoRetry.allTypes(AllTypesRequest.builder().build()).join()) .hasCauseInstanceOf(ProtocolJsonRpcException.class); }
Example #24
Source File: ParsecAsyncHttpClientProfilingTest.java From parsec-libraries with Apache License 2.0 | 4 votes |
@Test public void postRequestRetriesShouldBeLogged() throws ExecutionException, InterruptedException { String url = "/postRequestRetriesProfiling"; String headerStr = "postRetriesHost"; String scenarioName = "postRetries"; WireMock.stubFor(post(urlEqualTo(url)).inScenario(scenarioName) .whenScenarioStateIs(Scenario.STARTED) .willSetStateTo("requested count 1") .withRequestBody(equalToJson(stubReqBodyJson)) .willReturn(aResponse() .withHeader(ParsecClientDefine.HEADER_CONTENT_LENGTH,"0") .withStatus(500))); WireMock.stubFor(post(urlEqualTo(url)).inScenario(scenarioName) .whenScenarioStateIs("requested count 1") .withRequestBody(equalToJson(stubReqBodyJson)) .willReturn(okJson(stubRespBodyJson) .withHeader(ParsecClientDefine.HEADER_CONTENT_LENGTH, String.valueOf(stubRespBodyJson.length())) )); String requestMethod = HttpMethod.POST; Map<String, Collection<String>> headers = new HashMap<>(); headers.put(ParsecClientDefine.HEADER_HOST, Arrays.asList(headerStr)); ParsecAsyncHttpRequest request = new ParsecAsyncHttpRequest.Builder() .setUrl(wireMockBaseUrl + url) .setHeaders(headers) .setRequestTimeout(COMMON_REQUEST_TIME_OUT) .setMethod(requestMethod) .setMaxRetries(2) .addRetryStatusCode(500) .setBody(stubReqBodyJson).setBodyEncoding("UTF-8").build(); Response response = parsecHttpClient.criticalExecute(request).get(); assertThat(response.getStatus(), equalTo(200)); ArgumentCaptor<ILoggingEvent> loggingEventArgumentCaptor = ArgumentCaptor.forClass(ILoggingEvent.class); then(mockAppender).should(times(2)).doAppend(loggingEventArgumentCaptor.capture()); String loggedFailureMsg = loggingEventArgumentCaptor.getAllValues().get(0).toString(); String failurePatternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr, "0",500, "single"); assertThat(loggedFailureMsg, matchesPattern(failurePatternAsStr)); String successPatternAsStr = createPatternString(requestMethod, request.getUrl(), headerStr, "49", 200, "single\\|retry:500"); String loggedSuccessMsg = loggingEventArgumentCaptor.getAllValues().get(1).toString(); assertThat(loggedSuccessMsg, matchesPattern(successPatternAsStr)); }
Example #25
Source File: GitHubSCMSourceTest.java From github-branch-source-plugin with MIT License | 4 votes |
@Test public void fetchSmokes_badMergeCommit() throws Exception { // make it so the merge commit is not found returns 404 // Causes PR 2 to fall back to null merge_commit_sha githubApi.stubFor( get(urlEqualTo("/repos/cloudbeers/yolo/commits/38814ca33833ff5583624c29f305be9133f27a40")) .inScenario("PR 2 Merge 404") .whenScenarioStateIs(Scenario.STARTED) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-heads-master-notfound.json")) .willSetStateTo(Scenario.STARTED)); SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch(new SCMSourceCriteria() { @Override public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; } }, collector, null, null); Map<String,SCMHead> byName = new HashMap<>(); Map<String,SCMRevision> revByName = new HashMap<>(); for (Map.Entry<SCMHead, SCMRevision> h: collector.result().entrySet()) { byName.put(h.getKey().getName(), h.getKey()); revByName.put(h.getKey().getName(), h.getValue()); } assertThat(byName.keySet(), containsInAnyOrder("PR-2", "PR-3", "PR-4", "master", "stephenc-patch-1")); assertThat(byName.get("PR-2"), instanceOf(PullRequestSCMHead.class)); assertThat(((PullRequestSCMHead)byName.get("PR-2")).isMerge(), is(true)); assertThat(revByName.get("PR-2"), is(new PullRequestSCMRevision((PullRequestSCMHead)(byName.get("PR-2")), "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1", null ))); ((PullRequestSCMRevision)revByName.get("PR-2")).validateMergeHash(); assertThat(byName.get("PR-3"), instanceOf(PullRequestSCMHead.class)); assertThat(((PullRequestSCMHead)byName.get("PR-3")).isMerge(), is(true)); assertThat(((SCMHeadOrigin.Fork) byName.get("PR-3").getOrigin()).getName(), is("stephenc")); assertThat(revByName.get("PR-3"), is(new PullRequestSCMRevision((PullRequestSCMHead)(byName.get("PR-3")), "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1", PullRequestSCMRevision.NOT_MERGEABLE_HASH ))); // validation should fail for this PR. Exception abort = null; try { ((PullRequestSCMRevision)revByName.get("PR-3")).validateMergeHash(); } catch (Exception e) { abort = e; } assertThat(abort, instanceOf(AbortException.class)); assertThat(abort.getMessage(), containsString("Not mergeable")); assertThat(byName.get("PR-4"), instanceOf(PullRequestSCMHead.class)); assertThat(((SCMHeadOrigin.Fork) byName.get("PR-4").getOrigin()).getName(), is("stephenc/jenkins-58450")); assertThat(byName.get("master"), instanceOf(BranchSCMHead.class)); assertThat(revByName.get("master"), hasProperty("hash", is("8f1314fc3c8284d8c6d5886d473db98f2126071c") )); assertThat(byName.get("stephenc-patch-1"), instanceOf(BranchSCMHead.class)); assertThat(revByName.get("stephenc-patch-1"), hasProperty("hash", is("095e69602bb95a278505e937e41d505ac3cdd263") )); }
Example #26
Source File: GitHubSCMSourceTest.java From github-branch-source-plugin with MIT License | 4 votes |
@Test public void fetchSmokes_badUser() throws Exception { // make it so PR-2 returns a file not found for user githubApi.stubFor( get(urlMatching("(/api/v3)?/repos/cloudbeers/yolo/pulls/2")) .inScenario("Pull Request Merge Hash") .whenScenarioStateIs(Scenario.STARTED) .willReturn( aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-yolo-pulls-2-bad-user.json"))); githubApi.stubFor( get(urlMatching("(/api/v3)?/repos/cloudbeers/yolo/pulls\\?state=open")) .inScenario("Pull Request Merge Hash") .whenScenarioStateIs(Scenario.STARTED) .willReturn( aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-yolo-pulls-bad-user.json"))); SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch(new SCMSourceCriteria() { @Override public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; } }, collector, null, null); Map<String,SCMHead> byName = new HashMap<>(); Map<String,SCMRevision> revByName = new HashMap<>(); for (Map.Entry<SCMHead, SCMRevision> h: collector.result().entrySet()) { byName.put(h.getKey().getName(), h.getKey()); revByName.put(h.getKey().getName(), h.getValue()); } assertThat(byName.keySet(), containsInAnyOrder("PR-3", "PR-4", "master", "stephenc-patch-1")); // PR-2 fails to find user and throws file not found for user. // Caught and handled by removing PR-2 but scan continues. assertThat(byName.get("PR-3"), instanceOf(PullRequestSCMHead.class)); assertThat(((SCMHeadOrigin.Fork) byName.get("PR-3").getOrigin()).getName(), is("stephenc")); assertThat(((PullRequestSCMHead)byName.get("PR-3")).isMerge(), is(true)); assertThat(revByName.get("PR-3"), is(new PullRequestSCMRevision((PullRequestSCMHead)(byName.get("PR-3")), "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1", PullRequestSCMRevision.NOT_MERGEABLE_HASH ))); // validation should fail for this PR. Exception abort = null; try { ((PullRequestSCMRevision)revByName.get("PR-3")).validateMergeHash(); } catch (Exception e) { abort = e; } assertThat(abort, instanceOf(AbortException.class)); assertThat(abort.getMessage(), containsString("Not mergeable")); assertThat(byName.get("PR-4"), instanceOf(PullRequestSCMHead.class)); assertThat(((SCMHeadOrigin.Fork) byName.get("PR-4").getOrigin()).getName(), is("stephenc/jenkins-58450")); assertThat(byName.get("master"), instanceOf(BranchSCMHead.class)); assertThat(revByName.get("master"), hasProperty("hash", is("8f1314fc3c8284d8c6d5886d473db98f2126071c") )); assertThat(byName.get("stephenc-patch-1"), instanceOf(BranchSCMHead.class)); assertThat(revByName.get("stephenc-patch-1"), hasProperty("hash", is("095e69602bb95a278505e937e41d505ac3cdd263") )); }
Example #27
Source File: GitHubSCMSourceTest.java From github-branch-source-plugin with MIT License | 4 votes |
@Test public void fetchSmokes_badTarget() throws Exception { // make it so the merge commit is not found returns 404 // Causes PR 2 to fall back to null merge_commit_sha // Then make it so refs/heads/master returns 404 for first call // Causes PR 2 to fail because it cannot determine base commit. githubApi.stubFor( get(urlMatching("(/api/v3)?/repos/cloudbeers/yolo/commits/38814ca33833ff5583624c29f305be9133f27a40")) .inScenario("PR 2 Merge 404") .whenScenarioStateIs(Scenario.STARTED) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-heads-master-notfound.json")) .willSetStateTo(Scenario.STARTED)); githubApi.stubFor( get(urlMatching("(/api/v3)?/repos/cloudbeers/yolo/git/refs/heads/master")) .inScenario("PR 2 Master 404") .whenScenarioStateIs(Scenario.STARTED) .willReturn( aResponse() .withStatus(404) .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-heads-master-notfound.json")) .willSetStateTo("Master 200")); githubApi.stubFor( get(urlMatching("(/api/v3)?/repos/cloudbeers/yolo/git/refs/heads/master")) .inScenario("PR 2 Master 404") .whenScenarioStateIs("Master 200") .willReturn( aResponse() .withStatus(200) .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-heads-master.json")) .willSetStateTo("Master 200")); SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch(new SCMSourceCriteria() { @Override public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; } }, collector, null, null); Map<String,SCMHead> byName = new HashMap<>(); Map<String,SCMRevision> revByName = new HashMap<>(); for (Map.Entry<SCMHead, SCMRevision> h: collector.result().entrySet()) { byName.put(h.getKey().getName(), h.getKey()); revByName.put(h.getKey().getName(), h.getValue()); } assertThat(byName.keySet(), containsInAnyOrder("PR-3", "PR-4", "master", "stephenc-patch-1")); // PR-2 fails to find master and throws file not found for master. // Caught and handled by removing PR-2 but scan continues. assertThat(byName.get("PR-3"), instanceOf(PullRequestSCMHead.class)); assertThat(((SCMHeadOrigin.Fork) byName.get("PR-3").getOrigin()).getName(), is("stephenc")); assertThat(((PullRequestSCMHead)byName.get("PR-3")).isMerge(), is(true)); assertThat(revByName.get("PR-3"), is(new PullRequestSCMRevision((PullRequestSCMHead)(byName.get("PR-3")), "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1", PullRequestSCMRevision.NOT_MERGEABLE_HASH ))); // validation should fail for this PR. Exception abort = null; try { ((PullRequestSCMRevision)revByName.get("PR-3")).validateMergeHash(); } catch (Exception e) { abort = e; } assertThat(abort, instanceOf(AbortException.class)); assertThat(abort.getMessage(), containsString("Not mergeable")); assertThat(byName.get("PR-4"), instanceOf(PullRequestSCMHead.class)); assertThat(((SCMHeadOrigin.Fork) byName.get("PR-4").getOrigin()).getName(), is("stephenc/jenkins-58450")); assertThat(byName.get("master"), instanceOf(BranchSCMHead.class)); assertThat(revByName.get("master"), hasProperty("hash", is("8f1314fc3c8284d8c6d5886d473db98f2126071c") )); assertThat(byName.get("stephenc-patch-1"), instanceOf(BranchSCMHead.class)); assertThat(revByName.get("stephenc-patch-1"), hasProperty("hash", is("095e69602bb95a278505e937e41d505ac3cdd263") )); }
Example #28
Source File: GitHubSCMSourceTest.java From github-branch-source-plugin with MIT License | 4 votes |
@Test public void fetchSmokesUnknownMergeable() throws Exception { // make it so PR-2 always returns mergeable = null githubApi.stubFor( get(urlEqualTo("/repos/cloudbeers/yolo/pulls/2")) .inScenario("Pull Request Merge Hash") .whenScenarioStateIs(Scenario.STARTED) .willReturn( aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withBodyFile("body-yolo-pulls-2-mergeable-null.json"))); SCMHeadObserver.Collector collector = SCMHeadObserver.collect(); source.fetch(new SCMSourceCriteria() { @Override public boolean isHead(@NonNull Probe probe, @NonNull TaskListener listener) throws IOException { return probe.stat("README.md").getType() == SCMFile.Type.REGULAR_FILE; } }, collector, null, null); Map<String,SCMHead> byName = new HashMap<>(); Map<String,SCMRevision> revByName = new HashMap<>(); for (Map.Entry<SCMHead, SCMRevision> h: collector.result().entrySet()) { byName.put(h.getKey().getName(), h.getKey()); revByName.put(h.getKey().getName(), h.getValue()); } assertThat(byName.keySet(), containsInAnyOrder("PR-2", "PR-3", "PR-4", "master", "stephenc-patch-1")); assertThat(byName.get("PR-2"), instanceOf(PullRequestSCMHead.class)); assertThat(((PullRequestSCMHead)byName.get("PR-2")).isMerge(), is(true)); assertThat(revByName.get("PR-2"), is(new PullRequestSCMRevision((PullRequestSCMHead)(byName.get("PR-2")), "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1", null ))); ((PullRequestSCMRevision)revByName.get("PR-2")).validateMergeHash(); assertThat(byName.get("PR-3"), instanceOf(PullRequestSCMHead.class)); assertThat(((SCMHeadOrigin.Fork) byName.get("PR-3").getOrigin()).getName(), is("stephenc")); assertThat(((PullRequestSCMHead)byName.get("PR-3")).isMerge(), is(true)); assertThat(revByName.get("PR-3"), is(new PullRequestSCMRevision((PullRequestSCMHead)(byName.get("PR-3")), "8f1314fc3c8284d8c6d5886d473db98f2126071c", "c0e024f89969b976da165eecaa71e09dc60c3da1", PullRequestSCMRevision.NOT_MERGEABLE_HASH ))); // validation should fail for this PR. Exception abort = null; try { ((PullRequestSCMRevision)revByName.get("PR-3")).validateMergeHash(); } catch (Exception e) { abort = e; } assertThat(abort, instanceOf(AbortException.class)); assertThat(abort.getMessage(), containsString("Not mergeable")); assertThat(byName.get("PR-4"), instanceOf(PullRequestSCMHead.class)); assertThat(((SCMHeadOrigin.Fork) byName.get("PR-4").getOrigin()).getName(), is("stephenc/jenkins-58450")); assertThat(byName.get("master"), instanceOf(BranchSCMHead.class)); assertThat(revByName.get("master"), hasProperty("hash", is("8f1314fc3c8284d8c6d5886d473db98f2126071c") )); assertThat(byName.get("stephenc-patch-1"), instanceOf(BranchSCMHead.class)); assertThat(revByName.get("stephenc-patch-1"), hasProperty("hash", is("095e69602bb95a278505e937e41d505ac3cdd263") )); }
Example #29
Source File: BoxUserTest.java From box-java-sdk with Apache License 2.0 | 4 votes |
@Test @Category(UnitTest.class) public void testCreateReadAddTrackingCodesSucceeds() throws IOException { final String userID = "12345"; final String departmentID = "8675"; final String companyID = "1701"; final String usersURL = "/users/" + userID; // Mock: Create two tracking codes Map<String, String> createTrackingCodes = new HashMap<String, String>(); createTrackingCodes.put("Employee ID", userID); createTrackingCodes.put("Department ID", departmentID); String createBody = this.trackingCodesJson(createTrackingCodes).toString(); String createResponse = TestConfig.getFixture("BoxUser/CreateTrackingCodes200"); WIRE_MOCK_CLASS_RULE.stubFor(WireMock.put(WireMock.urlPathEqualTo(usersURL)) .withRequestBody(WireMock.equalToJson(createBody)) .willReturn(WireMock.aResponse() .withHeader("Content-Type", "application/json") .withBody(createResponse))); // Mock: Verify change String twoTrackingCodesResponse = TestConfig.getFixture("BoxUser/GetUserTwoTrackingCodes200"); WIRE_MOCK_CLASS_RULE.stubFor(WireMock.get(WireMock.urlPathEqualTo(usersURL)) .withQueryParam("fields", WireMock.equalTo("tracking_codes")) .inScenario("Get Tracking Code Scenario") .whenScenarioStateIs(Scenario.STARTED) .willReturn(WireMock.aResponse() .withHeader("Content-Type", "application/json") .withBody(twoTrackingCodesResponse)) .willSetStateTo("1st Request")); // Mock: Add one more tracking code Map<String, String> appendTrackingCodes = new HashMap<String, String>(); appendTrackingCodes.put("Employee ID", userID); appendTrackingCodes.put("Department ID", departmentID); appendTrackingCodes.put("Company ID", companyID); String updateBody = this.trackingCodesJson(appendTrackingCodes).toString(); String updateResponse = TestConfig.getFixture("BoxUser/UpdateTrackingCodes200"); WIRE_MOCK_CLASS_RULE.stubFor(WireMock.put(WireMock.urlPathEqualTo(usersURL)) .withRequestBody(WireMock.equalToJson(updateBody)) .willReturn(WireMock.aResponse() .withHeader("Content-Type", "application/json") .withBody(updateResponse))); // Mock: Verify change String threeTrackingCodesResponse = TestConfig.getFixture("BoxUser/GetUserThreeTrackingCodes200"); WIRE_MOCK_CLASS_RULE.stubFor(WireMock.get(WireMock.urlPathEqualTo(usersURL)) .withQueryParam("fields", WireMock.equalTo("tracking_codes")) .inScenario("Get Tracking Code Scenario") .whenScenarioStateIs("1st Request") .willReturn(WireMock.aResponse() .withHeader("Content-Type", "application/json") .withBody(threeTrackingCodesResponse)) .willSetStateTo("2nd Request")); // Create two tracking codes BoxUser user = new BoxUser(this.api, userID); BoxUser.Info info = user.new Info(); info.setTrackingCodes(createTrackingCodes); user.updateInfo(info); // Verify change user = new BoxUser(this.api, userID); info = user.getInfo("tracking_codes"); Map<String, String> receivedTrackingCodes = info.getTrackingCodes(); Assert.assertEquals(createTrackingCodes, receivedTrackingCodes); // Add one more tracking code info.appendTrackingCodes("Company ID", companyID); user.updateInfo(info); // Verify change user = new BoxUser(this.api, userID); info = user.getInfo("tracking_codes"); receivedTrackingCodes = info.getTrackingCodes(); Assert.assertEquals(appendTrackingCodes, receivedTrackingCodes); }