@Test public void testCorsFilterOnOtherPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("*")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( get("/test/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN)); }
@Test public void processValidationErrorTest() throws Exception { UserJWTController control = new UserJWTController(null, null); MockMvc jwtMock = MockMvcBuilders.standaloneSetup(control) .setControllerAdvice(new ExceptionTranslator()) .build(); MvcResult res = jwtMock.perform(post("/api/authenticate") .contentType(MediaType.APPLICATION_JSON_UTF8) .accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN, MediaType.ALL) .content("{\"username\":\"fakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLongfakeUsernameTooLong" + "\",\"password\":\"fakePassword\",\"rememberMe\":false}")) .andExpect(status().isBadRequest()) .andReturn(); assertThat(res.getResolvedException(), instanceOf(MethodArgumentNotValidException.class)); }
public void testAjaxController() throws Exception { AjaxController controller = new AjaxController(); MockMvc mockMvc = standaloneSetup(controller).build(); String testJson = "{\"name\":\"First Last\"," + "\"likes\":{" + "\"data\":[{" + "\"name\":\"GeeCON\"," + "\"about\":\"Java and JVM based technologies, dynamic languages, patterns, distributed " + "computing and much more...\"," + "\"id\":\"354953985700\"" + "}]" + "}" + "}"; mockMvc.perform(post("/userJson") .accept(MediaType.APPLICATION_JSON) .content(testJson)) .andExpect(status().isAccepted()); }
public static MvcResult getHttpResultContent(MockMvc mockMvc, String uri, Method method, Map<String, String> keyvals) throws Exception { MockHttpServletRequestBuilder builder = null; switch (method) { case GET: builder = MockMvcRequestBuilders.get(uri); break; case POST: builder = MockMvcRequestBuilders.post(uri); break; case PUT: builder = MockMvcRequestBuilders.put(uri); break; case DELETE: builder = MockMvcRequestBuilders.delete(uri); break; default: builder = MockMvcRequestBuilders.get(uri); } for (Map.Entry<String, String> entry : keyvals.entrySet()) { builder = builder.param(entry.getKey(), entry.getValue()); } MvcResult result = mockMvc.perform(builder.accept(MediaType.ALL)).andReturn(); // result.getResponse().getHeaderNames(); return result; }
protected void setupMvcClient(final WebApplicationContext ctx, final int noOfClients) { LOG.info("setupMvcClient start"); isMvc = true; // loadProperties(); clients = new ArrayList<LoomClient>(noOfClients); for (int i = 0; i < noOfClients; i++) { MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build(); clients.add(new LoomMvcClient(mockMvc)); if (i == 0) { client = clients.get(0); } waitForStartup(); } LOG.info("setupMvcClient end"); }
public static void expect404WhileGeneratingCertificate(MockMvc mockMvc, String certName, String token, String expectedMessage) throws Exception { MockHttpServletRequestBuilder certPost = post("/api/v1/data") .header("Authorization", "Bearer " + token) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) //language=JSON .content("{\n" + " \"name\" : \"" + certName + "\",\n" + " \"type\" : \"certificate\",\n" + " \"parameters\" : {\n" + " \"common_name\" : \"federation\",\n" + " \"ca\" : \"picard\"\n" + " }\n" + "}"); mockMvc.perform(certPost) .andDo(print()) .andExpect(status().isNotFound()) .andExpect(jsonPath("$.error", equalTo(expectedMessage))); }
@Test public void gaugeServiceThatThrows() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( Config.class, MetricFilterAutoConfiguration.class); GaugeService gaugeService = context.getBean(GaugeService.class); willThrow(new IllegalStateException()).given(gaugeService).submit(anyString(), anyDouble()); Filter filter = context.getBean(Filter.class); MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) .addFilter(filter).build(); mvc.perform(get("/templateVarTest/foo")).andExpect(status().isOk()); verify(context.getBean(CounterService.class)) .increment("status.200.templateVarTest.someVariable"); verify(context.getBean(GaugeService.class)) .submit(eq("response.templateVarTest.someVariable"), anyDouble()); context.close(); }
@Test public void agentServletWithCustomPath() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "endpoints.jolokia.path=/foo/bar"); this.context.register(EndpointsConfig.class, WebMvcAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, ManagementServerPropertiesAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, JolokiaAutoConfiguration.class); this.context.refresh(); assertThat(this.context.getBeanNamesForType(JolokiaMvcEndpoint.class)).hasSize(1); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); mockMvc.perform(MockMvcRequestBuilders.get("/foo/bar")) .andExpect(MockMvcResultMatchers.content() .string(Matchers.containsString("\"request\":{\"type\""))); }
@Test public void records5xxxHttpInteractionsAsSingleMetric() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( Config.class, MetricFilterAutoConfiguration.class, ServiceUnavailableFilter.class); MetricsFilter filter = context.getBean(MetricsFilter.class); MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) .addFilter(filter) .addFilter(context.getBean(ServiceUnavailableFilter.class)).build(); mvc.perform(get("/unknownPath/1")).andExpect(status().isServiceUnavailable()); mvc.perform(get("/unknownPath/2")).andExpect(status().isServiceUnavailable()); verify(context.getBean(CounterService.class), times(2)) .increment("status.503.unmapped"); verify(context.getBean(GaugeService.class), times(2)) .submit(eq("response.unmapped"), anyDouble()); context.close(); }
@Test public void correctlyRecordsMetricsForDeferredResultResponse() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( Config.class, MetricFilterAutoConfiguration.class); MetricsFilter filter = context.getBean(MetricsFilter.class); CountDownLatch latch = new CountDownLatch(1); MockMvc mvc = MockMvcBuilders .standaloneSetup(new MetricFilterTestController(latch)).addFilter(filter) .build(); String attributeName = MetricsFilter.class.getName() + ".StopWatch"; MvcResult result = mvc.perform(post("/create")).andExpect(status().isOk()) .andExpect(request().asyncStarted()) .andExpect(request().attribute(attributeName, is(notNullValue()))) .andReturn(); latch.countDown(); mvc.perform(asyncDispatch(result)).andExpect(status().isCreated()) .andExpect(request().attribute(attributeName, is(nullValue()))); verify(context.getBean(CounterService.class)).increment("status.201.create"); context.close(); }
public static String generateCa(MockMvc mockMvc, String caName, String token) throws Exception { MockHttpServletRequestBuilder caPost = post("/api/v1/data") .header("Authorization", "Bearer " + token) .accept(APPLICATION_JSON) .contentType(APPLICATION_JSON) //language=JSON .content("{\n" + " \"name\" : \"" + caName + "\",\n" + " \"type\" : \"certificate\",\n" + " \"overwrite\": true,\n" + " \"parameters\" : {\n" + " \"common_name\" : \"federation\",\n" + " \"is_ca\" : true,\n" + " \"self_sign\" : true\n" + " }\n" + "}"); String caResult = mockMvc.perform(caPost) .andExpect(status().isOk()) .andReturn().getResponse().getContentAsString(); return caResult; }
@Test public void defaultHeaderConfiguration() throws Exception { this.context = SpringApplication.run(VanillaWebConfiguration.class, "--server.port=0"); MockMvc mockMvc = MockMvcBuilders .webAppContextSetup((WebApplicationContext) this.context) .addFilters((FilterChainProxy) this.context .getBean("springSecurityFilterChain", Filter.class)) .build(); mockMvc.perform(MockMvcRequestBuilders.get("/")) .andExpect(MockMvcResultMatchers.header().string("X-Content-Type-Options", is(notNullValue()))) .andExpect(MockMvcResultMatchers.header().string("X-XSS-Protection", is(notNullValue()))) .andExpect(MockMvcResultMatchers.header().string("Cache-Control", is(notNullValue()))) .andExpect(MockMvcResultMatchers.header().string("X-Frame-Options", is(notNullValue()))); }
@Test public void securityHeadersCanBeDisabled() throws Exception { this.context = SpringApplication.run(VanillaWebConfiguration.class, "--server.port=0", "--security.headers.content-type=false", "--security.headers.xss=false", "--security.headers.cache=false", "--security.headers.frame=false"); MockMvc mockMvc = MockMvcBuilders .webAppContextSetup((WebApplicationContext) this.context) .addFilters( this.context.getBean("springSecurityFilterChain", Filter.class)) .build(); mockMvc.perform(MockMvcRequestBuilders.get("/")) .andExpect(MockMvcResultMatchers.status().isUnauthorized()) .andExpect(MockMvcResultMatchers.header() .doesNotExist("X-Content-Type-Options")) .andExpect( MockMvcResultMatchers.header().doesNotExist("X-XSS-Protection")) .andExpect(MockMvcResultMatchers.header().doesNotExist("Cache-Control")) .andExpect( MockMvcResultMatchers.header().doesNotExist("X-Frame-Options")); }
/** * Perform a POST request to check the {@link SpringletsImageFileConverter} works. * * Only the needed autoconfiguration is loaded in order to create * the Spring Web MVC artifacts to handle the HTTP request. * * @see MockServletContext * @see MockMvc */ @Test public void checkConverter() throws Exception { EnvironmentTestUtils.addEnvironment(this.context, "springlets.image.management:true"); this.context.setServletContext(new MockServletContext()); this.context.register(TestConfiguration.class); this.context.refresh(); MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(this.context).build(); // Mock a multipart file to be sended MockMultipartFile imageFile = new MockMultipartFile("image", "image1.jpg", "image/jpg", "image1.jpg".getBytes()); mockMvc .perform(MockMvcRequestBuilders.fileUpload("/persons").file(imageFile) .param("name", "TESTNAME").param("surname", "TESTSURNAME")) .andExpect(status().isOk()).andDo(print()); }
public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { String authorizationHeaderValue = "Basic " + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); MockHttpServletResponse response = mockMvc .perform(post("/oauth/token") .header("Authorization", authorizationHeaderValue) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("client_id", "trusted-sw360-client") .param("client_secret", "sw360-secret") .param("username", username) .param("password", password) .param("grant_type", "password") .param("scope", "sw360.read")) .andReturn().getResponse(); return new ObjectMapper() .readValue(response.getContentAsByteArray(), OAuthToken.class) .accessToken; }
@Before public void setUp() throws Exception { MockMvc mockMvc = MockMvcBuilders .webAppContextSetup(applicationContext) .apply(springSecurity()) .build(); String bearer = "Bearer " + AuthConstants.INVALID_SCOPE_KEY_JWT; MockHttpServletRequestBuilder getRequest = get(CREDENTIAL_URL) .header("Authorization", bearer) .header("X-Forwarded-For", "1.1.1.1,2.2.2.2") .accept(MediaType.APPLICATION_JSON) .contentType(MediaType.APPLICATION_JSON) .with(request -> { request.setRemoteAddr("12346"); return request; }); response = mockMvc.perform(getRequest); }
@Test public void controllerMethodThatThrowsUnhandledException() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( Config.class, MetricFilterAutoConfiguration.class); Filter filter = context.getBean(Filter.class); MockMvc mvc = MockMvcBuilders.standaloneSetup(new MetricFilterTestController()) .addFilter(filter).build(); try { mvc.perform(get("/unhandledException")) .andExpect(status().isInternalServerError()); } catch (NestedServletException ex) { // Expected } verify(context.getBean(CounterService.class)) .increment("status.500.unhandledException"); verify(context.getBean(GaugeService.class)) .submit(eq("response.unhandledException"), anyDouble()); context.close(); }
@Test public void testCorsFilterOnApiPath() throws Exception { props.getCors().setAllowedOrigins(Collections.singletonList("*")); props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); props.getCors().setAllowedHeaders(Collections.singletonList("*")); props.getCors().setMaxAge(1800L); props.getCors().setAllowCredentials(true); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()) .addFilters(webConfigurer.corsFilter()) .build(); mockMvc.perform( options("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com") .header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")) .andExpect(header().string(HttpHeaders.VARY, "Origin")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800")); mockMvc.perform( get("/api/test-cors") .header(HttpHeaders.ORIGIN, "other.domain.com")) .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")); }