org.mockserver.model.HttpRequest Java Examples
The following examples show how to use
org.mockserver.model.HttpRequest.
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: HttpClientTest.java From pmq with Apache License 2.0 | 7 votes |
@Test public void getErrorTest() throws IOException { ClientAndServer mockClient = new ClientAndServer(5000); try { mockClient.when(HttpRequest.request().withMethod("GET")) .respond(HttpResponse.response().withStatusCode(700).withBody("1")); HttpClient httpClient = new HttpClient(); boolean rs = false; try { assertEquals("1", httpClient.get("http://localhost:5000/hs")); } catch (Exception e) { rs = true; } assertEquals(true, rs); } finally { mockClient.stop(true); } }
Example #2
Source File: NotificationsTest.java From apollo with Apache License 2.0 | 6 votes |
@Test public void testSlackNotification() throws Exception { ApolloTestClient apolloTestClient = Common.signupAndLogin(); Notification notification = ModelsGenerator.createAndSubmitNotification(apolloTestClient, NotificationType.SLACK, slackNotificationConfiguration); Environment environment = apolloTestClient.getEnvironment(notification.getEnvironmentId()); Service service = apolloTestClient.getService(notification.getServiceId()); DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service); Deployment deployment = ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion); mockSlackServer(); StandaloneApollo.getOrCreateServer().getInstance(ApolloNotifications.class).notify(Deployment.DeploymentStatus.DONE, deployment); waitForRequest(); mockServerClient.verify( HttpRequest.request() .withMethod("POST") .withPath(pseudoUrl), VerificationTimes.exactly(1) ); }
Example #3
Source File: TestTusClient.java From tus-java-client with MIT License | 6 votes |
@Test public void testCreateUploadWithMissingLocationHeader() throws IOException, Exception { mockServer.when(new HttpRequest() .withMethod("POST") .withPath("/files") .withHeader("Tus-Resumable", TusClient.TUS_VERSION) .withHeader("Upload-Length", "10")) .respond(new HttpResponse() .withStatusCode(201) .withHeader("Tus-Resumable", TusClient.TUS_VERSION)); TusClient client = new TusClient(); client.setUploadCreationURL(mockServerURL); TusUpload upload = new TusUpload(); upload.setSize(10); upload.setInputStream(new ByteArrayInputStream(new byte[10])); try { TusUploader uploader = client.createUpload(upload); throw new Exception("unreachable code reached"); } catch(ProtocolException e) { assertEquals(e.getMessage(), "missing upload URL in response for creating upload"); } }
Example #4
Source File: DatadogSecretsDoNotLeakWhenApiCalledFunctionalTest.java From kayenta with Apache License 2.0 | 6 votes |
@Test public void test_that_the_datadog_remote_service_does_not_log_the_api_key_when_getMetrics_is_called() { DatadogMetricDescriptorsResponse mockResponse = new DatadogMetricDescriptorsResponse(); String mockResponseAsString; try { mockResponseAsString = objectMapper.writeValueAsString(mockResponse); } catch (JsonProcessingException e) { throw new RuntimeException("Failed to serialize mock DatadogTimeSeries response"); } mockServerClient .when(HttpRequest.request()) .respond(HttpResponse.response(mockResponseAsString)); DatadogMetricDescriptorsResponse res = datadogRemoteService.getMetrics( API_KEY, APPLICATION_KEY, Instant.now().minus(5, ChronoUnit.MINUTES).toEpochMilli()); assertEquals(mockResponse, res); assertTrue("We expected there to be at least 1 logged message", listAppender.list.size() > 0); assertMessagesDoNotContainSecrets(listAppender.list); }
Example #5
Source File: HealthCheckServiceUnitTest.java From galeb with Apache License 2.0 | 6 votes |
@BeforeClass public static void setupClass() { environmentVariables.set("ENVIRONMENT_NAME", "env1"); environmentVariables.set("ZONE_ID", "zone1"); mockServer = ClientAndServer.startClientAndServer(BACKEND_PORT); mockServer.when(HttpRequest.request() .withMethod("GET") .withPath("/") .withHeaders( Header.header("user-agent", "Galeb_HealthChecker/1.0"), Header.header(NottableString.not("cookie"))) .withKeepAlive(true)) .respond(HttpResponse.response() .withCookie(new Cookie("session", "test-cookie")) .withStatusCode(HttpStatus.OK.value())); mockTCPOnlyServer(); }
Example #6
Source File: LowLatencyMontageClientTest.java From render with GNU General Public License v2.0 | 6 votes |
private void addAcqNextTileResponse(final AcquisitionTileList acquisitionTileList) { final JsonBody responseBody = json(acquisitionTileList.toJson()); mockServer .when( HttpRequest.request() .withMethod("POST") .withPath(getBaseAcquisitionPath() + "/next-tile"), Times.once() ) .respond( HttpResponse.response() .withStatusCode(HttpStatus.SC_OK) .withHeader("Content-Type", responseBody.getContentType()) .withBody(responseBody) ); }
Example #7
Source File: MockServerTestHelper.java From mutual-tls-ssl with Apache License 2.0 | 6 votes |
public MockServerTestHelper(ClientType clientType) { clientAndServer = ClientAndServer.startClientAndServer(8080); mockServerClient = new MockServerClient("127.0.0.1", 8080); mockServerClient .when( HttpRequest.request() .withMethod("GET") .withPath("/api/hello") .withHeader("client-type", clientType.getValue()), Times.unlimited(), TimeToLive.unlimited()) .respond( HttpResponse.response() .withBody("Hello") .withStatusCode(200) ); }
Example #8
Source File: AbstractServletContainerIntegrationTest.java From apm-agent-java with Apache License 2.0 | 6 votes |
public List<JsonNode> getEvents(String eventType) { try { final List<JsonNode> events = new ArrayList<>(); final ObjectMapper objectMapper = new ObjectMapper(); for (HttpRequest httpRequest : mockServerContainer.getClient().retrieveRecordedRequests(request(INTAKE_V2_URL))) { final String bodyAsString = httpRequest.getBodyAsString(); for (String ndJsonLine : bodyAsString.split("\n")) { final JsonNode ndJson = objectMapper.readTree(ndJsonLine); if (ndJson.get(eventType) != null) { // as inferred spans are created only after the profiling session ends // they can leak into another test if (!isInferredSpan(ndJson.get(eventType))) { validateEventMetadata(bodyAsString); } events.add(ndJson.get(eventType)); } } } return events; } catch (IOException e) { throw new RuntimeException(e); } }
Example #9
Source File: HttpClientTest.java From pmq with Apache License 2.0 | 6 votes |
@Test public void postError3Test() throws IOException { ClientAndServer mockClient = new ClientAndServer(5000); try { mockClient.when(HttpRequest.request().withMethod("POST")) .respond(HttpResponse.response().withStatusCode(200).withBody("1")); HttpClient httpClient = new HttpClient(); boolean rs = false; try { assertEquals(1, httpClient.post("http://localhost:5001/hs", "1", TestDemo.class).getT()); } catch (Exception e) { rs = true; } assertEquals(true, rs); } finally { mockClient.stop(true); } }
Example #10
Source File: HttpClientTest.java From pmq with Apache License 2.0 | 6 votes |
@Test public void postError2Test() throws IOException { ClientAndServer mockClient = new ClientAndServer(5000); try { mockClient.when(HttpRequest.request().withMethod("POST")) .respond(HttpResponse.response().withStatusCode(700).withBody("1")); HttpClient httpClient = new HttpClient(); boolean rs = false; try { assertEquals(1, httpClient.post("http://localhost:5000/hs", "1", TestDemo.class).getT()); } catch (Exception e) { rs = true; } assertEquals(true, rs); } finally { mockClient.stop(true); } }
Example #11
Source File: RegistryClientTest.java From titus-control-plane with Apache License 2.0 | 6 votes |
@Test public void missingImageTest() { final String repo = "titusops/alpine"; final String tag = "doesnotexist"; mockServer .when( HttpRequest.request().withPath("/v2/" + repo + "/manifests/" + tag) ).respond(HttpResponse.response() .withStatusCode(HttpResponseStatus.NOT_FOUND.code())); try { registryClient.getImageDigest(repo, tag).timeout(TIMEOUT).block(); } catch (TitusRegistryException e) { assertThat(e.getErrorCode()).isEqualTo(TitusRegistryException.ErrorCode.IMAGE_NOT_FOUND); } }
Example #12
Source File: HttpClientTest.java From pmq with Apache License 2.0 | 6 votes |
@Test public void postError1Test() throws IOException { ClientAndServer mockClient = new ClientAndServer(5000); try { mockClient.when(HttpRequest.request().withMethod("POST")) .respond(HttpResponse.response().withStatusCode(200).withBody("1")); HttpClient httpClient = new HttpClient(); boolean rs = false; try { assertEquals("1", httpClient.post("http://localhost:5001/hs", "1")); } catch (Exception e) { rs = true; } assertEquals(true, rs); } finally { mockClient.stop(true); } }
Example #13
Source File: HttpClientTest.java From pmq with Apache License 2.0 | 6 votes |
@Test public void postErrorTest() throws IOException { ClientAndServer mockClient = new ClientAndServer(5000); try { mockClient.when(HttpRequest.request().withMethod("POST")) .respond(HttpResponse.response().withStatusCode(700).withBody("1")); HttpClient httpClient = new HttpClient(); boolean rs = false; try { assertEquals("1", httpClient.post("http://localhost:5000/hs", "1")); } catch (Exception e) { rs = true; } assertEquals(true, rs); } finally { mockClient.stop(true); } }
Example #14
Source File: HttpClientTest.java From pmq with Apache License 2.0 | 6 votes |
@Test public void getError1Test() throws IOException { ClientAndServer mockClient = new ClientAndServer(5000); try { mockClient.when(HttpRequest.request().withMethod("GET")) .respond(HttpResponse.response().withStatusCode(700).withBody("1")); HttpClient httpClient = new HttpClient(); boolean rs = false; try { assertEquals("1", httpClient.get("http://localhost:50001/hs")); } catch (Exception e) { rs = true; } assertEquals(true, rs); } finally { mockClient.stop(true); } }
Example #15
Source File: LowLatencyMontageClientTest.java From render with GNU General Public License v2.0 | 6 votes |
private void addRenderStackMetaDataResponse() { final String requestPath = getRenderStackRequestPath(); final StackMetaData stackMetaData = new StackMetaData(acquireStackId, null); stackMetaData.setState(StackMetaData.StackState.LOADING); final JsonBody responseBody = json(stackMetaData.toJson()); mockServer .when( HttpRequest.request() .withMethod("GET") .withPath(requestPath), Times.once() ) .respond( HttpResponse.response() .withStatusCode(HttpStatus.SC_OK) .withHeader("Content-Type", responseBody.getContentType()) .withBody(responseBody) ); }
Example #16
Source File: TunnelTest.java From incubator-gobblin with Apache License 2.0 | 5 votes |
@Test(enabled=false, expectedExceptions = SocketException.class) public void mustRefuseConnectionWhenProxyRefuses() throws Exception{ mockServer.when(HttpRequest.request().withMethod("CONNECT").withPath("www.us.apache.org:80")) .respond(HttpResponse.response().withStatusCode(403)); Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT); try { int tunnelPort = tunnel.getPort(); fetchContent(tunnelPort); } finally { tunnel.close(); } }
Example #17
Source File: TunnelTest.java From incubator-gobblin with Apache License 2.0 | 5 votes |
@Test(enabled=false, expectedExceptions = SocketException.class) public void mustRefuseConnectionWhenProxyTimesOut() throws Exception{ mockServer.when(HttpRequest.request().withMethod("CONNECT").withPath("www.us.apache.org:80")) .respond(HttpResponse.response().withDelay(TimeUnit.SECONDS,2).withStatusCode(200)); Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT); try { int tunnelPort = tunnel.getPort(); fetchContent(tunnelPort); } finally { tunnel.close(); } }
Example #18
Source File: TestUtils.java From HubTurbo with GNU Lesser General Public License v3.0 | 5 votes |
/** * Creates a GitHub API v3 request that can be used with MockServer and GitHubClient * * @param method the HTTP request method * @param page the page of the resource being requested * @param repoStringId string version of the repo id * @param repoNumericId numeric version of the repo id returned in the Link header * @param apiSegments segments of the request path after the repo id * @return */ public static HttpRequest createMockServerRequest(String method, int page, String repoStringId, String repoNumericId, String apiSegments) { String repoSegment = page == 1 ? "/repos/" + repoStringId : "/repositories/" + repoNumericId; String path = API_PREFIX + repoSegment + apiSegments; return HttpRequest.request() .withMethod(method) .withPath(path) .withQueryStringParameter("state", "all") .withQueryStringParameter("per_page", "100") .withQueryStringParameter("page", Integer.toString(page)); }
Example #19
Source File: GitLabCommitStatusPublisherTest.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
@Test public void unstable() throws IOException, InterruptedException { AbstractBuild build = mockBuild(GITLAB_CONNECTION_V4, Result.UNSTABLE, "test/project.git"); HttpRequest[] requests = prepareCheckCommitAndUpdateStatusRequests("v4", build, BuildState.failed); performAndVerify(build, false, requests); }
Example #20
Source File: GitLabAcceptMergeRequestPublisherTest.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
private HttpRequest prepareAcceptMergeRequest(String apiLevel, int mergeRequestId) throws UnsupportedEncodingException { return request() .withPath("/gitlab/api/" + apiLevel + "/projects/" + PROJECT_ID + "/merge_requests/" + mergeRequestId + "/merge") .withMethod("PUT") .withHeader("PRIVATE-TOKEN", "secret") .withBody("merge_commit_message=Merge+Request+accepted+by+jenkins+build+success&should_remove_source_branch=false"); }
Example #21
Source File: GitLabCommitStatusPublisherTest.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
@Test public void running_commitNotExists() throws UnsupportedEncodingException { AbstractBuild build = mockBuild(GITLAB_CONNECTION_V4, null, "test/project.git"); HttpRequest updateCommitStatus = prepareUpdateCommitStatusWithSuccessResponse("v4", "test/project", build, BuildState.running); new GitLabCommitStatusPublisher("jenkins", false).prebuild(build, listener); mockServerClient.verify(updateCommitStatus, VerificationTimes.exactly(0)); }
Example #22
Source File: GitLabMessagePublisherTest.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
private HttpRequest prepareSendMessageStatus(final String apiLevel, int mergeRequestId, String body) throws UnsupportedEncodingException { return request() .withPath("/gitlab/api/" + apiLevel + "/projects/" + PROJECT_ID + "/merge_requests/" + mergeRequestId + "/notes") .withMethod("POST") .withHeader("PRIVATE-TOKEN", "secret") .withBody("body=" + URLEncoder.encode(body, "UTF-8")); }
Example #23
Source File: TestTusUploader.java From tus-java-client with MIT License | 5 votes |
@Test public void testTusUploader() throws IOException, ProtocolException { byte[] content = "hello world".getBytes(); mockServer.when(new HttpRequest() .withPath("/files/foo") .withHeader("Tus-Resumable", TusClient.TUS_VERSION) .withHeader("Upload-Offset", "3") .withHeader("Content-Type", "application/offset+octet-stream") .withHeader(isOpenJDK6 ? "": "Expect: 100-continue") .withBody(Arrays.copyOfRange(content, 3, 11))) .respond(new HttpResponse() .withStatusCode(204) .withHeader("Tus-Resumable", TusClient.TUS_VERSION) .withHeader("Upload-Offset", "11")); TusClient client = new TusClient(); URL uploadUrl = new URL(mockServerURL + "/foo"); TusInputStream input = new TusInputStream(new ByteArrayInputStream(content)); long offset = 3; TusUpload upload = new TusUpload(); TusUploader uploader = new TusUploader(client, upload, uploadUrl, input, offset); uploader.setChunkSize(5); assertEquals(uploader.getChunkSize(), 5); assertEquals(5, uploader.uploadChunk()); assertEquals(3, uploader.uploadChunk(5)); assertEquals(-1, uploader.uploadChunk()); assertEquals(-1, uploader.uploadChunk(5)); assertEquals(11, uploader.getOffset()); uploader.finish(); }
Example #24
Source File: GitLabCommitStatusPublisherTest.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
@Test public void success_v4() throws IOException, InterruptedException { AbstractBuild build = mockBuild(GITLAB_CONNECTION_V4, Result.SUCCESS, "test/project.git"); HttpRequest[] requests = prepareCheckCommitAndUpdateStatusRequests("v4", build, BuildState.success); performAndVerify(build, false, requests); }
Example #25
Source File: ExpectationCallbackHandler.java From tutorials with MIT License | 5 votes |
public HttpResponse handle(HttpRequest httpRequest) { if (httpRequest.getPath().getValue().endsWith("/callback")) { return httpResponse; } else { return notFoundResponse(); } }
Example #26
Source File: GitLabCommitStatusPublisherTest.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
@Test public void failedWithLibrary() throws IOException, InterruptedException { AbstractBuild build = mockBuildWithLibrary(GITLAB_CONNECTION_V4, Result.FAILURE, "test/project.git"); HttpRequest[] requests = prepareCheckCommitAndUpdateStatusRequests("v4", build, BuildState.failed); performAndVerify(build, false, requests); }
Example #27
Source File: UrlGetCollectorTest.java From monsoon with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test(timeout = 10000) public void scrape() throws Exception { final HttpRequest REQUEST = HttpRequest.request("/scrape") .withMethod("GET"); final UrlGetCollector collector = endpoint("/scrape"); mockServerClient .when(REQUEST) .respond(HttpResponse.response("chocoladevla") .withHeader("Test-Header", "Test-Response") .withHeader("Double-Value", "17.1")); Collection<MetricGroup> groups = GroupGenerator.deref(collector.getGroups(threadpool, new CompletableFuture<>())); mockServerClient.verify(REQUEST, VerificationTimes.once()); assertThat(groups.stream().map(MetricGroup::getName).collect(Collectors.toList()), Matchers.contains(GroupName.valueOf("test"))); // Verify data in test_group. final Map<MetricName, MetricValue> metrics = Arrays.stream(groups.stream() .filter(mg -> mg.getName().equals(GroupName.valueOf("test"))) .findFirst() .get() .getMetrics() ) .collect(Collectors.toMap(Metric::getName, Metric::getValue)); System.err.println(metrics); assertThat(metrics, allOf( hasEntry(MetricName.valueOf("up"), MetricValue.TRUE), hasEntry(MetricName.valueOf("header", "Test-Header"), MetricValue.fromStrValue("Test-Response")), hasEntry(MetricName.valueOf("header", "Double-Value"), MetricValue.fromDblValue(17.1)), hasEntry(MetricName.valueOf("content", "length"), MetricValue.fromIntValue(12)), hasEntry(MetricName.valueOf("content", "type"), MetricValue.fromStrValue("text/plain")), hasEntry(MetricName.valueOf("status", "code"), MetricValue.fromIntValue(200)), not(hasKey(MetricName.valueOf("body"))))); }
Example #28
Source File: UrlJsonCollectorTest.java From monsoon with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test(timeout = 10000) public void scrape() throws Exception { final HttpRequest REQUEST = HttpRequest.request("/json_scrape") .withMethod("GET"); final UrlJsonCollector collector = endpoint("/json_scrape"); mockServerClient .when(REQUEST) .respond(HttpResponse.response(JSON)); Collection<MetricGroup> groups = GroupGenerator.deref(collector.getGroups(threadpool, new CompletableFuture<>())); mockServerClient.verify(REQUEST, VerificationTimes.once()); assertThat(groups.stream().map(MetricGroup::getName).collect(Collectors.toList()), Matchers.contains(GroupName.valueOf("test"))); // Verify data in test_group. final Map<MetricName, MetricValue> metrics = Arrays.stream(groups.stream() .filter(mg -> mg.getName().equals(GroupName.valueOf("test"))) .findFirst() .get() .getMetrics() ) .collect(Collectors.toMap(Metric::getName, Metric::getValue)); System.err.println(metrics); assertThat(metrics, allOf( hasEntry(MetricName.valueOf("up"), MetricValue.TRUE), hasEntry(MetricName.valueOf("body", "bool"), MetricValue.TRUE), hasEntry(MetricName.valueOf("body", "int"), MetricValue.fromIntValue(7)), hasEntry(MetricName.valueOf("body", "dbl"), MetricValue.fromDblValue(3.1415)), hasEntry(MetricName.valueOf("body", "str"), MetricValue.fromStrValue("foobar")), hasEntry(MetricName.valueOf("body", "map", "key"), MetricValue.fromStrValue("value")), hasEntry(MetricName.valueOf("body", "list", "0"), MetricValue.fromStrValue("item")), hasEntry(MetricName.valueOf("content", "type"), MetricValue.fromStrValue("text/plain")), hasEntry(MetricName.valueOf("status", "code"), MetricValue.fromIntValue(200)))); }
Example #29
Source File: LinkExplorerTest.java From timbuctoo with GNU General Public License v3.0 | 5 votes |
@Test public void findLinksInHeader() throws Exception { String path = "/foo/bar/page2.html"; getMockServer() .when(HttpRequest.request() .withMethod("GET") .withPath(path), Times.exactly(1)) .respond(HttpResponse.response() .withStatusCode(200) .withHeader("Link", "<http://www.example.com/dataset1/capabilitylist.xml>; rel=\"resourcesync\"") .withHeader("Link", "</dataset2/capabilitylist.xml>; rel=\"resourcesync\"") .withHeader("Content-Type", "text/html; charset=utf-8") .withBody(createValidHtml()) ); LinkExplorer explorer = new LinkExplorer(getHttpclient(), getRsContext(), LinkExplorer.linkReader); ResultIndex index = new ResultIndex(); Result<LinkList> result = explorer.explore(composeUri(path), index, null); result.getErrors().forEach(Throwable::printStackTrace); assertThat(result.getErrors().isEmpty(), is(true)); assertThat(result.getContent().isPresent(), is(true)); LinkList linkList = result.getContent().orElse(new LinkList()); Set<URI> validUris = linkList.getValidUris(); assertThat(validUris, containsInAnyOrder( composeUri("dataset2/capabilitylist.xml"), URI.create("http://www.example.com/dataset1/capabilitylist.xml"))); assertThat(linkList.getInvalidUris().size(), equalTo(0)); assertThat(index.contains(composeUri(path)), is(true)); }
Example #30
Source File: GitLabMessagePublisherTest.java From gitlab-plugin with GNU General Public License v2.0 | 5 votes |
private void performAndVerify(AbstractBuild build, String note, boolean onlyForFailure, boolean replaceSuccessNote, boolean replaceFailureNote, boolean replaceAbortNote, boolean replaceUnstableNote, HttpRequest... requests) throws InterruptedException, IOException { String successNoteText = replaceSuccessNote ? note : null; String failureNoteText = replaceFailureNote ? note : null; String abortNoteText = replaceAbortNote ? note : null; String unstableNoteText = replaceUnstableNote ? note : null; GitLabMessagePublisher publisher = preparePublisher(new GitLabMessagePublisher(onlyForFailure, replaceSuccessNote, replaceFailureNote, replaceAbortNote, replaceUnstableNote, successNoteText, failureNoteText, abortNoteText, unstableNoteText), build); publisher.perform(build, null, listener); if (requests.length > 0) { mockServerClient.verify(requests); } else { mockServerClient.verifyZeroInteractions(); } }