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:cn.org.once.cstack.explorer.FileControllerTestIT.java

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();
    User user = null;//from w w  w  .  jav a  2s  .  co m
    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);
}

From source file:cn.org.once.cstack.modules.ModulesControllerTestIT.java

@Before
public void setup() throws Exception {
    logger.info("setup");

    this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    User user = null;/*w w w.  j a  va 2  s . co  m*/
    try {
        user = userService.findByLogin("johndoe");
    } catch (ServiceException e) {
        logger.error(e.getLocalizedMessage());
    }

    assert user != null;
    Authentication authentication = new UsernamePasswordAuthenticationToken(user.getLogin(),
            user.getPassword());
    Authentication result = authenticationManager.authenticate(authentication);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(result);
    session = new MockHttpSession();
    String secContextAttr = HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY;
    session.setAttribute(secContextAttr, securityContext);

}

From source file:org.jasig.cas.client.session.SingleSignOutFilterTests.java

@Test
public void frontChannelRequestRelayState() throws IOException, ServletException {
    final String logoutMessage = LogoutMessageGenerator.generateFrontChannelLogoutMessage(TICKET);
    request.setParameter(ConfigurationKeys.FRONT_LOGOUT_PARAMETER_NAME.getDefaultValue(), logoutMessage);
    request.setParameter(ConfigurationKeys.RELAY_STATE_PARAMETER_NAME.getDefaultValue(), RELAY_STATE);
    request.setQueryString(ConfigurationKeys.FRONT_LOGOUT_PARAMETER_NAME.getDefaultValue() + "=" + logoutMessage
            + "&" + ConfigurationKeys.RELAY_STATE_PARAMETER_NAME.getDefaultValue() + "=" + RELAY_STATE);
    request.setMethod("GET");
    final MockHttpSession session = new MockHttpSession();
    SingleSignOutFilter.getSingleSignOutHandler().getSessionMappingStorage().addSessionById(TICKET, session);
    filter.doFilter(request, response, filterChain);
    assertNull(SingleSignOutFilter.getSingleSignOutHandler().getSessionMappingStorage()
            .removeSessionByMappingId(TICKET));
    assertEquals(/*from www  .  j a v  a 2s .co m*/
            CAS_SERVER_URL_PREFIX + "/logout?_eventId=next&"
                    + ConfigurationKeys.RELAY_STATE_PARAMETER_NAME.getDefaultValue() + "=" + RELAY_STATE,
            response.getRedirectedUrl());
}

From source file:br.com.edo.atmlist.controller.ATMControllerTest.java

/**
 * Test of logout method, of class ATMController.
 *///w  w  w.  jav a 2  s .  c  om
@Test
public void testLogout() {
    System.out.println("logout");
    ModelMap model = new ModelMap();
    HttpSession session = new MockHttpSession();
    ATMController instance = new ATMController();
    String expResult = "redirect:login";
    String result = instance.logout(model, session);
    assertEquals(expResult, result);

}

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

/**
 * @see ChangePasswordFormController#handleSubmission(HttpSession, String, String, String, String, String, User, BindingResult)
 *//*from  w ww  . ja v a2s  .c om*/
@Test
@Verifies(value = "display error message if password is weak", method = "handleSubmission()")
public void handleSubmission_shouldDiplayErrorMessageOnWeakPasswords() throws Exception {
    ChangePasswordFormController controller = new ChangePasswordFormController();
    BindException errors = new BindException(controller.formBackingObject(), "user");

    String result = controller.handleSubmission(new MockHttpSession(), oldPassword, "password", "password", "",
            "", "", Context.getAuthenticatedUser(), errors);

    assertTrue(errors.hasErrors());
    assertEquals("error.password.requireMixedCase", errors.getGlobalError().getCode());
}

From source file:alpha.portal.webapp.filter.LocaleFilterTest.java

/**
 * Test locale and country./*from  w  ww  . j  a  v  a2  s  .c  o  m*/
 * 
 * @throws Exception
 *             the exception
 */
public void testLocaleAndCountry() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setSession(new MockHttpSession());
    request.addParameter("locale", "zh_TW");

    final MockHttpServletResponse response = new MockHttpServletResponse();
    this.filter.doFilter(request, response, new MockFilterChain());

    // session not null, should result in not null
    final Locale locale = (Locale) request.getSession().getAttribute(Constants.PREFERRED_LOCALE_KEY);
    Assert.assertNotNull(locale);
    Assert.assertEquals(new Locale("zh", "TW"), locale);
}

From source file:Controllers.AdministrateControllerTest.java

@Test
public void testChangePassWithValidUser() throws Exception {
    MockHttpSession mockHttpSession = new MockHttpSession();
    User user = new User();
    user.setEmail("Hei@gmail.com");
    mockHttpSession.setAttribute("user", user);
    Person person = new Person();
    when(personService.getPerson(any(String.class))).thenReturn(person);
    when(personService.changePassword(any(Person.class), any(String.class), any(String.class),
            any(String.class))).thenReturn(true);
    this.mockMvc/*from   www .j  ava 2  s .  co m*/
            .perform(post("/changePassword").param("oldPw", "asdasdasd").param("newPw", "asdasdasdasd")
                    .param("confirmPw", "asdasdasdasd").session(mockHttpSession))
            .andExpect(model().attribute("changedPassword", "Passordet er endret."))
            .andExpect(view().name("administrateAccount"));

}

From source file:cn.org.once.cstack.security.SecurityTestIT.java

@Before
public void setup() {
    logger.info("*********************************");
    logger.info("             setup               ");
    logger.info("*********************************");

    this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    // If user1 is null (first test) we create its session and its application
    try {/*from ww  w .j  a v  a  2  s .co m*/
        logger.info("Create session for user1 : " + user1);
        // we affect the user to skip this branch too
        User user1 = userService.findByLogin("usertest1");
        Authentication authentication = new UsernamePasswordAuthenticationToken(user1.getLogin(),
                user1.getPassword());
        Authentication result = authenticationManager.authenticate(authentication);
        SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
        securityContext.setAuthentication(result);
        session1 = new MockHttpSession();
        session1.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                securityContext);
    } catch (ServiceException e) {
        logger.error(e.getLocalizedMessage());
    }

    // After the first tests, all others are for User2
    try {
        logger.info("Create session for user2");
        User user2 = userService.findByLogin("usertest2");
        Authentication authentication = new UsernamePasswordAuthenticationToken(user2.getLogin(),
                user2.getPassword());
        Authentication result = authenticationManager.authenticate(authentication);
        SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
        securityContext.setAuthentication(result);
        session2 = new MockHttpSession();
        session2.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
                securityContext);
    } catch (ServiceException e) {
        logger.error(e.getLocalizedMessage());
    }

}

From source file:io.lavagna.web.security.login.DemoLoginTest.java

@Test
public void testLogoutWithActiveSession() throws IOException, ServletException {

    MockHttpSession unauthMockSession = new MockHttpSession();
    MockHttpSession mockSession = new MockHttpSession();

    when(req.getSession()).thenReturn(unauthMockSession, mockSession);
    when(req.getSession(true)).thenReturn(mockSession);

    UserSession.setUser(user, req, resp, userRepository);

    Assert.assertTrue(dl.handleLogout(req, resp));
    verify(resp).setStatus(HttpServletResponse.SC_OK);
    Assert.assertTrue(mockSession.isInvalid());
}