Example usage for org.springframework.mock.web MockHttpSession MockHttpSession

List of usage examples for org.springframework.mock.web MockHttpSession MockHttpSession

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpSession MockHttpSession.

Prototype

public MockHttpSession() 

Source Link

Document

Create a new MockHttpSession with a default MockServletContext .

Usage

From source file:org.openmrs.web.controller.user.ChangePasswordFormControllerTest.java

/**
 * @see ChangePasswordFormController#formBackingObject()
 *///from ww  w  .j a  va2s.c o  m
@Test
@Verifies(value = "remain on the changePasswordForm page if there are errors", method = "formBackingObject()")
public void formBackingObject_shouldRemainOnChangePasswordFormPageIfThereAreErrors() throws Exception {
    ChangePasswordFormController controller = new ChangePasswordFormController();
    BindException errors = new BindException(controller.formBackingObject(), "user");
    errors.addError(new ObjectError("Test", "Test Error"));
    String result = controller.handleSubmission(new MockHttpSession(), oldPassword, "password",
            "differentPassword", "", "", "", Context.getAuthenticatedUser(), errors);
    assertEquals("/module/legacyui/admin/users/changePasswordForm", result);
}

From source file:fragment.web.AuthenticationControllerTest.java

@Test
public void testLoginFailedOther() throws Exception {
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/login");
    request.setParameter("login_failed", "");
    MockHttpSession mockSession = new MockHttpSession();
    mockSession.setAttribute(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY,
            "someuser");
    mockSession.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, new Exception());
    String actualResult = controller.login(request, map, mockSession);
    if (config.getAuthenticationService().compareToIgnoreCase("cas") == 0) {
        Assert.assertEquals("redirect:" + config.getCasLoginUrl() + "?service="
                + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8"), actualResult);
    } else {//from w w w . ja  v  a2 s . c  om
        Assert.assertEquals("auth.login", actualResult);
    }
    String message = (String) map.get("error");
    Assert.assertNotNull(message);
    Assert.assertThat(message, JUnitMatchers.containsString("Unknown error"));
}

From source file:org.jasig.cas.client.authentication.AuthenticationFilterTests.java

@Test
public void testIgnorePatternsWithExactMatching() throws Exception {
    final AuthenticationFilter f = new AuthenticationFilter();
    final MockServletContext context = new MockServletContext();
    context.addInitParameter("casServerLoginUrl", CAS_LOGIN_URL);

    final URL url = new URL(CAS_SERVICE_URL + "?param=valueToIgnore");

    context.addInitParameter("ignorePattern", url.toExternalForm());
    context.addInitParameter("ignoreUrlPatternType", "EXACT");
    context.addInitParameter("service", CAS_SERVICE_URL);
    f.init(new MockFilterConfig(context));

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setScheme(url.getProtocol());
    request.setServerName(url.getHost());
    request.setServerPort(url.getPort());
    request.setQueryString(url.getQuery());
    request.setRequestURI(url.getPath());

    final MockHttpSession session = new MockHttpSession();
    request.setSession(session);/*from w w w. j  a va2 s  .c  o  m*/

    final MockHttpServletResponse response = new MockHttpServletResponse();

    final FilterChain filterChain = new FilterChain() {
        public void doFilter(ServletRequest request, ServletResponse response)
                throws IOException, ServletException {
        }
    };

    f.doFilter(request, response, filterChain);
    assertNull(response.getRedirectedUrl());
}

From source file:Controllers.AdministrateControllerTest.java

@Test
public void testChooseAdministrateAsGuest() throws Exception {
    MockHttpSession mockHttpSession = new MockHttpSession();
    User user = new User();
    user.setEmail("GUEST");
    mockHttpSession.setAttribute("user", user);
    this.mockMvc.perform(post("/chooseAdministrateFunction").param("chooseId", "3").session(mockHttpSession))
            .andExpect(model().attribute("chooseSite", 5)).andExpect(view().name("administrateAccount"));
}

From source file:Controllers.ResembleControllerTest.java

@Test
public void testSubmitResembleGameCreateTask() throws Exception {
    User user = new User();
    user.setInLogged(true);//from  w  ww .j  a v a2s  . c  om
    CreateResembleGame createResembleGame = new CreateResembleGame();
    ResembleGame rg = new ResembleGame();
    rg.setCreatorId("asd");
    rg.setInfo("hasdasd");
    rg.setLearningGoal("iasdasd");
    rg.setDifficulty(2);
    createResembleGame.setResembleGame(rg);

    MockHttpSession mockHttpSession = new MockHttpSession();
    mockHttpSession.setAttribute("user", user);
    mockHttpSession.setAttribute("createResembleGame", createResembleGame);
    this.mockMvc.perform(post("/submitresemblegame").param("button", "Lag deloppgave").session(mockHttpSession))
            .andExpect(model().attributeExists("createResembleTask"))
            .andExpect(view().name("createresembletask"));
}

From source file:org.openmrs.module.radiology.web.controller.RadiologyOrderFormControllerTest.java

/**
 * @see RadiologyOrderFormController#postSaveRadiologyOrder(HttpServletRequest, Integer, Order,
 *      BindingResult)//from  www.  j a v a 2 s .  c  o  m
 */
@Test
@Verifies(value = "should set http session attribute openmrs message to saved fail worklist and redirect to patient dashboard when save study was not successful and given patient id", method = "postSaveRadiologyOrder(HttpServletRequest, Integer, RadiologyOrder, BindingResult)")
public void postSaveRadiologyOrder_shouldSetHttpSessionAttributeOpenmrsMessageToSavedFailWorklistAndRedirectToPatientDashboardWhenSaveStudyWasNotSuccessfulAndGivenPatientId()
        throws Exception {

    //given
    RadiologyOrder mockRadiologyOrder = RadiologyTestData.getMockRadiologyOrder1();
    mockRadiologyOrder.getStudy().setMwlStatus(MwlStatus.SAVE_ERR);

    when(radiologyService.placeRadiologyOrder(mockRadiologyOrder)).thenReturn(mockRadiologyOrder);

    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.addParameter("saveOrder", "saveOrder");
    MockHttpSession mockSession = new MockHttpSession();
    mockRequest.setSession(mockSession);

    BindingResult orderErrors = mock(BindingResult.class);
    when(orderErrors.hasErrors()).thenReturn(false);

    ModelAndView modelAndView = radiologyOrderFormController.postSaveRadiologyOrder(mockRequest,
            mockRadiologyOrder.getPatient().getPatientId(), mockRadiologyOrder, mockRadiologyOrder,
            orderErrors);

    assertNotNull(modelAndView);
    assertThat(modelAndView.getViewName(),
            is("redirect:/patientDashboard.form?patientId=" + mockRadiologyOrder.getPatient().getPatientId()));
    assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR),
            is("radiology.savedFailWorklist"));

    mockRequest = new MockHttpServletRequest();
    mockRequest.addParameter("saveOrder", "saveOrder");
    mockSession = new MockHttpSession();
    mockRequest.setSession(mockSession);

    mockRadiologyOrder.getStudy().setMwlStatus(MwlStatus.SAVE_ERR);
    when(radiologyService.placeRadiologyOrder(mockRadiologyOrder)).thenReturn(mockRadiologyOrder);

    modelAndView = radiologyOrderFormController.postSaveRadiologyOrder(mockRequest,
            mockRadiologyOrder.getPatient().getPatientId(), mockRadiologyOrder, mockRadiologyOrder,
            orderErrors);

    assertNotNull(modelAndView);
    assertThat(modelAndView.getViewName(),
            is("redirect:/patientDashboard.form?patientId=" + mockRadiologyOrder.getPatient().getPatientId()));
    assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR),
            is("radiology.savedFailWorklist"));
}

From source file:org.openmrs.module.radiology.order.web.RadiologyOrderFormControllerTest.java

/**
 * @see RadiologyOrderFormController#saveRadiologyOrder(HttpServletRequest, RadiologyOrder, BindingResult)
 * @verifies save given radiology order if valid and set http session attribute openmrs message to order saved and
 *           redirect to the new radiology order
 */// w  w w.j a  v a 2  s .  c o  m
@Test
public void saveRadiologyOrder_shouldSaveGivenRadiologyOrderIfValidAndSetHttpSessionAttributeOpenmrsMessageToOrderSavedAndRedirectToNewRadiologyOrder()
        throws Exception {

    // given
    RadiologyOrder mockRadiologyOrder = RadiologyTestData.getMockRadiologyOrder1();

    when(radiologyOrderService.placeRadiologyOrder(mockRadiologyOrder)).thenReturn(mockRadiologyOrder);

    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.addParameter("saveOrder", "saveOrder");
    MockHttpSession mockSession = new MockHttpSession();
    mockRequest.setSession(mockSession);

    BindingResult orderErrors = mock(BindingResult.class);
    when(orderErrors.hasErrors()).thenReturn(false);

    ModelAndView modelAndView = radiologyOrderFormController.saveRadiologyOrder(mockRequest, mockRadiologyOrder,
            orderErrors);

    assertNotNull(modelAndView);
    assertThat(modelAndView.getViewName(),
            is("redirect:/module/radiology/radiologyOrder.form?orderId=" + mockRadiologyOrder.getOrderId()));
    assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR), is("Order.saved"));
}

From source file:org.openmrs.web.controller.user.ChangePasswordFormControllerTest.java

/**
 * @see ChangePasswordFormController#handleSubmission(HttpSession, String, String, String, String, String, User, BindingResult)
 *///  w  w w.  j a v a  2s  .  c o  m
@Test
@Verifies(value = "set the secret question and answer of the user", method = "handleSubmission()")
public void handleSubmission_shouldSetTheUserSecretQuestionAndAnswer() throws Exception {
    User user = Context.getAuthenticatedUser();
    new UserProperties(user.getUserProperties()).setSupposedToChangePassword(true);

    UserService us = Context.getUserService();
    us.saveUser(user);

    ChangePasswordFormController controller = new ChangePasswordFormController();
    BindException errors = new BindException(controller.formBackingObject(), "user");

    controller.handleSubmission(new MockHttpSession(), oldPassword, "Passw0rd", "Passw0rd", "test_question",
            "test_answer", "test_answer", Context.getAuthenticatedUser(), errors);

    User modifiedUser = us.getUser(user.getId());

    assertTrue(us.isSecretAnswer(modifiedUser, "test_answer"));
}

From source file:Controllers.AdministrateControllerTest.java

@Test
public void testChooseAdministrateAsRegUser() throws Exception {
    MockHttpSession mockHttpSession = new MockHttpSession();
    User user = new User();
    user.setEmail("somemail@gmail.com");
    mockHttpSession.setAttribute("user", user);
    this.mockMvc.perform(post("/chooseAdministrateFunction").param("chooseId", "3").session(mockHttpSession))
            .andExpect(model().attribute("chooseSite", 3)).andExpect(view().name("administrateAccount"));
}

From source file:Controllers.ResembleControllerTest.java

@Test
public void testSubmitResembleGameError() throws Exception {
    User user = new User();
    user.setInLogged(true);//w ww. j a v a 2s . c o m
    CreateResembleGame createResembleGame = new CreateResembleGame();
    ResembleGame rg = new ResembleGame();
    rg.setCreatorId("asd");
    rg.setInfo("hasdasd");
    rg.setLearningGoal("iasdasd");
    rg.setDifficulty(2);
    createResembleGame.setResembleGame(rg);

    MockHttpSession mockHttpSession = new MockHttpSession();
    mockHttpSession.setAttribute("user", user);
    mockHttpSession.setAttribute("createResembleGame", createResembleGame);

    this.mockMvc.perform(
            post("/submitresemblegame").param("learningGoal", "").param("button", "").session(mockHttpSession))
            .andExpect(view().name("createresemblegame"));
}