Java Code Examples for org.springframework.mock.web.MockHttpServletRequest#addHeader()
The following examples show how to use
org.springframework.mock.web.MockHttpServletRequest#addHeader() .
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: JsonRpcServerTest.java From jsonrpc4j with MIT License | 8 votes |
@Test public void testGzipRequest() throws IOException { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test-post"); request.addHeader(CONTENT_ENCODING, "gzip"); request.setContentType("application/json"); byte[] bytes = "{\"jsonrpc\":\"2.0\",\"id\":123,\"method\":\"testMethod\",\"params\":[\"Whir?inaki\"]}".getBytes(StandardCharsets.UTF_8); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos); gos.write(bytes); gos.close(); request.setContent(baos.toByteArray()); MockHttpServletResponse response = new MockHttpServletResponse(); jsonRpcServer = new JsonRpcServer(Util.mapper, mockService, ServiceInterface.class, true); jsonRpcServer.handle(request, response); String responseContent = new String(response.getContentAsByteArray(), StandardCharsets.UTF_8); Assert.assertEquals(responseContent, "{\"jsonrpc\":\"2.0\",\"id\":123,\"result\":null}\n"); Assert.assertNull(response.getHeader(CONTENT_ENCODING)); }
Example 2
Source File: ApmFilterTest.java From apm-agent-java with Apache License 2.0 | 8 votes |
@Test void testNoHeaderRecording() throws IOException, ServletException { when(coreConfiguration.isCaptureHeaders()).thenReturn(false); filterChain = new MockFilterChain(new TestServlet()); final MockHttpServletRequest get = new MockHttpServletRequest("GET", "/foo"); get.addHeader("Elastic-Apm-Traceparent", "00-0af7651916cd43dd8448eb211c80319c-b9c7c989f97918e1-01"); get.setCookies(new Cookie("foo", "bar")); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); mockResponse.addHeader("foo", "bar"); mockResponse.addHeader("bar", "baz"); filterChain.doFilter(get, mockResponse); assertThat(reporter.getTransactions()).hasSize(1); assertThat(reporter.getFirstTransaction().getContext().getResponse().getHeaders().isEmpty()).isTrue(); assertThat(reporter.getFirstTransaction().getContext().getRequest().getHeaders().isEmpty()).isTrue(); assertThat(reporter.getFirstTransaction().getContext().getRequest().getCookies().isEmpty()).isTrue(); assertThat(reporter.getFirstTransaction().getTraceContext().getTraceId().toString()).isEqualTo("0af7651916cd43dd8448eb211c80319c"); assertThat(reporter.getFirstTransaction().getTraceContext().getParentId().toString()).isEqualTo("b9c7c989f97918e1"); }
Example 3
Source File: ConfigViewTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testRender() throws Exception { ConfigView configView = ConfigView.getInstance(); Model configData = new LinkedHashModelFactory().createEmptyModel(); configData.add(RDF.ALT, RDF.TYPE, RDFS.CLASS); Map<Object, Object> map = new LinkedHashMap<>(); map.put(ConfigView.HEADERS_ONLY, false); map.put(ConfigView.CONFIG_DATA_KEY, configData); map.put(ConfigView.FORMAT_KEY, RDFFormat.NTRIPLES); final MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod(HttpMethod.GET.name()); request.addHeader("Accept", RDFFormat.NTRIPLES.getDefaultMIMEType()); MockHttpServletResponse response = new MockHttpServletResponse(); configView.render(map, request, response); String ntriplesData = response.getContentAsString(); Model renderedData = Rio.parse(new StringReader(ntriplesData), "", RDFFormat.NTRIPLES); assertThat(renderedData).isNotEmpty(); }
Example 4
Source File: JWTFilterTest.java From 21-points with Apache License 2.0 | 6 votes |
@Test public void testJWTFilterWrongScheme() throws Exception { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( "test-user", "test-password", Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) ); String jwt = tokenProvider.createToken(authentication, false); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Basic " + jwt); request.setRequestURI("/api/test"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); jwtFilter.doFilter(request, response, filterChain); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); }
Example 5
Source File: MockHttpUtil.java From attic-rave with Apache License 2.0 | 5 votes |
public static void setupRequestAsNonMobileUserAgent(MockHttpServletRequest mockHttpServletRequest) { mockHttpServletRequest.addHeader("User-Agent", "MSIE"); mockHttpServletRequest.setAttribute(DeviceUtils.CURRENT_DEVICE_ATTRIBUTE, new LiteDeviceResolver().resolveDevice(mockHttpServletRequest)); }
Example 6
Source File: ServiceThemeResolverTests.java From cas4.0.x-server-wechat with Apache License 2.0 | 5 votes |
@Test public void testGetDefaultServiceWithNoServicesManager() { this.serviceThemeResolver.setServicesManager(null); final MockHttpServletRequest request = new MockHttpServletRequest(); request.setParameter("service", "myServiceId"); request.addHeader("User-Agent", "Mozilla"); assertEquals("test", this.serviceThemeResolver.resolveThemeName(request)); }
Example 7
Source File: JWTFilterTest.java From jhipster-microservices-example with Apache License 2.0 | 5 votes |
@Test public void testJWTFilterWrongScheme() throws Exception { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( "test-user", "test-password", Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) ); String jwt = tokenProvider.createToken(authentication, false); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Basic " + jwt); request.setRequestURI("/api/test"); }
Example 8
Source File: SampleKatharsisServletTest.java From katharsis-framework with Apache License 2.0 | 5 votes |
@Test public void onCollectionRequestWithParamsGetShouldReturnCollection() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setMethod("GET"); request.setContextPath(""); request.setServletPath("/api"); request.setPathInfo("/tasks"); request.setRequestURI("/api/tasks"); request.setContentType(JsonApiMediaType.APPLICATION_JSON_API); request.addHeader("Accept", "*/*"); request.addParameter("filter[Task][name]", "John"); request.setQueryString(URLEncoder.encode("filter[Task][name]", StandardCharsets.UTF_8.name()) + "=John"); MockHttpServletResponse response = new MockHttpServletResponse(); katharsisServlet.service(request, response); String responseContent = response.getContentAsString(); log.debug("responseContent: {}", responseContent); assertNotNull(responseContent); assertJsonPartEquals("tasks", responseContent, "data[0].type"); assertJsonPartEquals("\"1\"", responseContent, "data[0].id"); assertJsonPartEquals(FIRST_TASK_ATTRIBUTES, responseContent, "data[0].attributes"); assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data[0].links"); assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data[0].relationships.project.links"); }
Example 9
Source File: SampleKatharsisFilterTest.java From katharsis-framework with Apache License 2.0 | 5 votes |
@Test public void onSimpleResourceGetShouldReturnOneResource() throws Exception { MockFilterChain filterChain = new MockFilterChain(); MockHttpServletRequest request = new MockHttpServletRequest(servletContext); request.setMethod("GET"); request.setContextPath(""); request.setServletPath(null); request.setPathInfo(null); request.setRequestURI("/api/tasks/1"); request.setContentType(JsonApiMediaType.APPLICATION_JSON_API); request.addHeader("Accept", "*/*"); MockHttpServletResponse response = new MockHttpServletResponse(); katharsisFilter.doFilter(request, response, filterChain); String responseContent = response.getContentAsString(); log.debug("responseContent: {}", responseContent); assertNotNull(responseContent); assertJsonPartEquals("tasks", responseContent, "data.type"); assertJsonPartEquals("\"1\"", responseContent, "data.id"); assertJsonPartEquals(SOME_TASK_ATTRIBUTES, responseContent, "data.attributes"); assertJsonPartEquals(FIRST_TASK_LINKS, responseContent, "data.links"); assertJsonPartEquals(PROJECT1_RELATIONSHIP_LINKS, responseContent, "data.relationships.project.links"); }
Example 10
Source File: LogClientTypeAspectShould.java From mutual-tls-ssl with Apache License 2.0 | 5 votes |
@Test public void logClientTypeIfPresent() { LogCaptor<LogClientTypeAspect> logCaptor = LogCaptor.forClass(LogClientTypeAspect.class); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("client-type", "okhttp"); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); logClientTypeAspect.logClientTypeIfPresent(); List<String> logs = logCaptor.getLogs(); assertThat(logs).containsExactly("Received the request from the following client: okhttp"); }
Example 11
Source File: HttpHeaderAuthenticationFilterTest.java From herd with Apache License 2.0 | 5 votes |
@Test public void testHttpHeaderAuthenticationFilterUserWithMultiRoleHeaderNameRegexMultiRoles() throws Exception { String testUserId = "testUser"; String userIdSuffix = "suffix"; String userIdWithSuffix = testUserId + "@" + userIdSuffix; modifyPropertySourceInEnvironment(getDefaultSecurityEnvironmentVariablesWithMultiHeaderRoles()); try { MockHttpServletRequest request = getRequestWithHeaders(testUserId, "testFirstName", "testLastName", "testEmail", "", "Wed, 11 Mar 2015 10:24:09"); request.addHeader("privtestrole1", "valid"); request.addHeader("privtestrole2", "valid"); request.addHeader("useridSuffix", userIdSuffix); // Invalidate user session if exists. invalidateApplicationUser(request); httpHeaderAuthenticationFilter.init(new MockFilterConfig()); httpHeaderAuthenticationFilter.doFilter(request, new MockHttpServletResponse(), new MockFilterChain()); Set<String> expectedRoles = new HashSet<>(); expectedRoles.add("testrole1"); expectedRoles.add("testrole2"); validateHttpHeaderApplicationUser(userIdWithSuffix, "testFirstName", "testLastName", "testEmail", expectedRoles, "Wed, 11 Mar 2015 10:24:09", null, null); } finally { restorePropertySourceInEnvironment(); } }
Example 12
Source File: JWTFilterTest.java From Full-Stack-Development-with-JHipster with MIT License | 5 votes |
@Test public void testJWTFilterWrongScheme() throws Exception { UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( "test-user", "test-password", Collections.singletonList(new SimpleGrantedAuthority(AuthoritiesConstants.USER)) ); String jwt = tokenProvider.createToken(authentication, false); MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Basic " + jwt); request.setRequestURI("/api/test"); }
Example 13
Source File: FrameworkExtensionTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { for (String headerName : this.headers.keySet()) { request.addHeader(headerName, this.headers.get(headerName)); } return request; }
Example 14
Source File: JWTFilterTest.java From alchemy with Apache License 2.0 | 5 votes |
@Test public void testJWTFilterMissingToken() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(JWTFilter.AUTHORIZATION_HEADER, "Bearer "); request.setRequestURI("/api/test"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); jwtFilter.doFilter(request, response, filterChain); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); }
Example 15
Source File: TokenAuthenticationFilterTest.java From molgenis with GNU Lesser General Public License v3.0 | 5 votes |
@Test void doFilter() throws IOException, ServletException { SecurityContext previous = SecurityContextHolder.getContext(); try { SecurityContext testContext = SecurityContextHolder.createEmptyContext(); SecurityContextHolder.setContext(testContext); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); RestAuthenticationToken auth = new RestAuthenticationToken( "admin", "admin", Arrays.asList(new SimpleGrantedAuthority("admin")), "token"); request.setRequestURI("/api/v1/dataset"); request.addHeader(TokenExtractor.TOKEN_HEADER, "token"); when(authenticationProvider.authenticate(new RestAuthenticationToken("token"))) .thenReturn(auth); filter.doFilter(request, response, chain); verify(chain).doFilter(request, response); assertEquals(auth, getContext().getAuthentication()); } finally { SecurityContextHolder.setContext(previous); } }
Example 16
Source File: JWTFilterTest.java From jhipster-microservices-example with Apache License 2.0 | 5 votes |
@Test public void testJWTFilterMissingToken() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(JWTConfigurer.AUTHORIZATION_HEADER, "Bearer "); request.setRequestURI("/api/test"); MockHttpServletResponse response = new MockHttpServletResponse(); MockFilterChain filterChain = new MockFilterChain(); jwtFilter.doFilter(request, response, filterChain); assertThat(response.getStatus()).isEqualTo(HttpStatus.OK.value()); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); }
Example 17
Source File: PutMethodTest.java From alfresco-remote-api with GNU Lesser General Public License v3.0 | 5 votes |
/** * Executes WebDAV method for testing * <p> * Sets content to request from a test file * * @param methodName Method to prepare, should be initialized (PUT, LOCK, UNLOCK are supported) * @param fileName the name of the file set to the context, can be used with path, i.e. "path/to/file/fileName.txt" * @param content If <b>not null</b> adds test content to the request * @param headers to set to request, can be null * @throws Exception */ private void executeMethod(String methodName, String fileName, byte[] content, Map<String, String> headers) throws Exception { if (methodName == WebDAV.METHOD_PUT) method = new PutMethod(); else if (methodName == WebDAV.METHOD_LOCK) method = new LockMethod(); else if (methodName == WebDAV.METHOD_UNLOCK) method = new UnlockMethod(); if (method != null) { request = new MockHttpServletRequest(methodName, "/alfresco/webdav/" + fileName); response = new MockHttpServletResponse(); request.setServerPort(8080); request.setServletPath("/webdav"); if (content != null) { request.setContent(content); } if (headers != null && !headers.isEmpty()) { for (String key : headers.keySet()) { request.addHeader(key, headers.get(key)); } } method.setDetails(request, response, webDAVHelper, companyHomeNodeRef); method.execute(); } }
Example 18
Source File: FrameworkExtensionTests.java From spring-analysis-note with MIT License | 5 votes |
@Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { for (String headerName : this.headers.keySet()) { request.addHeader(headerName, this.headers.get(headerName)); } return request; }
Example 19
Source File: OAuth2TokenMockUtil.java From cubeai with Apache License 2.0 | 4 votes |
@Override public MockHttpServletRequest postProcessRequest(MockHttpServletRequest mockHttpServletRequest) { mockHttpServletRequest.addHeader("Authorization", "Bearer " + token); return mockHttpServletRequest; }
Example 20
Source File: TestExtractor.java From proctor with Apache License 2.0 | 4 votes |
@Test public void testEmptyFilterTestsProvided() { final Extractor extractor = getBasicExtractor(); final String fr = "fr"; final String userId = "123456"; final MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader(LANGUAGE_HEADER_NAME, fr); request.setParameter(USER_IDENTIFIER_QUERY_PARAM, userId); request.setParameter("test", ""); final RawParameters parameters = extractor.extract(request); assertNotNull(parameters.getTest()); assertTrue(parameters.getTest().isEmpty()); }