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.concept.ConceptStopWordListControllerTest.java

/**
 * @see {@link ConceptStopWordListController#handleSubmission(javax.servlet.http.HttpSession, String[])
 *///  w  w  w.j  a v a  2 s .  co  m
@Test
@Verifies(value = "should add the already deleted error message in session attribute if delete the same word twice", method = "handleSubmission(HttpSession, String[])")
public void handleSubmission_shouldAddTheDeleteErrorMessageInSession() throws Exception {
    ConceptStopWordListController controller = (ConceptStopWordListController) applicationContext
            .getBean("conceptStopWordListController");

    HttpSession mockSession = new MockHttpSession();

    controller.handleSubmission(mockSession, new String[] { "1", "1" });

    String successMessage = (String) mockSession.getAttribute(WebConstants.OPENMRS_MSG_ATTR);
    String errorMessage = (String) mockSession.getAttribute(WebConstants.OPENMRS_ERROR_ATTR);

    Assert.assertNotNull(successMessage);
    Assert.assertNotNull(errorMessage);
    Assert.assertEquals("ConceptStopWord.error.notfound", errorMessage);
}

From source file:org.ambraproject.BaseWebTest.java

protected void setupContext(Map<String, Object> sessionAttributes) {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpSession session = new MockHttpSession();
    for (String attr : sessionAttributes.keySet()) {
        session.setAttribute(attr, sessionAttributes.get(attr));
    }/*  w w  w . j a va 2 s.  co  m*/
    request.setSession(session);

    ConfigurationManager configurationManager = new ConfigurationManager();
    configurationManager.addContainerProvider(new XWorkConfigurationProvider());
    Configuration config = configurationManager.getConfiguration();
    Container strutsContainer = config.getContainer();

    ValueStack stack = strutsContainer.getInstance(ValueStackFactory.class).createValueStack();
    stack.getContext().put(ServletActionContext.CONTAINER, strutsContainer);

    ActionContext.setContext(new ActionContext(stack.getContext()));
    ActionContext.getContext().setSession(sessionAttributes);
    ServletActionContext.setContext(ActionContext.getContext());
    ServletActionContext.setRequest(request);
}

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

@Test
public void testRenew() 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
        }//  w ww.  ja v  a2 s  . co m
    };

    this.filter.setRenew(true);
    request.setSession(session);
    this.filter.doFilter(request, response, filterChain);

    assertNotNull(response.getRedirectedUrl());
    assertTrue(response.getRedirectedUrl().indexOf("renew=true") != -1);
}

From source file:org.jasig.cas.support.oauth.web.flow.OAuthActionTests.java

@Test
public void testFinishAuthentication() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setParameter(OAuthConstants.OAUTH_PROVIDER, "FacebookProvider");

    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.setAttribute(OAuthConstants.THEME, MY_THEME);
    mockSession.setAttribute(OAuthConstants.LOCALE, MY_LOCALE);
    mockSession.setAttribute(OAuthConstants.METHOD, MY_METHOD);
    final Service service = new SimpleWebApplicationServiceImpl(MY_SERVICE);
    mockSession.setAttribute(OAuthConstants.SERVICE, service);
    mockRequest.setSession(mockSession);

    final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);

    final MockRequestContext mockRequestContext = new MockRequestContext();
    mockRequestContext.setExternalContext(servletExternalContext);

    final CentralAuthenticationService centralAuthenticationService = mock(CentralAuthenticationService.class);

    final OAuthAction oAuthAction = new OAuthAction();
    oAuthAction.setConfiguration(newConfiguration());
    oAuthAction.setCentralAuthenticationService(centralAuthenticationService);
    final Event event = oAuthAction.execute(mockRequestContext);
    assertEquals("success", event.getId());
    assertEquals(MY_THEME, mockRequest.getAttribute(OAuthConstants.THEME));
    assertEquals(MY_LOCALE, mockRequest.getAttribute(OAuthConstants.LOCALE));
    assertEquals(MY_METHOD, mockRequest.getAttribute(OAuthConstants.METHOD));
    final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
    assertEquals(service, flowScope.get(OAuthConstants.SERVICE));
}

From source file:org.jasig.cas.support.oauth.web.OAuth20AuthorizeCallbackActionControllerTests.java

@Test
public void verifyNoClientIdError() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET",
            CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_ACTION_URL);
    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.putValue(OAuthConstants.OAUTH20_RESPONSE_TYPE, RESPONSE_TYPE);
    mockSession.putValue(OAuthConstants.OAUTH20_STATE, STATE);
    mockSession.putValue(OAuthConstants.OAUTH20_REDIRECT_URI, REDIRECT_URI);
    mockSession.putValue(OAuthConstants.OAUTH20_TOKEN_TYPE, TokenType.OFFLINE);
    mockSession.putValue(OAuthConstants.OAUTH20_LOGIN_TICKET_ID, TICKET_GRANTING_TICKET_ID);
    mockSession.putValue(OAuthConstants.OAUTH20_SCOPE, SCOPE);
    mockRequest.setSession(mockSession);
    mockRequest.setParameter(OAuthConstants.OAUTH20_APPROVAL_PROMPT_ACTION,
            OAuthConstants.OAUTH20_APPROVAL_PROMPT_ACTION_ALLOW);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(OAuthConstants.ERROR_VIEW, modelAndView.getViewName());

    assertNull(mockSession.getAttribute(OAuthConstants.OAUTH20_RESPONSE_TYPE));
    assertNull(mockSession.getAttribute(OAuthConstants.OAUTH20_CLIENT_ID));
    assertNull(mockSession.getAttribute(OAuthConstants.OAUTH20_STATE));
    assertNull(mockSession.getAttribute(OAuthConstants.OAUTH20_REDIRECT_URI));
    assertNull(mockSession.getAttribute(OAuthConstants.OAUTH20_TOKEN_TYPE));
    assertNull(mockSession.getAttribute(OAuthConstants.OAUTH20_LOGIN_TICKET_ID));
    assertNull(mockSession.getAttribute(OAuthConstants.OAUTH20_SCOPE_SET));
}

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

@Test
public void backChannelLogoutOK() {
    final String logoutMessage = LogoutMessageGenerator.generateBackChannelLogoutMessage(TICKET);
    request.setParameter(LOGOUT_PARAMETER_NAME, logoutMessage);
    request.setMethod("POST");
    final MockHttpSession session = new MockHttpSession();
    handler.getSessionMappingStorage().addSessionById(TICKET, session);
    assertFalse(handler.process(request, response));
    assertTrue(session.isInvalid());/*from  w  w w  . j  a v  a 2s. c om*/
}

From source file:org.jasig.cas.support.pac4j.web.flow.ClientActionTests.java

@Test
public void verifyFinishAuthentication() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "FacebookClient");

    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.setAttribute(ClientAction.THEME, MY_THEME);
    mockSession.setAttribute(ClientAction.LOCALE, MY_LOCALE);
    mockSession.setAttribute(ClientAction.METHOD, MY_METHOD);
    final Service service = new SimpleWebApplicationServiceImpl(MY_SERVICE);
    mockSession.setAttribute(ClientAction.SERVICE, service);
    mockRequest.setSession(mockSession);

    final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);

    final MockRequestContext mockRequestContext = new MockRequestContext();
    mockRequestContext.setExternalContext(servletExternalContext);

    final FacebookClient facebookClient = new MockFacebookClient();
    final Clients clients = new Clients(MY_LOGIN_URL, facebookClient);

    final TicketGrantingTicket tgt = new TicketGrantingTicketImpl(TGT_ID, mock(Authentication.class),
            mock(ExpirationPolicy.class));
    final CentralAuthenticationService casImpl = mock(CentralAuthenticationService.class);
    when(casImpl.createTicketGrantingTicket(any(Credential.class))).thenReturn(tgt);
    final ClientAction action = new ClientAction(casImpl, clients);
    final Event event = action.execute(mockRequestContext);
    assertEquals("success", event.getId());
    assertEquals(MY_THEME, mockRequest.getAttribute(ClientAction.THEME));
    assertEquals(MY_LOCALE, mockRequest.getAttribute(ClientAction.LOCALE));
    assertEquals(MY_METHOD, mockRequest.getAttribute(ClientAction.METHOD));
    assertEquals(MY_SERVICE, mockRequest.getAttribute(ClientAction.SERVICE));
    final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
    final MutableAttributeMap requestScope = mockRequestContext.getRequestScope();
    assertEquals(service, flowScope.get(ClientAction.SERVICE));
    assertEquals(TGT_ID, flowScope.get(TGT_NAME));
    assertEquals(TGT_ID, requestScope.get(TGT_NAME));
}

From source file:org.openmrs.web.controller.person.PersonAttributeTypeListControllerTest.java

License:asdf

/**
 * @see PersonAttributeTypeListController#moveUp(null,HttpSession)
 *//*from  ww w .j  a va 2 s .  c o m*/
@Test
@Verifies(value = "should not fail if given first id", method = "moveUp(null,HttpSession)")
public void moveUp_shouldNotFailIfGivenFirstId() throws Exception {
    // sanity check
    List<PersonAttributeType> allTypes = Context.getPersonService().getAllPersonAttributeTypes();
    Assert.assertEquals(1, allTypes.get(0).getId().intValue());

    // the test
    new PersonAttributeTypeListController().moveUp(new Integer[] { 1 }, new MockHttpSession());
}

From source file:fr.treeptik.cloudunit.snapshot.AbstractSnapshotControllerTestIT.java

@Before
public void setup() {
    logger.info("setup");
    this.mockMvc = MockMvcBuilders.webAppContextSetup(context).addFilters(springSecurityFilterChain).build();

    User user = null;//from w  ww  . ja  va2s .  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);

}

From source file:com.comcast.video.dawg.controller.park.ParkControllerTest.java

@SuppressWarnings("unchecked")
@Test(dataProvider = "testUserFrontWithValidTokenData")
public void testUserFrontWithValidToken(String token, String tag, String q, String[] sort,
        String[] otherTagsExp) {/*from w  ww  .  j  a  va  2 s  .  com*/
    ParkController controller = new ParkController();
    Map<String, Object>[] filteredStbs = new HashMap[1];
    Map<String, Object>[] allStbs = new HashMap[2];
    Map<String, Object> stb1 = new HashMap<String, Object>();
    stb1.put(MetaStb.ID, "sample");
    stb1.put(MetaStb.TAGS, Arrays.asList("tag1"));
    stb1.put(MetaStb.MACADDRESS, "00:00:00:00:00");

    Map<String, Object> stb2 = new HashMap<String, Object>();
    stb2.put(MetaStb.ID, "otherDevice");
    stb2.put(MetaStb.TAGS, Arrays.asList("tag2", "tag3"));
    stb2.put(MetaStb.MACADDRESS, "00:00:00:00:01");

    filteredStbs[0] = stb1;
    allStbs[0] = stb1;
    allStbs[1] = stb2;

    ReflectionTestUtils.setField(controller, "serverUtils", utils);

    ParkService mockService = EasyMock.createMock(ParkService.class);
    if (q == null) {
        EasyMock.expect(mockService.findAll((Pageable) EasyMock.anyObject())).andReturn(allStbs);
    } else {
        EasyMock.expect(
                mockService.findByKeys((String[]) EasyMock.anyObject(), (Pageable) EasyMock.anyObject()))
                .andReturn(filteredStbs);
        EasyMock.expect(mockService.findAll()).andReturn(allStbs);
    }
    if (tag != null) {
        EasyMock.expect(
                mockService.findByCriteria((Criteria) EasyMock.anyObject(), (Pageable) EasyMock.anyObject()))
                .andReturn(filteredStbs);
    }
    EasyMock.replay(mockService);
    ReflectionTestUtils.setField(controller, "service", mockService);
    ReflectionTestUtils.setField(controller, "config", createConfig());

    Integer page = Integer.valueOf(1);
    Integer size = Integer.valueOf(1);
    Boolean asc = Boolean.TRUE;

    try {
        Model model = new BindingAwareModelMap();
        MockHttpSession session = new MockHttpSession();
        Assert.assertEquals("index",
                controller.userFront(token, tag, q, page, size, asc, sort, model, session));
        Assert.assertEquals(model.asMap().get("search"), q == null ? "" : q);
        String otherTagsJson = (String) model.asMap().get("otherTags");
        String deviceTagsJson = (String) model.asMap().get("deviceTags");
        JsonCerealEngine engine = new JsonCerealEngine();
        List<String> otherTags = engine.readFromString(otherTagsJson, List.class);
        Map<String, List<String>> deviceTags = engine.readFromString(deviceTagsJson, Map.class);

        Assert.assertEquals(otherTags.size(), otherTagsExp.length);
        for (String tags : otherTagsExp) {
            Assert.assertTrue(otherTags.contains(tags));
        }
        Assert.assertEquals(deviceTags.size(), q != null ? 1 : 2);
        Assert.assertTrue(deviceTags.containsKey("sample"));
        Assert.assertTrue(deviceTags.get("sample").contains("tag1"));
    } catch (CerealException e) {

        Assert.fail(e.getMessage());
    }
}