@Test public void sessionAttribute() { this.builder.sessionAttr("foo", "bar"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); assertEquals("bar", request.getSession().getAttribute("foo")); }
@Test public void mergeSession() throws Exception { String attrName = "PARENT"; String attrValue = "VALUE"; MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController()) .defaultRequest(get("/").sessionAttr(attrName, attrValue)) .build(); assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getSession().getAttribute(attrName), equalTo(attrValue)); }
@Test public void session() { MockHttpSession session = new MockHttpSession(this.servletContext); session.setAttribute("foo", "bar"); this.builder.session(session); this.builder.sessionAttr("baz", "qux"); MockHttpServletRequest request = this.builder.buildRequest(this.servletContext); assertEquals(session, request.getSession()); assertEquals("bar", request.getSession().getAttribute("foo")); assertEquals("qux", request.getSession().getAttribute("baz")); }
@Test public void requestWhenConnectMessageAndUsingSockJsThenUsesCsrfTokenHandshakeInterceptor() throws Exception { this.spring.configLocations(xml("SyncSockJsConfig")).autowire(); WebApplicationContext context = (WebApplicationContext) this.spring.getContext(); MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build(); String csrfAttributeName = CsrfToken.class.getName(); String customAttributeName = this.getClass().getName(); MvcResult result = mvc.perform(get("/app/289/tpyx6mde/websocket") .requestAttr(csrfAttributeName, this.token) .sessionAttr(customAttributeName, "attributeValue")) .andReturn(); CsrfToken handshakeToken = (CsrfToken) this.testHandshakeHandler.attributes.get(csrfAttributeName); String handshakeValue = (String) this.testHandshakeHandler.attributes.get(customAttributeName); String sessionValue = (String) result.getRequest().getSession().getAttribute(customAttributeName); assertThat(handshakeToken).isEqualTo(this.token) .withFailMessage("CsrfToken is populated"); assertThat(handshakeValue).isEqualTo(sessionValue) .withFailMessage("Explicitly listed session variables are not overridden"); }
@Test public void requestWhenConnectMessageThenUsesCsrfTokenHandshakeInterceptor() throws Exception { this.spring.configLocations(xml("SyncConfig")).autowire(); WebApplicationContext context = (WebApplicationContext) this.spring.getContext(); MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build(); String csrfAttributeName = CsrfToken.class.getName(); String customAttributeName = this.getClass().getName(); MvcResult result = mvc.perform(get("/app") .requestAttr(csrfAttributeName, this.token) .sessionAttr(customAttributeName, "attributeValue")) .andReturn(); CsrfToken handshakeToken = (CsrfToken) this.testHandshakeHandler.attributes.get(csrfAttributeName); String handshakeValue = (String) this.testHandshakeHandler.attributes.get(customAttributeName); String sessionValue = (String) result.getRequest().getSession().getAttribute(customAttributeName); assertThat(handshakeToken).isEqualTo(this.token) .withFailMessage("CsrfToken is populated"); assertThat(handshakeValue).isEqualTo(sessionValue) .withFailMessage("Explicitly listed session variables are not overridden"); }
@Test public void sessionAttributesAreClearedBetweenInvocations() throws Exception { this.mvc.perform(get("/")) .andExpect(content().string(HELLO)) .andExpect(request().sessionAttribute(FOO, nullValue())); this.mvc.perform(get("/").sessionAttr(FOO, BAR)) .andExpect(content().string(HELLO)) .andExpect(request().sessionAttribute(FOO, BAR)); this.mvc.perform(get("/")) .andExpect(content().string(HELLO)) .andExpect(request().sessionAttribute(FOO, nullValue())); }
/** * Set session attributes. * @param sessionAttributes the session attributes */ public MockHttpServletRequestBuilder sessionAttrs(Map<String, Object> sessionAttributes) { Assert.notEmpty(sessionAttributes, "'sessionAttributes' must not be empty"); for (String name : sessionAttributes.keySet()) { sessionAttr(name, sessionAttributes.get(name)); } return this; }
@Test public void shouldValidateDeleteOnlinePage() throws ApsSystemException, Exception { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build(); String accessToken = mockOAuthInterceptor(user); when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true); when(this.controller.getPageValidator().getPageManager().getOnlinePage(any(String.class))).thenReturn(new Page()); ResultActions result = mockMvc.perform( delete("/pages/{pageCode}", "online_page") .sessionAttr("user", user) .header("Authorization", "Bearer " + accessToken)); result.andExpect(status().isBadRequest()); String response = result.andReturn().getResponse().getContentAsString(); result.andExpect(jsonPath("$.errors", hasSize(1))); result.andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_ONLINE_PAGE))); }
@Test public void shouldAddUserAuthorities() throws Exception { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build(); String accessToken = mockOAuthInterceptor(user); String mockJson = "[{\"group\":\"group1\", \"role\":\"role1\"},{\"group\":\"group2\", \"role\":\"role2\"}]"; List<UserAuthorityDto> authorities = (List<UserAuthorityDto>) this.createMetadata(mockJson, List.class); when(this.controller.getUserValidator().getGroupManager().getGroup(any(String.class))).thenReturn(mockedGroup()); when(this.controller.getUserValidator().getRoleManager().getRole(any(String.class))).thenReturn(mockedRole()); when(this.controller.getUserService().addUserAuthorities(any(String.class), any(UserAuthoritiesRequest.class))).thenReturn(authorities); ResultActions result = mockMvc.perform( put("/users/{target}/authorities", "mockuser") .sessionAttr("user", user) .content(mockJson) .contentType(MediaType.APPLICATION_JSON) .header("Authorization", "Bearer " + accessToken)); result.andExpect(status().isOk()); }
@Test public void shouldValidateDeletePageWithChildren() throws ApsSystemException, Exception { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build(); String accessToken = mockOAuthInterceptor(user); Page page = new Page(); page.setCode("page_with_children"); page.addChildCode("child"); when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true); when(this.controller.getPageValidator().getPageManager().getDraftPage(any(String.class))).thenReturn(page); ResultActions result = mockMvc.perform( delete("/pages/{pageCode}", "page_with_children") .sessionAttr("user", user) .header("Authorization", "Bearer " + accessToken)); result.andExpect(status().isBadRequest()); String response = result.andReturn().getResponse().getContentAsString(); result.andExpect(jsonPath("$.errors", hasSize(1))); result.andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_PAGE_HAS_CHILDREN))); }
@Test public void shouldValidateMovePageInvalidPosition() throws ApsSystemException, Exception { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build(); String accessToken = mockOAuthInterceptor(user); PagePositionRequest request = new PagePositionRequest(); request.setCode("page_to_move"); request.setParentCode("new_parent_page"); request.setPosition(0); when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true); when(this.controller.getPageValidator().getPageManager().getDraftPage("new_parent_page")).thenReturn(new Page()); ResultActions result = mockMvc.perform( put("/pages/{pageCode}/position", "page_to_move") .sessionAttr("user", user) .content(convertObjectToJsonBytes(request)) .contentType(MediaType.APPLICATION_JSON) .header("Authorization", "Bearer " + accessToken)); result.andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errors", hasSize(1))) .andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_CHANGE_POSITION_INVALID_REQUEST))); }
@Test public void shouldValidateMovePageMissingParent() throws ApsSystemException, Exception { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build(); String accessToken = mockOAuthInterceptor(user); PagePositionRequest request = new PagePositionRequest(); request.setCode("page_to_move"); request.setParentCode("new_parent_page"); request.setPosition(0); when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true); ResultActions result = mockMvc.perform( put("/pages/{pageCode}/position", "page_to_move") .sessionAttr("user", user) .content(convertObjectToJsonBytes(request)) .contentType(MediaType.APPLICATION_JSON) .header("Authorization", "Bearer " + accessToken)); result.andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errors", hasSize(1))) .andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_CHANGE_POSITION_INVALID_REQUEST))); }
@Test public void shouldGetUsersList() throws Exception { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build(); String accessToken = mockOAuthInterceptor(user); when(this.userService.getUsers(any(RestListRequest.class), any(String.class))).thenReturn(mockUsers()); ResultActions result = mockMvc.perform( get("/users") .param("withProfile", "0") .param("sort", "username") .param("filter[0].attribute", "username") .param("filter[0].operator", "like") .param("filter[0].value", "user") .sessionAttr("user", user) .header("Authorization", "Bearer " + accessToken)); System.out.println("result: " + result.andReturn().getResponse().getContentAsString()); result.andExpect(status().isOk()); }
@Test public void shouldValidateMovePageNameMismatch() throws ApsSystemException, Exception { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build(); String accessToken = mockOAuthInterceptor(user); PagePositionRequest request = new PagePositionRequest(); request.setCode("WRONG"); request.setParentCode("new_parent_page"); request.setPosition(1); when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true); when(this.controller.getPageValidator().getPageManager().getDraftPage("new_parent_page")).thenReturn(new Page()); ResultActions result = mockMvc.perform( put("/pages/{pageCode}/position", "page_to_move") .sessionAttr("user", user) .content(convertObjectToJsonBytes(request)) .contentType(MediaType.APPLICATION_JSON) .header("Authorization", "Bearer " + accessToken)); result.andExpect(status().isBadRequest()) .andExpect(jsonPath("$.errors", hasSize(1))) .andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_URINAME_MISMATCH))); }
@Test public void shouldAdd4CharsUsernamePost() throws Exception { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build(); String accessToken = mockOAuthInterceptor(user); String mockJson = "{\"username\": \"user\",\n" + " \"password\": \"new_password\",\n" + " \"status\": \"active\"\n" + "}"; when(this.userService.addUser(any(UserRequest.class))).thenReturn(this.mockUser()); ResultActions result = mockMvc.perform( post("/users") .sessionAttr("user", user) .content(mockJson) .contentType(MediaType.APPLICATION_JSON) .header("Authorization", "Bearer " + accessToken)); result.andExpect(status().isOk()); String response = result.andReturn().getResponse().getContentAsString(); System.out.println(response); result.andExpect(jsonPath("$.errors", hasSize(0))); }
@Test public void shouldValidateUserPut() throws Exception { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build(); String accessToken = mockOAuthInterceptor(user); String mockJson = "{\n" + " \"username\": \"username_test\",\n" + " \"status\": \"inactive\",\n" + " \"password\": \"invalid spaces\"\n" + " }"; when(this.userManager.getUser(any(String.class))).thenReturn(this.mockUserDetails("username_test")); ResultActions result = mockMvc.perform( put("/users/{target}", "mismach") .sessionAttr("user", user) .content(mockJson) .contentType(MediaType.APPLICATION_JSON) .header("Authorization", "Bearer " + accessToken)); String response = result.andReturn().getResponse().getContentAsString(); System.out.println("users: " + response); result.andExpect(status().isConflict()); }
@Test public void testSendEmail() throws Exception { String from = "test@mail.com"; String message = "Mail message"; String name = "Name"; ContactForm contactForm = new ContactForm(); contactForm.setMail(from); contactForm.setMessage(message); contactForm.setName(name); Mockito.when(mailService.sendEMail(from, mailTo, "Message from " + name, message)).thenReturn(true); mockMvc.perform(post("/contact").accept(MediaType.APPLICATION_XHTML_XML) .sessionAttr("contactForm", contactForm)) .andExpect(redirectedUrl("contact?sent=false")) .andExpect(model().attributeExists("contactForm")); } }
@Test public void shouldLoadOrderWhenContinuing() throws Exception { this.mockMvc.perform(get("/continueOrder") .sessionAttr("currentOrder", 10000L)) .andExpect(status().isOk()) .andExpect(model().attributeExists("currentOrder")) .andExpect(view().name("order")); } }
@Test public void shouldBeUnauthorized() throws Exception { UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24") .withGroup(Group.FREE_GROUP_NAME) .build(); String accessToken = mockOAuthInterceptor(user); ResultActions result = mockMvc.perform( get("/pages/{parentCode}", "mock_page") .sessionAttr("user", user) .header("Authorization", "Bearer " + accessToken) ); String response = result.andReturn().getResponse().getContentAsString(); result.andExpect(status().isForbidden()); }
@Test public void startsANewPizza() throws Exception { this.mockMvc.perform(get("/addPizza") .sessionAttr("currentOrder", 10000L)) .andExpect(status().isOk()) .andExpect(model().attributeExists("basePizzaMenuOptions")) .andExpect(model().attributeExists("currentPizza")) .andExpect(view().name("chooseBaseOptions")); }