Java Code Examples for okhttp3.mockwebserver.RecordedRequest#getHeader()
The following examples show how to use
okhttp3.mockwebserver.RecordedRequest#getHeader() .
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: AbstractMockWebServerTestCase.java From java-technology-stack with MIT License | 6 votes |
private MockResponse postRequest(RecordedRequest request, String expectedRequestContent, String location, String contentType, byte[] responseBody) { assertEquals(1, request.getHeaders().values("Content-Length").size()); assertTrue("Invalid request content-length", Integer.parseInt(request.getHeader("Content-Length")) > 0); String requestContentType = request.getHeader("Content-Type"); assertNotNull("No content-type", requestContentType); Charset charset = StandardCharsets.ISO_8859_1; if (requestContentType.contains("charset=")) { String charsetName = requestContentType.split("charset=")[1]; charset = Charset.forName(charsetName); } assertEquals("Invalid request body", expectedRequestContent, request.getBody().readString(charset)); Buffer buf = new Buffer(); buf.write(responseBody); return new MockResponse() .setHeader("Location", baseUrl + location) .setHeader("Content-Type", contentType) .setHeader("Content-Length", responseBody.length) .setBody(buf) .setResponseCode(201); }
Example 2
Source File: AbstractMockWebServerTestCase.java From spring-analysis-note with MIT License | 6 votes |
private MockResponse postRequest(RecordedRequest request, String expectedRequestContent, String location, String contentType, byte[] responseBody) { assertEquals(1, request.getHeaders().values("Content-Length").size()); assertTrue("Invalid request content-length", Integer.parseInt(request.getHeader("Content-Length")) > 0); String requestContentType = request.getHeader("Content-Type"); assertNotNull("No content-type", requestContentType); Charset charset = StandardCharsets.ISO_8859_1; if (requestContentType.contains("charset=")) { String charsetName = requestContentType.split("charset=")[1]; charset = Charset.forName(charsetName); } assertEquals("Invalid request body", expectedRequestContent, request.getBody().readString(charset)); Buffer buf = new Buffer(); buf.write(responseBody); return new MockResponse() .setHeader("Location", baseUrl + location) .setHeader("Content-Type", contentType) .setHeader("Content-Length", responseBody.length) .setBody(buf) .setResponseCode(201); }
Example 3
Source File: RequestMatchers.java From RESTMock with Apache License 2.0 | 6 votes |
/** * Checks whether matched request contains non-null headers with given names * * @param headerNames names of headers to match * @return A new {@link RequestMatcher} object that will match {@link RecordedRequest} if it * contains specified header names */ public static RequestMatcher hasHeaderNames(final String... headerNames) { return new RequestMatcher("has headers: " + Arrays.toString(headerNames)) { @Override protected boolean matchesSafely(RecordedRequest item) { if (headerNames == null) { throw new IllegalArgumentException("You did not specify any header names"); } if (headerNames.length > 0 && item.getHeaders() == null) { return false; } for (String header : headerNames) { if (item.getHeader(header) == null) { return false; } } return true; } }; }
Example 4
Source File: ClientTest.java From contentful.java with Apache License 2.0 | 5 votes |
@Test @Enqueue public void addingApplicationToCustomHeaderWorks() throws InterruptedException { final CDAClient client = createBuilder() .setApplication("Contentful Java Unit Test", "0.0.1-beta4") .build(); client.fetchSpace(); final RecordedRequest request = server.takeRequest(); final String headerValue = request.getHeader(ContentfulUserAgentHeaderInterceptor.HEADER_NAME); assertThat(headerValue).contains("app contentful-java-unit-test/0.0.1-beta4;"); }
Example 5
Source File: ClientTest.java From contentful.java with Apache License 2.0 | 5 votes |
@Test @Enqueue public void addingIntegrationToCustomHeaderWorks() throws InterruptedException { // use this features if you are using creating a library on top of the sdk. final CDAClient client = createBuilder() .setIntegration("contentful.awesomelib.java", "0.0.1-beta9") .build(); client.fetchSpace(); final RecordedRequest request = server.takeRequest(); final String headerValue = request.getHeader(ContentfulUserAgentHeaderInterceptor.HEADER_NAME); assertThat(headerValue).contains("integration contentful.awesomelib.java/0.0.1-beta9;"); }
Example 6
Source File: AbstractMockWebServerTestCase.java From java-technology-stack with MIT License | 5 votes |
private MockResponse putRequest(RecordedRequest request, String expectedRequestContent) { assertTrue("Invalid request content-length", Integer.parseInt(request.getHeader("Content-Length")) > 0); String requestContentType = request.getHeader("Content-Type"); assertNotNull("No content-type", requestContentType); Charset charset = StandardCharsets.ISO_8859_1; if (requestContentType.contains("charset=")) { String charsetName = requestContentType.split("charset=")[1]; charset = Charset.forName(charsetName); } assertEquals("Invalid request body", expectedRequestContent, request.getBody().readString(charset)); return new MockResponse().setResponseCode(202); }
Example 7
Source File: RequestConfigTest.java From kubernetes-client with Apache License 2.0 | 5 votes |
@Test public void testList() throws InterruptedException { server.expect().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, new PodBuilder() .withNewMetadata() .withName("testPod") .endMetadata() .build()).always(); server.expect().withPath("/api/v1/namespaces/test/pods/pod2").andReturn(200, new PodBuilder() .withNewMetadata() .withName("testPod") .endMetadata() .build()).always(); NamespacedKubernetesClient client = server.getClient(); Pod pod1 = client.withRequestConfig(new RequestConfigBuilder().withOauthToken("TOKEN").build()).call(c -> c.pods().inNamespace("test").withName("pod1").get()); //Let's check that request config actually works RecordedRequest request1 = server.getMockServer().takeRequest(); String authHeader1 = request1.getHeader("Authorization"); assertEquals("Bearer TOKEN", authHeader1); //Let's also check that we didn't pollute client config. Pod pod2 = client.pods().inNamespace("test").withName("pod2").get(); RecordedRequest request2 = server.getMockServer().takeRequest(); String authHeader2 = request2.getHeader("Authorization"); assertNotEquals("Bearer TOKEN", authHeader2); }
Example 8
Source File: AuthenticationTests.java From edx-app-android with Apache License 2.0 | 5 votes |
@Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { MockResponse response = new MockResponse(); String path = request.getPath(); String header = request.getHeader("Authorization"); response.setResponseCode(HttpStatus.NOT_FOUND); try { if (path.equals("/oauth2/access_token/")) { response.setResponseCode(HttpStatus.OK).setBody(MockDataUtil.getMockResponse("post_oauth2_access_token")); } else if (path.equals("/dummy/endpoint/")) { switch (header) { case "expired_token": response.setResponseCode(HttpStatus.UNAUTHORIZED) .addHeader("Authorization", "old_access_token") .setBody(MockDataUtil.getMockResponse("401_expired_token_body")); break; case "Bearer dummy": response.setResponseCode(HttpStatus.OK); break; case "401_not_caused_by_expired_token": response.setResponseCode(HttpStatus.UNAUTHORIZED); break; } } } catch (IOException exception) { exception.printStackTrace(); } return response; }
Example 9
Source File: JobsEntityTest.java From auth0-java with MIT License | 5 votes |
@Test public void shouldRequestUsersImport() throws Exception { File usersFile = new File(MGMT_JOB_POST_USERS_IMPORTS_INPUT); Request<Job> request = api.jobs().importUsers("con_123456789", usersFile, null); assertThat(request, is(notNullValue())); server.jsonResponse(MGMT_JOB_POST_USERS_IMPORTS, 200); Job response = request.execute(); RecordedRequest recordedRequest = server.takeRequest(); assertThat(recordedRequest, hasMethodAndPath("POST", "/api/v2/jobs/users-imports")); assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken")); String ctHeader = recordedRequest.getHeader("Content-Type"); assertThat(ctHeader, startsWith("multipart/form-data")); String[] ctParts = ctHeader.split("multipart/form-data; boundary="); RecordedMultipartRequest recordedMultipartRequest = new RecordedMultipartRequest(recordedRequest); assertThat(recordedMultipartRequest.getPartsCount(), is(2)); assertThat(recordedMultipartRequest.getBoundary(), is(notNullValue())); assertThat(recordedMultipartRequest.getBoundary(), is(ctParts[1])); //Connection ID KeyValuePart formParam = recordedMultipartRequest.getKeyValuePart("connection_id"); assertThat(formParam, is(notNullValue())); assertThat(formParam.getValue(), is("con_123456789")); //Users JSON FilePart jsonFile = recordedMultipartRequest.getFilePart("users"); assertThat(jsonFile, is(notNullValue())); String utf8Contents = new String(Files.readAllBytes(usersFile.toPath())); assertThat(jsonFile.getContentType(), is("text/json")); assertThat(jsonFile.getFilename(), is("job_post_users_imports_input.json")); assertThat(jsonFile.getValue(), is(utf8Contents)); assertThat(response, is(notNullValue())); }
Example 10
Source File: ClientTest.java From contentful.java with Apache License 2.0 | 5 votes |
@Test @Enqueue public void contentfulCustomHeaderUsed() throws InterruptedException { final CDAClient client = createBuilder().build(); client.fetchSpace(); final RecordedRequest request = server.takeRequest(); final String headerValue = request.getHeader(ContentfulUserAgentHeaderInterceptor.HEADER_NAME); assertThat(headerValue).matches("((sdk|platform|os) [.a-zA-Z0-9]+/[.a-zA-Z0-9]+(-.*)?; ?){3}"); }
Example 11
Source File: MarathonRecorderTest.java From marathon-plugin with Apache License 2.0 | 5 votes |
/** * Test a basic API token using StringCredentials. * * @throws Exception */ @Test public void testRecorderBasicToken() throws Exception { final FreeStyleProject project = j.createFreeStyleProject(); final String responseStr = "{\"version\": \"one\", \"deploymentId\": \"someid-here\"}"; final SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class); final CredentialsStore systemStore = system.getStore(j.getInstance()); final String tokenValue = "my secret token"; final Secret secret = Secret.fromString(tokenValue); final StringCredentials credential = new StringCredentialsImpl(CredentialsScope.GLOBAL, "basictoken", "a token for basic token test", secret); TestUtils.enqueueJsonResponse(httpServer, responseStr); systemStore.addCredentials(Domain.global(), credential); // add builders addBuilders(TestUtils.loadFixture("idonly.json"), project); // add post-builder addPostBuilders(project, "basictoken"); final FreeStyleBuild build = j.assertBuildStatusSuccess(project.scheduleBuild2(0).get()); j.assertLogContains("[Marathon]", build); // handler assertions assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount()); RecordedRequest request = httpServer.takeRequest(); final String authorizationText = request.getHeader("Authorization"); assertEquals("Token does not match", "token=" + tokenValue, authorizationText); }
Example 12
Source File: MarathonRecorderTest.java From marathon-plugin with Apache License 2.0 | 5 votes |
/** * Test that a JSON credential with "jenkins_token" uses the token value as the authentication token. * * @throws Exception */ @Test public void testRecorderJSONToken() throws Exception { final FreeStyleProject project = j.createFreeStyleProject(); final String responseStr = "{\"version\": \"one\", \"deploymentId\": \"someid-here\"}"; final SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class); final CredentialsStore systemStore = system.getStore(j.getInstance()); final String tokenValue = "my secret token"; final String credentialValue = "{\"field1\":\"some value\", \"jenkins_token\":\"" + tokenValue + "\"}"; final Secret secret = Secret.fromString(credentialValue); final StringCredentials credential = new StringCredentialsImpl(CredentialsScope.GLOBAL, "jsontoken", "a token for JSON token test", secret); TestUtils.enqueueJsonResponse(httpServer, responseStr); systemStore.addCredentials(Domain.global(), credential); // add builders addBuilders(TestUtils.loadFixture("idonly.json"), project); // add post-builder addPostBuilders(project, "jsontoken"); final FreeStyleBuild build = j.assertBuildStatusSuccess(project.scheduleBuild2(0).get()); j.assertLogContains("[Marathon]", build); // handler assertions assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount()); RecordedRequest request = httpServer.takeRequest(); final String authorizationText = request.getHeader("Authorization"); assertEquals("Token does not match", "token=" + tokenValue, authorizationText); }
Example 13
Source File: JobsEntityTest.java From auth0-java with MIT License | 4 votes |
@Test public void shouldRequestUsersImportWithOptions() throws Exception { UsersImportOptions options = new UsersImportOptions(); options.withExternalId("ext_id123"); options.withUpsert(true); options.withSendCompletionEmail(false); File usersFile = new File(MGMT_JOB_POST_USERS_IMPORTS_INPUT); Request<Job> request = api.jobs().importUsers("con_123456789", usersFile, options); assertThat(request, is(notNullValue())); server.jsonResponse(MGMT_JOB_POST_USERS_IMPORTS, 200); Job response = request.execute(); RecordedRequest recordedRequest = server.takeRequest(); assertThat(recordedRequest, hasMethodAndPath("POST", "/api/v2/jobs/users-imports")); assertThat(recordedRequest, hasHeader("Authorization", "Bearer apiToken")); String ctHeader = recordedRequest.getHeader("Content-Type"); assertThat(ctHeader, startsWith("multipart/form-data")); String[] ctParts = ctHeader.split("multipart/form-data; boundary="); RecordedMultipartRequest recordedMultipartRequest = new RecordedMultipartRequest(recordedRequest); assertThat(recordedMultipartRequest.getPartsCount(), is(5)); assertThat(recordedMultipartRequest.getBoundary(), is(notNullValue())); assertThat(recordedMultipartRequest.getBoundary(), is(ctParts[1])); //Connection ID KeyValuePart connectionIdParam = recordedMultipartRequest.getKeyValuePart("connection_id"); assertThat(connectionIdParam, is(notNullValue())); assertThat(connectionIdParam.getValue(), is("con_123456789")); //External ID KeyValuePart externalIdParam = recordedMultipartRequest.getKeyValuePart("external_id"); assertThat(externalIdParam, is(notNullValue())); assertThat(externalIdParam.getValue(), is("ext_id123")); //Upsert KeyValuePart upsertParam = recordedMultipartRequest.getKeyValuePart("upsert"); assertThat(upsertParam, is(notNullValue())); assertThat(upsertParam.getValue(), is("true")); //Send Completion Email KeyValuePart sendCompletionEmailParam = recordedMultipartRequest.getKeyValuePart("send_completion_email"); assertThat(sendCompletionEmailParam, is(notNullValue())); assertThat(sendCompletionEmailParam.getValue(), is("false")); //Users JSON FilePart jsonFile = recordedMultipartRequest.getFilePart("users"); assertThat(jsonFile, is(notNullValue())); String utf8Contents = new String(Files.readAllBytes(usersFile.toPath())); assertThat(jsonFile.getContentType(), is("text/json")); assertThat(jsonFile.getFilename(), is("job_post_users_imports_input.json")); assertThat(jsonFile.getValue(), is(utf8Contents)); assertThat(response, is(notNullValue())); }
Example 14
Source File: DefaultDockerClientUnitTest.java From docker-client with Apache License 2.0 | 4 votes |
@Test public void testBuildPassesMultipleRegistryConfigs() throws Exception { final RegistryConfigs registryConfigs = RegistryConfigs.create(ImmutableMap.of( "server1", RegistryAuth.builder() .serverAddress("server1") .username("u1") .password("p1") .email("e1") .build(), "server2", RegistryAuth.builder() .serverAddress("server2") .username("u2") .password("p2") .email("e2") .build() )); final RegistryAuthSupplier authSupplier = mock(RegistryAuthSupplier.class); when(authSupplier.authForBuild()).thenReturn(registryConfigs); final DefaultDockerClient client = builder.registryAuthSupplier(authSupplier) .build(); // build() calls /version to check what format of header to send enqueueServerApiVersion("1.20"); server.enqueue(new MockResponse() .setResponseCode(200) .addHeader("Content-Type", "application/json") .setBody( fixture("fixtures/1.22/build.json") ) ); final Path path = Paths.get(Resources.getResource("dockerDirectory").toURI()); client.build(path); final RecordedRequest versionRequest = takeRequestImmediately(); assertThat(versionRequest.getMethod(), is("GET")); assertThat(versionRequest.getPath(), is("/version")); final RecordedRequest buildRequest = takeRequestImmediately(); assertThat(buildRequest.getMethod(), is("POST")); assertThat(buildRequest.getPath(), is("/build")); final String registryConfigHeader = buildRequest.getHeader("X-Registry-Config"); assertThat(registryConfigHeader, is(not(nullValue()))); // check that the JSON in the header is equivalent to what we mocked out above from // the registryAuthSupplier final JsonNode headerJsonNode = toJson(BaseEncoding.base64().decode(registryConfigHeader)); assertThat(headerJsonNode, is(toJson(registryConfigs.configs()))); }
Example 15
Source File: RequestConfigTest.java From kubernetes-client with Apache License 2.0 | 4 votes |
private void assertAuthorizationHeader(String expectedValue) throws InterruptedException { RecordedRequest request = server.getMockServer().takeRequest(); String acutalValue = request.getHeader("Authorization"); assertEquals(expectedValue, acutalValue); }
Example 16
Source File: MockWebServerTest.java From KataTODOApiClientJava with Apache License 2.0 | 4 votes |
private void assertRequestContainsHeader(String key, String expectedValue, int requestIndex) throws InterruptedException { RecordedRequest recordedRequest = getRecordedRequestAtIndex(requestIndex); String value = recordedRequest.getHeader(key); assertEquals(expectedValue, value); }
Example 17
Source File: MockWebServerTest.java From mapbox-events-android with MIT License | 4 votes |
void assertRequestContainsHeader(String key, String expectedValue, int requestIndex) throws InterruptedException { RecordedRequest recordedRequest = obtainRecordedRequestAtIndex(requestIndex); String value = recordedRequest.getHeader(key); assertEquals(expectedValue, value); }
Example 18
Source File: AbstractMockWebServerTestCase.java From java-technology-stack with MIT License | 4 votes |
@Override public MockResponse dispatch(RecordedRequest request) throws InterruptedException { try { if (request.getPath().equals("/echo")) { assertThat(request.getHeader("Host"), Matchers.containsString("localhost:" + port)); MockResponse response = new MockResponse() .setHeaders(request.getHeaders()) .setHeader("Content-Length", request.getBody().size()) .setResponseCode(200) .setBody(request.getBody()); request.getBody().flush(); return response; } else if(request.getPath().equals("/status/ok")) { return new MockResponse(); } else if(request.getPath().equals("/status/notfound")) { return new MockResponse().setResponseCode(404); } else if(request.getPath().startsWith("/params")) { assertThat(request.getPath(), Matchers.containsString("param1=value")); assertThat(request.getPath(), Matchers.containsString("param2=value1¶m2=value2")); return new MockResponse(); } else if(request.getPath().equals("/methods/post")) { assertThat(request.getMethod(), Matchers.is("POST")); String transferEncoding = request.getHeader("Transfer-Encoding"); if(StringUtils.hasLength(transferEncoding)) { assertThat(transferEncoding, Matchers.is("chunked")); } else { long contentLength = Long.parseLong(request.getHeader("Content-Length")); assertThat("Invalid content-length", request.getBody().size(), Matchers.is(contentLength)); } return new MockResponse().setResponseCode(200); } else if(request.getPath().startsWith("/methods/")) { String expectedMethod = request.getPath().replace("/methods/","").toUpperCase(); assertThat(request.getMethod(), Matchers.is(expectedMethod)); return new MockResponse(); } return new MockResponse().setResponseCode(404); } catch (Throwable exc) { return new MockResponse().setResponseCode(500).setBody(exc.toString()); } }
Example 19
Source File: HttpTest.java From java-cloudant with Apache License 2.0 | 4 votes |
/** * Test that the stored cookie is applied to requests for different URLs. Most of the other * tests just check a single URL. * * @throws Exception */ @TestTemplate public void cookieAppliedToDifferentURL() throws Exception { mockWebServer.enqueue(OK_COOKIE); mockWebServer.enqueue(new MockResponse().setBody("first")); mockWebServer.enqueue(new MockResponse().setBody("second")); CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer) .username("a") .password("b") .build(); URI baseURI = c.getBaseUri(); URL first = new URL(baseURI.getScheme(), baseURI.getHost(), baseURI.getPort(), "/testdb"); String response = c.executeRequest(Http.GET(first)).responseAsString(); assertEquals("first", response, "The correct response body should be present"); // There should be a request for a cookie followed by a the real request assertEquals(2, mockWebServer.getRequestCount(), "There should be 2 requests"); assertEquals("/_session", MockWebServerResources.takeRequestWithTimeout(mockWebServer) .getPath(), "The first request should have been for a cookie"); RecordedRequest request = MockWebServerResources.takeRequestWithTimeout(mockWebServer); assertEquals("/testdb", request.getPath(), "The second request should have been for /testdb"); assertNotNull(request.getHeader("Cookie"), "There should be a cookie on the request"); // Now make a request to another URL URL second = new URL(baseURI.getScheme(), baseURI.getHost(), baseURI.getPort(), "/_all_dbs"); response = c.executeRequest(Http.GET(second)).responseAsString(); assertEquals("second", response, "The correct response body should be present"); // There should now be an additional request assertEquals(3, mockWebServer.getRequestCount(), "There should be 3 requests"); request = MockWebServerResources.takeRequestWithTimeout(mockWebServer); assertEquals("/_all_dbs", request.getPath(), "The second request should have been for " + "/_all_dbs"); String cookieHeader = request.getHeader("Cookie"); assertNotNull(cookieHeader, "There should be a cookie on the request"); assertTrue( request.getHeader("Cookie").contains(EXPECTED_OK_COOKIE), "The cookie header " + cookieHeader + " should contain the expected value."); }
Example 20
Source File: GeoApiContextTest.java From google-maps-services-java with Apache License 2.0 | 4 votes |
@Test public void testExperienceIdNotInHeader() throws Exception { final RecordedRequest request = makeMockRequest(); final String value = request.getHeader(HttpHeaders.X_GOOG_MAPS_EXPERIENCE_ID); assertNull(value); }