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.jasig.cas.client.session.SingleSignOutHandlerTests.java

@Test
public void frontChannelLogoutFailsIfNoSessionIndex() {
    final String logoutMessage = LogoutMessageGenerator.generateFrontChannelLogoutMessage("");
    request.setParameter(FRONT_LOGOUT_PARAMETER_NAME, logoutMessage);
    request.setQueryString(FRONT_LOGOUT_PARAMETER_NAME + "=" + logoutMessage);
    request.setMethod("GET");
    final MockHttpSession session = new MockHttpSession();
    handler.getSessionMappingStorage().addSessionById(TICKET, session);
    assertFalse(handler.process(request, response));
    assertFalse(session.isInvalid());//from  w  w w .  j  ava  2s.  c  o  m
}

From source file:fr.treeptik.cloudunit.modules.AbstractModuleControllerTestIT.java

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

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

    User user = null;/*from w w  w. j  av a 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);

    // create an application server
    String jsonString = "{\"applicationName\":\"" + applicationName + "\", \"serverName\":\"" + server + "\"}";
    mockMvc.perform(
            post("/application").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString))
            .andExpect(status().isOk());
}

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

@Before
public void setUp() throws Exception {
    logger.info("setup");
    applicationName = "app" + new Random().nextInt(100000);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    User user = null;/*from   w w  w .  jav a2s. c o  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);

    // create an application server
    String jsonString = "{\"applicationName\":\"" + applicationName + "\", \"serverName\":\"" + server + "\"}";
    mockMvc.perform(
            post("/application").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString))
            .andExpect(status().isOk());
}

From source file:fr.treeptik.cloudunit.users.UserControllerTestIT.java

@Test
public void test10_userCreation() throws Exception {
    User user = null;// w  w w .j a v a2  s  .c  o m
    try {
        user = userService.findByLogin("johndoe");
    } catch (ServiceException e) {
        logger.error(e.getLocalizedMessage());
    }

    Authentication 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);

    final String login = "user10";
    final String password = "123456";
    final String email = "user10@gmail.com";
    final String firstName = "user";
    final String lastName = "user";
    final String organization = "treeptik";

    String jsonString = "{\"login\":\"" + login + "\", \"password\":\"" + password + "\", \"email\":\"" + email
            + "\", \"firstName\":\"" + firstName + "\", \"lastName\":\"" + lastName + "\", \"organization\":\""
            + organization + "\" }";
    mockMvc.perform(
            post("/user/signin").session(session).contentType(MediaType.APPLICATION_JSON).content(jsonString))
            .andDo(print()).andExpect(status().is2xxSuccessful());
}

From source file:Controllers.ResembleControllerTest.java

@Test
public void testNextResembleTaskOtherGame() throws Exception {
    MockHttpSession mockHttpSession = new MockHttpSession();
    ResembleTask rt = new ResembleTask();
    ArrayList<Integer> taskNumbers = new ArrayList<>();
    taskNumbers.add(0);//from   w  w  w  . ja v  a 2 s.c om
    taskNumbers.add(1);
    taskNumbers.add(2);

    ResembleGame rg = new ResembleGame(taskNumbers, 2, "", "", 1);

    rg.setCurrentTask(2);
    mockHttpSession.setAttribute("resembleGame", rg);
    when(resembleTaskService.getResembleTask(any(Integer.class))).thenReturn(rt);
    this.mockMvc
            .perform(post("/nextresembletask").param("score", "50").param("othergame", "othergame")
                    .session(mockHttpSession))
            .andExpect(model().attribute("isOving", 0)).andExpect(view().name("otherResembleGame"));
}

From source file:fi.okm.mpass.shibboleth.authn.impl.ShibbolethSpAuthnServletTest.java

protected MockHttpServletRequest initServletRequest() {
    final MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    final MockHttpSession session = new MockHttpSession();
    servletRequest.setParameter(ExternalAuthentication.CONVERSATION_KEY, conversationKey);
    session.setAttribute(ExternalAuthentication.CONVERSATION_KEY + conversationKey,
            new ExternalAuthenticationImpl(prc));
    servletRequest.setSession(session);/*w w w .  j  ava2 s . c o  m*/
    return servletRequest;
}

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

/**
 * @see ChangePasswordFormController#handleSubmission(HttpSession, String, String, String, String, String, User, BindingResult)
 *///from  ww  w . j  a va2 s . com
@Test
@Verifies(value = "display error message when the answer and the confirm answer entered are not the same", method = "handleSubmission()")
public void handleSubmission_shouldDiplayErrorMessageIfAnswerAndConfirmAnswerAreNotTheSame() throws Exception {
    ChangePasswordFormController controller = new ChangePasswordFormController();
    BindException errors = new BindException(controller.formBackingObject(), "user");

    String result = controller.handleSubmission(new MockHttpSession(), oldPassword, "Passw0rd", "Passw0rd",
            "question", "answer", "confirmanswer", Context.getAuthenticatedUser(), errors);

    assertTrue(errors.hasErrors());
    assertEquals("error.options.secretAnswer.match", errors.getGlobalError().getCode());
}

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

@Test
public void logoutPostUserAuth() 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);
    when(req.getMethod()).thenReturn("POST");
    PrintWriter pw = mock(PrintWriter.class);
    when(resp.getWriter()).thenReturn(pw);
    Assert.assertFalse(mockSession.isInvalid());

    personaLogin.handleLogout(req, resp);

    verify(resp).setStatus(HttpServletResponse.SC_OK);
    verify(resp).setContentType("application/json");
    Assert.assertTrue(mockSession.isInvalid());
}

From source file:Controllers.AdministrateControllerTest.java

@Test
public void testAddClassIdValidInfo() throws Exception {
    MockHttpSession mockHttpSession = new MockHttpSession();
    User user = new User();
    user.setEmail("Hei@gmail.com");
    mockHttpSession.setAttribute("user", user);
    AddNewClassId ancid = new AddNewClassId();
    ancid.setClassId("klasse 1");

    when(personService.setClassId(any(Person.class), any(String.class))).thenReturn(true);
    when(personService.getPerson(any(String.class))).thenReturn(new Person());
    when(personService.changePassword(any(Person.class), any(String.class), any(String.class),
            any(String.class))).thenReturn(false);
    this.mockMvc.perform(post("/addClassId").param("classId", "klasse 1").session(mockHttpSession))
            .andExpect(model().attribute("NewClassMessage",
                    "Du er n registrert i klasse: " + ancid.getClassId()))
            .andExpect(view().name("administrateAccount"));
}

From source file:fragment.web.AuthenticationControllerTest.java

@Test
public void testLogin() throws Exception {
    MockHttpServletRequest request = getRequestTemplate(HttpMethod.GET, "/login");
    String actualResult = controller.login(request, map, new MockHttpSession());
    if (config.getAuthenticationService().compareToIgnoreCase("cas") == 0) {
        Assert.assertEquals("redirect:" + config.getCasLoginUrl() + "?service="
                + URLEncoder.encode(config.getCasServiceUrl(), "UTF-8"), actualResult);
    } else {//from w ww. j av a2 s. c  om
        Assert.assertEquals("auth.login", actualResult);
    }
}