Java Code Examples for org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder#header()
The following examples show how to use
org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder#header() .
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: BaseControllerTest.java From spring-boot-vue-admin with Apache License 2.0 | 6 votes |
private Result execute( final HttpMethod method, final String targetUrl, final Object args, final String token) throws Exception { final MockHttpServletRequestBuilder builders = MockMvcRequestBuilders.request(method, targetUrl) .contentType(MediaType.APPLICATION_JSON_UTF8); if (args != null) { builders.content(JSON.toJSONString(args)); } if (StringUtils.isNotBlank(token)) { builders.header("Authorization", token); } return JSON.parseObject( this.mockMvc .perform(builders) .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andReturn() .getResponse() .getContentAsString(), Result.class); }
Example 2
Source File: GrafanaAuthenticationTest.java From Insights with Apache License 2.0 | 5 votes |
private MockHttpServletRequestBuilder mockHttpServletRequestBuilderPostWithRequestParam(String url, String content, Map<String, String> headers) { MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.post(url).cookie(httpRequest.getCookies()); for(Map.Entry<String, String> entry : headers.entrySet()) { builder.header(entry.getKey(), entry.getValue()); } return builder; }
Example 3
Source File: DiscoveryNodeControllerTest.java From haven-platform with Apache License 2.0 | 5 votes |
@SuppressWarnings("deprecation") private void addNode(String hostPort, boolean auth) throws Exception { NotifierData data = new NotifierData(); data.setName(StringUtils.before(hostPort, ':')); data.setAddress(hostPort); MockHttpServletRequestBuilder b = MockMvcRequestBuilders.post(getClusterUrl(data.getName())) .param("ttl", "234") .contentType(MimeTypeUtils.APPLICATION_JSON_VALUE) .content(objectMapper.writeValueAsString(data)); if(auth) { b.header("X-Auth-Node", SECRET); } mvc.perform(b).andExpect(auth ? status().isOk() : status().isUnauthorized()); }
Example 4
Source File: MockMvcHelper.java From entando-core with GNU Lesser General Public License v3.0 | 5 votes |
/** * receives a MockHttpServletRequestBuilder, puts standard headers into it and returns it * * @param requestBuilder the MockHttpServletRequestBuilder to which add headers * @return the MockHttpServletRequestBuilder with standard headers */ private MockHttpServletRequestBuilder addStandardHeaders(MockHttpServletRequestBuilder requestBuilder) { if (! StringUtils.isEmpty(this.accessToken)) { requestBuilder = requestBuilder.header("Authorization", "Bearer " + this.accessToken); } return requestBuilder.contentType(MediaType.APPLICATION_JSON_VALUE); }
Example 5
Source File: DapTestCommon.java From tds with BSD 3-Clause "New" or "Revised" License | 4 votes |
public HttpResponse execute(HttpRequestBase rq) throws IOException { URI uri = rq.getURI(); DapController controller = getController(uri); StandaloneMockMvcBuilder mvcbuilder = MockMvcBuilders.standaloneSetup(controller); mvcbuilder.setValidator(new TestServlet.NullValidator()); MockMvc mockMvc = mvcbuilder.build(); MockHttpServletRequestBuilder mockrb = MockMvcRequestBuilders.get(uri); // We need to use only the path part mockrb.servletPath(uri.getPath()); // Move any headers from rq to mockrb Header[] headers = rq.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header h = headers[i]; mockrb.header(h.getName(), h.getValue()); } // Since the url has the query parameters, // they will automatically be parsed and added // to the rb parameters. // Finally set the resource dir mockrb.requestAttr("RESOURCEDIR", this.resourcepath); // Now invoke the servlet MvcResult result; try { result = mockMvc.perform(mockrb).andReturn(); } catch (Exception e) { throw new IOException(e); } // Collect the output MockHttpServletResponse res = result.getResponse(); byte[] byteresult = res.getContentAsByteArray(); // Convert to HttpResponse HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, res.getStatus(), ""); if (response == null) throw new IOException("HTTPMethod.executeMock: Response was null"); Collection<String> keys = res.getHeaderNames(); // Move headers to the response for (String key : keys) { List<String> values = res.getHeaders(key); for (String v : values) { response.addHeader(key, v); } } ByteArrayEntity entity = new ByteArrayEntity(byteresult); String sct = res.getContentType(); entity.setContentType(sct); response.setEntity(entity); return response; }
Example 6
Source File: LocalServerSecurityWithUsersFileTests.java From spring-cloud-skipper with Apache License 2.0 | 4 votes |
@Test public void testEndpointAuthentication() throws Exception { logger.info(String.format( "Using parameters - httpMethod: %s, " + "URL: %s, URL parameters: %s, user credentials: %s", this.httpMethod, this.url, this.urlParameters, userCredentials)); final MockHttpServletRequestBuilder rb; switch (httpMethod) { case GET: rb = get(url); break; case POST: rb = post(url); break; case PUT: rb = put(url); break; case DELETE: rb = delete(url); break; default: throw new IllegalArgumentException("Unsupported Method: " + httpMethod); } if (this.userCredentials != null) { rb.header("Authorization", SecurityTestUtils.basicAuthorizationHeader(this.userCredentials.getUsername(), this.userCredentials.getPassword())); } if (!CollectionUtils.isEmpty(urlParameters)) { for (Map.Entry<String, String> mapEntry : urlParameters.entrySet()) { rb.param(mapEntry.getKey(), mapEntry.getValue()); } } final ResultMatcher statusResultMatcher; switch (expectedHttpStatus) { case UNAUTHORIZED: statusResultMatcher = status().isUnauthorized(); break; case FORBIDDEN: statusResultMatcher = status().isForbidden(); break; case FOUND: statusResultMatcher = status().isFound(); break; case NOT_FOUND: statusResultMatcher = status().isNotFound(); break; case OK: statusResultMatcher = status().isOk(); break; case CREATED: statusResultMatcher = status().isCreated(); break; case BAD_REQUEST: statusResultMatcher = status().isBadRequest(); break; case CONFLICT: statusResultMatcher = status().isConflict(); break; case INTERNAL_SERVER_ERROR: statusResultMatcher = status().isInternalServerError(); break; default: throw new IllegalArgumentException("Unsupported Status: " + expectedHttpStatus); } try { localSkipperResource.getMockMvc().perform(rb).andDo(print()).andExpect(statusResultMatcher); } catch (AssertionError e) { throw new AssertionError(String.format( "Assertion failed for parameters - httpMethod: %s, " + "URL: %s, URL parameters: %s, user credentials: %s", this.httpMethod, this.url, this.urlParameters, this.userCredentials), e); } }
Example 7
Source File: LocalServerSecurityWithUsersFileTests.java From spring-cloud-dataflow with Apache License 2.0 | 4 votes |
@Test public void testEndpointAuthentication() throws Exception { logger.info(String.format( "Using parameters - httpMethod: %s, " + "URL: %s, URL parameters: %s, user credentials: %s", this.httpMethod, this.url, this.urlParameters, userCredentials)); final MockHttpServletRequestBuilder rb; switch (httpMethod) { case GET: rb = get(url); break; case POST: rb = post(url); break; case PUT: rb = put(url); break; case DELETE: rb = delete(url); break; default: throw new IllegalArgumentException("Unsupported Method: " + httpMethod); } if (this.userCredentials != null) { rb.header("Authorization", basicAuthorizationHeader(this.userCredentials.getUsername(), this.userCredentials.getPassword())); } if (!CollectionUtils.isEmpty(urlParameters)) { for (Map.Entry<String, String> mapEntry : urlParameters.entrySet()) { rb.param(mapEntry.getKey(), mapEntry.getValue()); } } final ResultMatcher statusResultMatcher; switch (expectedHttpStatus) { case UNAUTHORIZED: statusResultMatcher = status().isUnauthorized(); break; case FORBIDDEN: statusResultMatcher = status().isForbidden(); break; case FOUND: statusResultMatcher = status().isFound(); break; case NOT_FOUND: statusResultMatcher = status().isNotFound(); break; case OK: statusResultMatcher = status().isOk(); break; case CREATED: statusResultMatcher = status().isCreated(); break; case BAD_REQUEST: statusResultMatcher = status().isBadRequest(); break; case INTERNAL_SERVER_ERROR: statusResultMatcher = status().isInternalServerError(); break; default: throw new IllegalArgumentException("Unsupported Status: " + expectedHttpStatus); } try { localDataflowResource.getMockMvc().perform(rb).andDo(print()).andExpect(statusResultMatcher); } catch (AssertionError e) { throw new AssertionError(String.format( "Assertion failed for parameters - httpMethod: %s, " + "URL: %s, URL parameters: %s, user credentials: %s", this.httpMethod, this.url, this.urlParameters, this.userCredentials), e); } }