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#handleSubmission(HttpSession, String, String, String, String, String, User, BindingResult)
 *///w  ww . j  a  v  a2  s  .  c  o m
@Test
@Verifies(value = "display error message when question is empty and answer is not empty", method = "handleSubmission()")
public void handleSubmission_shouldDiplayErrorMessageIfQuestionIsEmptyAndAnswerIsNotEmpty() throws Exception {
    ChangePasswordFormController controller = new ChangePasswordFormController();
    BindException errors = new BindException(controller.formBackingObject(), "user");

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

    assertTrue(errors.hasErrors());
    assertEquals("auth.question.empty", errors.getGlobalError().getCode());
}

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

@Test
public void testGateway() throws Exception {
    final MockHttpSession session = new MockHttpSession();
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpServletResponse response = new MockHttpServletResponse();
    final FilterChain filterChain = new FilterChain() {

        public void doFilter(ServletRequest request, ServletResponse response)
                throws IOException, ServletException {
            // nothing to do
        }//from  w ww .  jav a  2 s.  c  om
    };

    request.setSession(session);
    this.filter.setRenew(true);
    this.filter.setGateway(true);
    this.filter.doFilter(request, response, filterChain);
    assertNotNull(session.getAttribute(DefaultGatewayResolverImpl.CONST_CAS_GATEWAY));
    assertNotNull(response.getRedirectedUrl());

    final MockHttpServletResponse response2 = new MockHttpServletResponse();
    this.filter.doFilter(request, response2, filterChain);
    assertNull(session.getAttribute(DefaultGatewayResolverImpl.CONST_CAS_GATEWAY));
    assertNull(response2.getRedirectedUrl());
}

From source file:Controllers.AdministrateControllerTest.java

@Test
public void testChangePassWithWrongPass() throws Exception {
    MockHttpSession mockHttpSession = new MockHttpSession();
    User user = new User();
    user.setEmail("Hei@gmail.com");
    mockHttpSession.setAttribute("user", user);
    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/*from   w w w. j  av a2 s.c o  m*/
            .perform(post("/changePassword").param("oldPw", "asdasdasd").param("newPw", "asdasdasdasd")
                    .param("confirmPw", "asdasdasdasd").session(mockHttpSession))
            .andExpect(model().attribute("changedPassword",
                    "Feil. Husk at passordet m vre lengre enn 8 tegn."))
            .andExpect(model().attribute("chooseSite", 1)).andExpect(view().name("administrateAccount"));
}

From source file:fragment.web.HomeControllerTest.java

@Test
public void testHome() throws Exception {

    User user = userDAO.find(1L);/*  www .j a va 2  s  . c  om*/
    asUser(user);

    eventService.createEvent(new Date(), user.getTenant(), "testSubject", "", Source.PORTAL, Scope.ACCOUNT,
            Category.ACCOUNT, Severity.INFORMATION, false);
    eventService.createEvent(new Date(), user.getTenant(), "testSubject", "", Source.PORTAL, Scope.ACCOUNT,
            Category.ACCOUNT, Severity.INFORMATION, false);
    eventService.createEvent(new Date(), user.getTenant(), "testSubject", "", Source.PORTAL, Scope.ACCOUNT,
            Category.ACCOUNT, Severity.INFORMATION, false);
    eventService.createEvent(new Date(), user.getTenant(), "testSubject", "", Source.PORTAL, Scope.ACCOUNT,
            Category.ACCOUNT, Severity.INFORMATION, false);

    HttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setAttribute("effectiveTenant", controller.getTenant());
    mockRequest.setAttribute("isSurrogatedTenant", Boolean.FALSE);
    ((MockHttpServletRequest) mockRequest).setParameter("lang", "en_US");
    Assert.assertEquals("main.home_service_with_second_level", controller.home(controller.getTenant(),
            controller.getTenant().getUuid(), false, map, new MockHttpSession(), mockRequest));
    Assert.assertTrue(map.containsAttribute("tenant"));
    Assert.assertTrue(map.containsAttribute("users"));
    Assert.assertTrue(map.containsAttribute("tickets"));
    Assert.assertTrue(map.containsAttribute("totalTickets"));
    Assert.assertTrue(map.containsAttribute("serviceCategoryList"));
    Assert.assertTrue(map.containsAttribute("alerts_for_today"));
    List<Event> events = (ArrayList<Event>) map.get("alerts_for_today");
    Assert.assertEquals(2, events.size());

    map.clear();
    asUser(userDAO.getUserByParam("username", "root", true));
    mockRequest = new MockHttpServletRequest();
    mockRequest.setAttribute("effectiveTenant", controller.getTenant());
    ((MockHttpServletRequest) mockRequest).setParameter("lang", "en_US");
    mockRequest.setAttribute("isSurrogatedTenant", Boolean.FALSE);
    Assert.assertEquals("main.home_service_with_second_level", controller.home(controller.getTenant(),
            controller.getTenant().getUuid(), false, map, new MockHttpSession(), mockRequest));
    Assert.assertTrue(map.containsAttribute("tenant"));
    Assert.assertTrue(map.containsAttribute("users"));
    Assert.assertTrue(map.containsAttribute("tickets"));
    Assert.assertTrue(map.containsAttribute("reportFusionNR"));
    Assert.assertTrue(map.containsAttribute("reportFusionCR"));

    map.clear();
    Tenant tenant = tenantService.getTenantByParam("id", "2", false);
    user = tenant.getOwner();
    user.setPassword(getSystemTenant().getUsers().get(0).getPassword());
    userDAO.save(user);
    asUser(user);
    mockRequest = new MockHttpServletRequest();
    mockRequest.setAttribute("effectiveTenant", controller.getTenant());
    ((MockHttpServletRequest) mockRequest).setParameter("lang", "en_US");
    mockRequest.setAttribute("isSurrogatedTenant", Boolean.FALSE);
    String resultString = controller.home(tenant, tenant.getUuid(), false, map, new MockHttpSession(),
            mockRequest);
    Assert.assertNotNull(resultString);
    Assert.assertEquals("main.home_with_second_level", resultString);
    Assert.assertTrue(map.containsAttribute("tenant"));
    Assert.assertTrue(map.containsAttribute("users"));
    Assert.assertTrue(map.containsAttribute("tickets"));
}

From source file:fragment.web.UsersControllerTest.java

@Before
public void init() throws Exception {
    map = new ModelMap();
    status = new MockSessionStatus();
    session = new MockHttpSession();
    request = new MockHttpServletRequest();
    prepareMock(true, bootstrapActivator);
    if (!isMockInstanceCreated) {

        Service ossService = serviceDAO.find(7l);
        ossService.setEnabled(true);// w w  w.  jav a2 s .c o m
        Service cloudService = serviceDAO.find(6l);
        connectorManagementService.getAllServiceInstances(cloudService);

        isMockInstanceCreated = true;
    }
    asRoot();
}

From source file:org.terasoluna.gfw.web.token.transaction.HttpSessionTransactionTokenStoreTest.java

/**
 * create a new Token key (stored token is as it is the same as sizePerTokenName)
 *//*from   w  w  w.j  a  v a2 s . c  om*/
@Test
public void testCreateAndReserveTokenKey_storedToken_is_as_same_as_sizePerTokenName()
        throws InterruptedException {
    // prepare store instance
    store = new HttpSessionTransactionTokenStore(4, 4);

    // setup parameters
    HttpSession session = new MockHttpSession();
    request.setSession(session);

    TransactionToken tokenA = new TransactionToken("tokenName", "tokenKeyA", "tokenValueA");
    store.store(tokenA);
    TimeUnit.MILLISECONDS.sleep(1);
    TransactionToken tokenB = new TransactionToken("tokenName", "tokenKeyB", "tokenValueB");
    store.store(tokenB);
    TimeUnit.MILLISECONDS.sleep(1);
    TransactionToken tokenC = new TransactionToken("tokenName", "tokenKeyC", "tokenValueC");
    store.store(tokenC);
    TimeUnit.MILLISECONDS.sleep(1);
    TransactionToken tokenD = new TransactionToken("tokenName", "tokenKeyD", "tokenValueD");
    store.store(tokenD);
    TimeUnit.MILLISECONDS.sleep(1);
    TransactionToken token1 = new TransactionToken("tokenName1", "tokenKey1", "tokenValue1");
    store.store(token1);
    TimeUnit.MILLISECONDS.sleep(1);
    TransactionToken token2 = new TransactionToken("tokenName2", "tokenKey2", "tokenValue2");
    store.store(token2);
    TimeUnit.MILLISECONDS.sleep(1);
    TransactionToken token3 = new TransactionToken("tokenName3", "tokenKey3", "tokenValue3");
    store.store(token3);

    // run
    String actual = store.createAndReserveTokenKey(tokenA.getTokenName());
    Enumeration<String> enumeration = session.getAttributeNames();
    while (enumeration.hasMoreElements()) {
        System.out.println(enumeration.nextElement());
    }

    // String expected = "";

    // assert
    assertNotNull(actual);
    assertThat(session.getAttribute(store.createSessionAttributeName(tokenA)), is(nullValue()));
    assertThat(session.getAttribute(store.createSessionAttributeName(tokenB)), is(notNullValue()));
    assertThat(session.getAttribute(store.createSessionAttributeName(tokenC)), is(notNullValue()));
    assertThat(session.getAttribute(store.createSessionAttributeName(tokenD)), is(notNullValue()));
    assertThat(session.getAttribute(store.createSessionAttributeName(token1)), is(notNullValue()));
    assertThat(session.getAttribute(store.createSessionAttributeName(token2)), is(notNullValue()));
    assertThat(session.getAttribute(store.createSessionAttributeName(token3)), is(notNullValue()));
}

From source file:fr.treeptik.cloudunit.alias.AliasControllerTestIT.java

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

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

    User user = null;/*from   w  w  w .  ja  v a 2  s  .  c om*/
    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);

    if (!isAppCreated) {
        try {
            logger.info("**********************************");
            logger.info("       Create Tomcat server       ");
            logger.info("**********************************");
            String jsonString = "{\"applicationName\":\"" + applicationName1 + "\", \"serverName\":\"" + release
                    + "\"}";
            ResultActions resultats = mockMvc.perform(post("/application").session(session)
                    .contentType(MediaType.APPLICATION_JSON).content(jsonString));
            resultats.andExpect(status().isOk());

            logger.info("Create Tomcat server");
            jsonString = "{\"applicationName\":\"" + applicationName2 + "\", \"serverName\":\"" + release
                    + "\"}";
            resultats = mockMvc.perform(post("/application").session(session)
                    .contentType(MediaType.APPLICATION_JSON).content(jsonString));
            resultats.andExpect(status().isOk());

            isAppCreated = true;

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}

From source file:cn.org.once.cstack.users.UserControllerTestIT.java

@Test
public void test10_userCreation() throws Exception {
    User user = null;/*from w  w  w  .  ja  va  2  s .c o  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);

    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:org.openmrs.web.controller.person.PersonAttributeTypeListControllerTest.java

License:asdf

/**
 * @see PersonAttributeTypeListController#updateGlobalProperties(String,String,String,String,String,HttpSession)
 *//* w w  w.j av  a2  s .co  m*/
@Test
@Verifies(value = "should save given personListingAttributeTypes", method = "updateGlobalProperties(String,String,String,String,String,HttpSession)")
public void updateGlobalProperties_shouldSaveGivenPersonListingAttributeTypes() throws Exception {
    new PersonAttributeTypeListController().updateGlobalProperties("asdf", "", "", "", "",
            new MockHttpSession());
    String attr = Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_LISTING_ATTRIBUTES);
    Assert.assertEquals("asdf", attr);
}