@Test public void testResetPassword() throws Exception { String username = "******"; User user = userManager.getUserByUsername(username); String token = userManager.generateRecoveryToken(user); String password = "******"; Wiser wiser = startWiser(getSmtpPort()); ResultActions update = mockMvc .perform( post("/updatePassword") .param("username", username) .param("token", token) .param("password", password)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/")); wiser.stop(); assertTrue(wiser.getMessages().size() == 1); MvcResult result = update.andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(); assertNotNull(session.getAttribute(BaseFormController.MESSAGES_KEY)); assertNull(session.getAttribute(BaseFormController.ERRORS_MESSAGES_KEY)); }
@Before public void setUp() throws Exception { MockHttpSession mockHttpSession = new MockHttpSession(); httpServletRequest.setSession(mockHttpSession); mockHttpSession.setAttribute(USER, USER); mockHttpSession.setAttribute(USER_ID, 1L); }
/** * @see RadiologyObsFormController#voidObs(HttpServletRequest, HttpServletResponse, Order, Obs, * String, String, Obs, BindingResult) */ @Test @Verifies( value = "should void obs for given request, response, orderId, obsId, voidObs, voidReason, and obs", method = "voidObs(HttpServletRequest, HttpServletResponse, Order, Obs, String, String, Obs, BindingResult)") public void voidObs_ShouldVoidObsForGivenRequestResponseOrderIdObsIdVoidObsVoidReasonAndObs() { MockHttpSession mockSession = new MockHttpSession(); mockRequest.addParameter("voidObs", "voidObs"); mockRequest.setSession(mockSession); when(obsErrors.hasErrors()).thenReturn(false); ModelAndView modelAndView = radiologyObsFormController.voidObs( mockRequest, null, mockRadiologyOrder, mockObs, "Test Void Reason"); assertNotNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR)); assertThat( (String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR), is("Obs.voidedSuccessfully")); assertThat( (String) modelAndView.getViewName(), is( "redirect:" + RADIOLOGY_OBS_FORM_URL + "orderId=" + mockRadiologyOrder.getId() + "&obsId=" + mockObs.getId())); }
@Test public void verifyOKWithState() throws Exception { final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET); final MockHttpSession mockSession = new MockHttpSession(); mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI); mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME); mockSession.putValue(OAuthConstants.OAUTH20_STATE, STATE); mockRequest.setSession(mockSession); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName()); final Map<String, Object> map = modelAndView.getModel(); assertEquals(SERVICE_NAME, map.get("serviceName")); assertEquals( REDIRECT_URI + "?" + OAuthConstants.CODE + "=" + SERVICE_TICKET + "&" + OAuthConstants.STATE + "=" + STATE, map.get("callbackUrl")); }
/** * @see RadiologyObsFormController#unvoidObs(HttpServletRequest, HttpServletResponse, Obs, String) */ @Test @Verifies( value = "should unvoid voided obs for given request, response and obs", method = "unvoidObs(HttpServletRequest, HttpServletResponse, Obs, String)") public void unvoidObs_shouldUnvoidVoidedObsForGivenRequestResponseAndObs() { MockHttpSession mockSession = new MockHttpSession(); mockRequest.addParameter("unvoidObs", "unvoidObs"); mockRequest.setSession(mockSession); when(obsErrors.hasErrors()).thenReturn(false); mockObs.setVoided(true); ModelAndView modelAndView = radiologyObsFormController.unvoidObs(mockRequest, null, mockObs); assertThat( modelAndView.getViewName(), is( "redirect:" + RADIOLOGY_OBS_FORM_URL + "orderId=" + mockRadiologyOrder.getId() + "&obsId=" + mockObs.getId())); assertThat( (String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR), is("Obs.unvoidedSuccessfully")); }
/** * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String, * RadiologyOrder, Obs Obs, BindingResult) */ @Test @Verifies( value = "should edit obs with edit reason and complex concept", method = "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)") public void saveObs_ShouldEditObsWithEditReasonAndComplexConcept() { MockHttpSession mockSession = new MockHttpSession(); mockRequest.addParameter("saveObs", "saveObs"); mockRequest.setSession(mockSession); when(obsErrors.hasErrors()).thenReturn(false); ConceptComplex concept = new ConceptComplex(); ConceptDatatype cdt = new ConceptDatatype(); cdt.setHl7Abbreviation("ED"); concept.setDatatype(cdt); mockObs.setConcept(concept); ModelAndView modelAndView = radiologyObsFormController.saveObs( mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors); assertNotNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR)); assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR), is("Obs.saved")); assertThat( modelAndView.getViewName(), is( "redirect:" + RADIOLOGY_OBS_FORM_URL + "orderId=" + mockRadiologyOrder.getId() + "&obsId=" + mockObs.getId())); }
/** * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String, * RadiologyOrder, Obs Obs, BindingResult) */ @Test @Verifies( value = "should edit obs with edit reason, complex concept and request which is an instance of multihttpserveletrequest", method = "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)") public void saveObs_ShouldEditObsWithEditReasonComplexConceptANdRequestWhichIsAnInstanceOfMultiHTTPServletRequest() { MockHttpSession mockSession = new MockHttpSession(); MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest(); mockRequest.addParameter("saveObs", "saveObs"); mockRequest.setSession(mockSession); when(obsErrors.hasErrors()).thenReturn(false); ConceptComplex concept = new ConceptComplex(); ConceptDatatype cdt = new ConceptDatatype(); cdt.setHl7Abbreviation("ED"); concept.setDatatype(cdt); mockObs.setConcept(concept); final String fileName = "test.txt"; final byte[] content = "Hello World".getBytes(); MockMultipartFile mockMultipartFile = new MockMultipartFile("complexDataFile", fileName, "text/plain", content); mockRequest.addFile(mockMultipartFile); radiologyObsFormController.saveObs( mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors); assertNotNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR)); assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR), is("Obs.saved")); }
@Before public void setUp() throws Exception { request = new MockHttpServletRequest(); MockHttpSession session = new MockHttpSession(); session.setAttribute(UserAuthenticationSuccessHandler.USER, USER); session.setAttribute(UserAuthenticationSuccessHandler.USER_ID, USER_ID); when(permissionService.hasPermissionOnZone(USER_ID, ZONE_ID)).thenReturn(true); request.setSession(session); }
@Test public void session() throws Exception { 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 testShowResetPasswordFormBadToken() throws Exception { String username = "******"; String badtoken = RandomStringUtils.random(32); ResultActions update = mockMvc .perform(get("/updatePassword").param("username", username).param("token", badtoken)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/")); MvcResult result = update.andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(); assertNotNull(session.getAttribute(BaseFormController.ERRORS_MESSAGES_KEY)); }
@Test public void testShowResetPasswordForm() throws Exception { String username = "******"; User user = userManager.getUserByUsername(username); String token = userManager.generateRecoveryToken(user); ResultActions update = mockMvc .perform(get("/updatePassword").param("username", username).param("token", token)) .andExpect(status().isOk()) .andExpect(view().name("updatePasswordForm")); MvcResult result = update.andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(); assertNull(session.getAttribute(BaseFormController.ERRORS_MESSAGES_KEY)); }
public MockHttpSession mockAnonymousHttpSession() { MockHttpSession mockSession = new MockHttpSession(); SecurityContext mockSecurityContext = mock(SecurityContext.class); AnonymousAuthenticationToken principal = new AnonymousAuthenticationToken(ANONYMOUS_USER_KEY, ANONYMOUS_USER_PRINCIPAL, AUTHORITIES); when(mockSecurityContext.getAuthentication()).thenReturn(principal); SecurityContextHolder.setContext(mockSecurityContext); mockSession.setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, mockSecurityContext); return mockSession; }
@Before public void setup() { logger.info("setup"); this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); User user = null; try { user = userService.findByLogin("johndoe"); } catch (ServiceException e) { logger.error(e.getLocalizedMessage()); } Authentication authentication = null; if (user != null) { authentication = new UsernamePasswordAuthenticationToken(user.getLogin(), user.getPassword()); } Authentication result = authenticationManager.authenticate(authentication); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(result); session = new MockHttpSession(); session.setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext); }
@Test public void testUpdatePasswordBadCurrentPassword() throws Exception { String username = "******"; String currentPassword = "******"; String password = "******"; mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build(); // user must ge logged in HttpSession session = mockMvc .perform( post("/j_security_check").param("j_username", "admin").param("j_password", "admin")) .andExpect(status().is(HttpStatus.FOUND.value())) .andExpect(redirectedUrl("/")) .andReturn() .getRequest() .getSession(); mockMvc .perform( post("/updatePassword") .session((MockHttpSession) session) .param("username", username) .param("currentPassword", currentPassword) .param("password", password)) .andExpect(status().isOk()); assertNull(session.getAttribute(BaseFormController.MESSAGES_KEY)); assertNotNull(session.getAttribute(BaseFormController.ERRORS_MESSAGES_KEY)); }
public MockHttpSession mockHttpSession(boolean secured) { MockHttpSession mockSession = new MockHttpSession(); SecurityContext mockSecurityContext = mock(SecurityContext.class); if (secured) { ExpiringUsernameAuthenticationToken principal = new ExpiringUsernameAuthenticationToken(null, USER_DETAILS, USER_NAME, AUTHORITIES); principal.setDetails(USER_DETAILS); when(mockSecurityContext.getAuthentication()).thenReturn(principal); } SecurityContextHolder.setContext(mockSecurityContext); mockSession.setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, mockSecurityContext); return mockSession; }
/** @see {@link HtmlFormEntryUtil#getLocation(String, FormEntryContext)} */ @Test @Verifies( value = "should find a location by session attribute", method = "getLocation(String,FormEntrySession)") public void getLocation_shouldFindALocationBySessionAttribute() throws Exception { String attrName = "emr.sessionLocation"; MockHttpSession httpSession = new MockHttpSession(); httpSession.setAttribute(attrName, "2"); FormEntryContext formEntryContext = new FormEntryContext(FormEntryContext.Mode.ENTER); formEntryContext.setHttpSession(httpSession); Assert.assertEquals( "2", HtmlFormEntryUtil.getLocation("SessionAttribute:" + attrName, formEntryContext) .getId() .toString()); }
@Test @Rollback(true) @Transactional public void positiveTestGetAllCompanies() throws Exception { session.setAttribute("googleUser", user); this.mockMvc .perform(get("/getAllCompanies").accept(MediaType.ALL).session(session)) .andExpect(status().isOk()); }
@Test public void shouldNotSetSecurityExceptionMessageOnSessionWhenBadCredentialsExceptionIsThrownBySpring() throws Exception { filter.onUnsuccessfulAuthentication(request, null, new BadCredentialsException("foobar")); assertThat( session.getAttribute(AuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY), is(nullValue())); }
@Test @ConfigureAgentEnabled(false) @ConfigureServletProbeUsernameSessionAttribute("username") @WrapInMockProbeExecution public void testUsernameSessionAttributeCaptureUnderDisabledAgent() throws ServletException, IOException { Servlet servlet = new MockServlet(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test"); MockHttpServletResponse response = new MockHttpServletResponse(); servlet.service(request, response); MockHttpSession session = new MockHttpSession(); session.setAttribute("username", "abc"); // perform assertions OperationSafeImpl operation = Agent.getInstance().getCurrentOperation(); assertNull(operation); }
@Test @Rollback(true) @Transactional public void negativeGoogleUserTestGetAllCompanies() throws Exception { session.setAttribute("googleUser", null); this.mockMvc .perform(get("/getAllCompanies").accept(MediaType.ALL).session(session)) .andExpect(status().isUnauthorized()); }
@Test public void testExecute() throws Exception { // start SMTP Server Wiser wiser = startWiser(getSmtpPort()); ResultActions actions = mockMvc .perform(get("/passwordHint.html").param("username", "user")) .andExpect(status().is3xxRedirection()); MvcResult result = actions.andReturn(); MockHttpSession session = (MockHttpSession) result.getRequest().getSession(); // verify that success messages are in the session assertNotNull(session.getAttribute(BaseFormController.MESSAGES_KEY)); // verify an account information e-mail was sent wiser.stop(); assertTrue(wiser.getMessages().size() == 1); }
/** * @see RadiologyObsFormController#voidObs(HttpServletRequest, HttpServletResponse, * RadiologyOrder, Obs, String, String, Obs, BindingResult) */ @Test @Verifies( value = "should not void obs with voiding reason null", method = "voidObs(HttpServletRequest, HttpServletResponse, RadiologyOrder, Obs, String, String, Obs, BindingResult)") public void voidObs_ShouldNotVoidObsWithVoidingReasonNull() { MockHttpSession mockSession = new MockHttpSession(); mockRequest.addParameter("voidObs", "voidObs"); mockRequest.setSession(mockSession); when(obsErrors.hasErrors()).thenReturn(false); ModelAndView modelAndView = radiologyObsFormController.voidObs(mockRequest, null, mockRadiologyOrder, mockObs, null); assertNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR)); assertThat(modelAndView.getViewName(), is("module/radiology/radiologyObsForm")); }
@Test @TransactionalReadWrite public void testUpdateAccountWithErrors() { testUtils.createAuthenticatedTestUser("SettingsControllerTest@testUpdateAccountWithErrors"); // Create request and session MockHttpServletRequest request = new MockHttpServletRequest("post", "/settings"); MockHttpSession session = new MockHttpSession(); request.setSession(session); assertNull(session.getAttribute("settings_ko")); // Create settings SettingsForm settingsForm = new SettingsForm(); settingsForm.setEditPassword("no"); settingsForm.setEmail("OTHER_EMAIL"); ModelAndView modelAndView = getModelAndViewSettingsPage(null, settingsForm, request); assertNotNull(session.getAttribute("settings_ko")); assertEquals("logged/settings", modelAndView.getViewName()); }
@Test public void testLoginUsingPasscodeWithUnknownToken() throws Exception { RemoteUserAuthentication userAuthentication = new RemoteUserAuthentication( marissa.getId(), marissa.getName(), marissa.getEmail(), new ArrayList<GrantedAuthority>()); final MockSecurityContext mockSecurityContext = new MockSecurityContext(userAuthentication); SecurityContextHolder.setContext(mockSecurityContext); MockHttpSession session = new MockHttpSession(); session.setAttribute( HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, mockSecurityContext); MockHttpServletRequestBuilder get = get("/passcode").accept(APPLICATION_JSON).session(session); getMockMvc().perform(get).andExpect(status().isForbidden()); }
@Test @TransactionalReadWrite public void testUpdateAccount() { User user = testUtils.createAuthenticatedTestUser("SettingsControllerTest@testUpdateAccount"); // Create request and session MockHttpServletRequest request = new MockHttpServletRequest("post", "/settings"); MockHttpSession session = new MockHttpSession(); request.setSession(session); assertNull(session.getAttribute("settings_ok")); // Create settings SettingsForm settingsForm = new SettingsForm(); settingsForm.setEditPassword("no"); settingsForm.setEmail(user.getEmail()); settingsForm.setLang(testUtils.LOCALE_US); ModelAndView modelAndView = getModelAndViewSettingsPage(null, settingsForm, request); assertNotNull(session.getAttribute("settings_ok")); assertEquals("redirectWithoutModel:settings", modelAndView.getViewName()); }
/** * @see RadiologyObsFormController#saveObs(HttpServletRequest, HttpServletResponse, String, * RadiologyOrder, Obs Obs, BindingResult) */ @Test @Verifies( value = "should edit obs with edit reason concept not complex and request which is an instance of multihttpserveletrequest", method = "saveObs(HttpServletRequest, HttpServletResponse, String, RadiologyOrder, Obs Obs, BindingResult)") public void saveObs_ShouldEditObsWithEditReasonConceptNotComplexAndRequestWhichIsAnInstanceOfMultiHTTPServletRequest() { MockHttpSession mockSession = new MockHttpSession(); MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest(); mockRequest.addParameter("saveObs", "saveObs"); mockRequest.setSession(mockSession); when(obsErrors.hasErrors()).thenReturn(false); ; mockObs.setConcept(new Concept()); final String fileName = "test.txt"; final byte[] content = "Hello World".getBytes(); MockMultipartFile mockMultipartFile = new MockMultipartFile("complexDataFile", fileName, "text/plain", content); mockRequest.addFile(mockMultipartFile); ModelAndView modelAndView = radiologyObsFormController.saveObs( mockRequest, null, "Test Edit Reason", mockRadiologyOrder, mockObs, obsErrors); assertNotNull(mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR)); assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR), is("Obs.saved")); assertThat( modelAndView.getViewName(), is( "redirect:" + RADIOLOGY_OBS_FORM_URL + "orderId=" + mockRadiologyOrder.getId() + "&obsId=" + mockObs.getId())); }
@Test public void testNonconcurrentLogin() throws Exception { MockFilterConfig filterConfig = new MockFilterConfig(servletContext); filter.init(filterConfig); MockHttpServletRequest req = new MockHttpServletRequest(servletContext); MockHttpServletResponse res = new MockHttpServletResponse(); MockHttpSession sessionOfAnon = new MockHttpSession(); req.setSession(sessionOfAnon); filter.doFilter(req, res, new MockFilterChain()); assertFalse(sessionOfAnon.isInvalid()); MockHttpSession sessionOfJohn = new MockHttpSession(servletContext); req.setUserPrincipal(new TransientUser("john")); req.setSession(sessionOfJohn); filter.doFilter(req, res, new MockFilterChain()); assertFalse(sessionOfJohn.isInvalid()); MockHttpSession sessionOfJane = new MockHttpSession(servletContext); req.setUserPrincipal(new TransientUser("jane")); req.setSession(sessionOfJane); filter.doFilter(req, res, new MockFilterChain()); assertFalse(sessionOfJane.isInvalid()); }
@Test public void testConcurrentLoginWithDisallowingAll() throws Exception { MockFilterConfig filterConfig = new MockFilterConfig(servletContext); filterConfig.addInitParameter("disallowConcurrentLoginUsernames", "*"); filter.init(filterConfig); MockHttpServletRequest req = new MockHttpServletRequest(servletContext); MockHttpServletResponse res = new MockHttpServletResponse(); MockHttpSession sessionOfJohn1 = new MockHttpSession(servletContext); req.setUserPrincipal(new TransientUser("john")); req.setSession(sessionOfJohn1); filter.doFilter(req, res, new MockFilterChain()); assertFalse(sessionOfJohn1.isInvalid()); MockHttpSession sessionOfJohn2 = new MockHttpSession(servletContext); req.setUserPrincipal(new TransientUser("john")); req.setSession(sessionOfJohn2); filter.doFilter(req, res, new MockFilterChain()); assertFalse(sessionOfJohn2.isInvalid()); req.setSession(sessionOfJohn1); filter.doFilter(req, res, new MockFilterChain()); assertTrue(sessionOfJohn1.isInvalid()); req.setSession(sessionOfJohn2); filter.doFilter(req, res, new MockFilterChain()); assertFalse(sessionOfJohn2.isInvalid()); }
/** Test that the store code is resolved and cached by <code>resolveStoreCodeHeader</code>. */ @Test public void testResolveStoreCodeSessionIsCached() { final String storeCode = "store5"; MockHttpSession session = new MockHttpSession(); session.setAttribute(STORE_CODE, storeCode); request.setSession(session); context.checking( new Expectations() { { oneOf(delegate).resolveStoreCodeSession(request, STORE_CODE); will(returnValue(storeCode)); } }); assertEquals( SAME_CODE_AS_DELEGATE_EXPECTED, storeCode, cachingResolver.resolveStoreCodeSession(request, STORE_CODE)); assertEquals( SAME_CODE_EXPECTED_ON_SECOND_CALL, storeCode, cachingResolver.resolveStoreCodeSession(request, STORE_CODE)); }
/** Test that the store code is resolved and cached by <code>resolveStoreCodeHeader</code>. */ @Test public void testResolveDomainSessionIsCached() { final String domain = "domain"; MockHttpSession session = new MockHttpSession(); session.setAttribute(domain, "http://www.store6.com"); request.setSession(session); context.checking( new Expectations() { { oneOf(delegate).resolveDomainSession(request, STORE_CODE); will(returnValue("store6")); } }); assertEquals( SAME_CODE_AS_DELEGATE_EXPECTED, "store6", cachingResolver.resolveDomainSession(request, STORE_CODE)); assertEquals( SAME_CODE_EXPECTED_ON_SECOND_CALL, "store6", cachingResolver.resolveDomainSession(request, STORE_CODE)); }