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:Controllers.ResembleControllerTest.java

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

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

    when(gameListService.getResemleGameByName(any(String.class)))
            .thenThrow(EmptyResultDataAccessException.class).thenReturn(rg);
    when(gameListService.insertResembleGame(any(String.class), any(String.class), any(String.class),
            any(String.class), any(String.class))).thenReturn(true);
    when(resembleTaskService.insertResembleTasks(any(ArrayList.class), any(Integer.class))).thenReturn(true);
    this.mockMvc.perform(post("/submitresemblegame").param("button", "").session(mockHttpSession))
            .andExpect(view().name("about"));
}

From source file:fragment.web.AuthenticationControllerTest.java

@SuppressWarnings("unchecked")
@Test/*w w  w.j  av a  2 s .  c  om*/
public void testLoginWithSuffixList() throws Exception {
    asRoot();
    Tenant defaultTenant = getDefaultTenant();
    defaultTenant.setUsernameSuffix("test");
    tenantService.save(defaultTenant);

    com.vmops.model.Configuration configuration = configurationService
            .locateConfigurationByName(Names.com_citrix_cpbm_username_duplicate_allowed);
    configuration.setValue("true");
    configurationService.update(configuration);

    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 {
        Assert.assertEquals("auth.login", actualResult);
    }

    List<String> suffixList = (List<String>) map.get("suffixList");
    Assert.assertEquals(1, suffixList.size());

    defaultTenant = getDefaultTenant();
    defaultTenant.setUsernameSuffix(null);
    tenantService.save(defaultTenant);

}

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

/**
 * @see RadiologyOrderFormController#postSaveRadiologyOrder(HttpServletRequest, Integer, Order,
 *      BindingResult)/* w w  w  .  ja va  2  s .  co  m*/
 */
@Test
@Verifies(value = "should set http session attribute openmrs message to study performed when study performed status is in progress and request was issued by radiology scheduler", method = "postSaveRadiologyOrder(HttpServletRequest, Integer, RadiologyOrder, BindingResult)")
public void postSaveRadiologyOrder_shouldSetHttpSessionAttributeOpenmrsMessageToStudyPerformedWhenStudyPerformedStatusIsInProgressAndRequestWasIssuedByRadiologyScheduler()
        throws Exception {

    //given
    RadiologyOrder mockRadiologyOrder = RadiologyTestData.getMockRadiologyOrder1();
    mockRadiologyOrder.getStudy().setPerformedStatus(PerformedProcedureStepStatus.IN_PROGRESS);
    User mockRadiologyScheduler = RadiologyTestData.getMockRadiologyScheduler();

    when(userContext.getAuthenticatedUser()).thenReturn(mockRadiologyScheduler);
    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("module/radiology/radiologyOrderForm"));
    assertThat((String) mockSession.getAttribute(WebConstants.OPENMRS_ERROR_ATTR),
            is("radiology.studyPerformed"));
}

From source file:fragment.web.UsersControllerTest.java

/**
 * create a user in an account which is created under a channel without overridden default time-zone and Locale value.
 * The default time-zone and Locale should be autoselected in user creation wizard.
 *//*from   w w  w .  j a  v  a2 s. c  om*/
@Test
public void testUserNewStep1WithoutConfigOverriddenAtChannel() {
    User user = userDAO.find(4L);
    asUser(user);
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    String view = controller.createStepOne(controller.getTenant(), null, map, new MockHttpSession(),
            mockRequest);
    UserForm form = (UserForm) map.get("user");
    String channelLocale = config.getDefaultLocale();
    String channelTimezone = configurationService
            .locateConfigurationByName(Names.com_citrix_cpbm_portal_settings_default_timezone).getValue();
    Assert.assertNotNull(form);
    Assert.assertNotNull(form.getUser());
    Assert.assertEquals("users.new.step1", view);
    Assert.assertEquals(user.getTenant().getAccountId(),
            ((com.citrix.cpbm.access.Tenant) map.get("userTenant")).getAccountId());
    Assert.assertEquals(channelLocale, map.get("defaultLocale"));
    Assert.assertEquals(channelTimezone, ((UserForm) map.get("user")).getTimeZone());
}

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

/**
 * @see RadiologyOrderFormController#discontinueRadiologyOrder(HttpServletRequest,RadiologyOrder,DiscontinuationOrderRequest,BindingResult)
 * @verifies discontinue non discontinued radiology order and redirect to discontinuation order
 *///from  w  w  w.j  a  va  2s.c om
@Test
public void discontinueRadiologyOrder_shouldDiscontinueNonDiscontinuedRadiologyOrderAndRedirectToDiscontinuationOrder()
        throws Exception {

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

    DiscontinuationOrderRequest discontinuationOrderRequest = new DiscontinuationOrderRequest();
    discontinuationOrderRequest.setOrderer(mockRadiologyOrderToDiscontinue.getOrderer());
    discontinuationOrderRequest.setReasonNonCoded("Wrong Procedure");

    Order mockDiscontinuationOrder = new Order();
    mockDiscontinuationOrder.setOrderId(2);
    mockDiscontinuationOrder.setAction(Order.Action.DISCONTINUE);
    mockDiscontinuationOrder.setOrderer(discontinuationOrderRequest.getOrderer());
    mockDiscontinuationOrder.setOrderReasonNonCoded(discontinuationOrderRequest.getReasonNonCoded());
    mockDiscontinuationOrder.setPreviousOrder(mockRadiologyOrderToDiscontinue);

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

    when(radiologyOrderService.getRadiologyOrder(mockRadiologyOrderToDiscontinue.getOrderId()))
            .thenReturn(mockRadiologyOrderToDiscontinue);
    when(radiologyOrderService.discontinueRadiologyOrder(mockRadiologyOrderToDiscontinue,
            mockDiscontinuationOrder.getOrderer(), mockDiscontinuationOrder.getOrderReasonNonCoded()))
                    .thenReturn(mockDiscontinuationOrder);

    BindingResult resultDiscontinueOrderRequest = mock(BindingResult.class);
    assertThat(mockRadiologyOrderToDiscontinue.getAction(), is(Order.Action.NEW));
    ModelAndView modelAndView = radiologyOrderFormController.discontinueRadiologyOrder(mockRequest,
            mockRadiologyOrderToDiscontinue, discontinuationOrderRequest, resultDiscontinueOrderRequest);

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

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

@Test
public void verifyNoPromptWithExistingToken() throws Exception {
    final Principal principal = mock(Principal.class);
    when(principal.getId()).thenReturn(PRINCIPAL_ID);

    final Authentication authentication = mock(Authentication.class);
    when(authentication.getPrincipal()).thenReturn(principal);

    final TicketGrantingTicket ticketGrantingTicket = mock(TicketGrantingTicket.class);
    when(ticketGrantingTicket.isExpired()).thenReturn(false);
    when(ticketGrantingTicket.getAuthentication()).thenReturn(authentication);

    final TicketRegistry ticketRegistry = mock(TicketRegistry.class);
    when(ticketRegistry.getTicket(TICKET_GRANTING_TICKET_ID)).thenReturn(ticketGrantingTicket);

    final Map<String, Scope> scopeMap = new HashMap<>();
    scopeMap.put("scope1", new Scope("scope1", "description2"));
    scopeMap.put("scope2", new Scope("scope2", "description2"));

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.getScopes(anySetOf(String.class))).thenReturn(scopeMap);
    when(centralOAuthService.isAccessToken(TokenType.ONLINE, CLIENT_ID, PRINCIPAL_ID, scopeMap.keySet()))
            .thenReturn(true);// w  w w  .  j  av a  2  s  . c o m
    when(centralOAuthService.isRefreshToken(CLIENT_ID, PRINCIPAL_ID, scopeMap.keySet())).thenReturn(false);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET",
            CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL);
    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.putValue(OAuthConstants.OAUTH20_LOGIN_TICKET_ID, TICKET_GRANTING_TICKET_ID);
    mockSession.putValue(OAuthConstants.OAUTH20_SCOPE, SCOPE);
    mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME);
    mockSession.putValue(OAuthConstants.OAUTH20_CLIENT_ID, CLIENT_ID);
    mockSession.putValue(OAuthConstants.OAUTH20_TOKEN_TYPE, TokenType.ONLINE);
    mockRequest.setSession(mockSession);

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.setTicketRegistry(ticketRegistry);
    oauth20WrapperController.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertTrue(modelAndView.getView() instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) modelAndView.getView();
    assertTrue(redirectView.getUrl()
            .endsWith(CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_ACTION_URL + "?action=allow"));

    assertEquals(scopeMap.keySet(), mockSession.getAttribute(OAuthConstants.OAUTH20_SCOPE_SET));
}

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

@Test
public void verifyResponseIsCodeWithState() throws Exception {
    final AuthorizationCode authorizationCode = mock(AuthorizationCode.class);
    when(authorizationCode.getId()).thenReturn(AC_ID);

    final Set<String> scopes = new HashSet<>();
    scopes.add(NAME1);//  ww w .j a  v  a2  s.  co m
    scopes.add(NAME2);

    final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class);
    when(centralOAuthService.grantAuthorizationCode(TokenType.OFFLINE, CLIENT_ID, TICKET_GRANTING_TICKET_ID,
            REDIRECT_URI, scopes)).thenReturn(authorizationCode);

    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET",
            CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_ACTION_URL);
    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.putValue(OAuthConstants.OAUTH20_CLIENT_ID, CLIENT_ID);
    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_SET, scopes);
    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.setCentralOAuthService(centralOAuthService);
    oauth20WrapperController.afterPropertiesSet();

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertTrue(modelAndView.getView() instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) modelAndView.getView();
    assertEquals(redirectView.getUrl(),
            REDIRECT_URI + "?" + OAuthConstants.CODE + "=" + AC_ID + "&" + OAuthConstants.STATE + '=' + STATE);

    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:fragment.web.UsersControllerTest.java

@Test
public void testUserNewDifferentTenantAsRoot() {
    asRoot();//from  w w  w .  j ava  2s .  c o  m

    Tenant other = tenantDAO.find(3L);
    MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setAttribute("isSurrogatedTenant", false);
    String view = controller.createStepOne(other, other.getUuid(), map, new MockHttpSession(), mockRequest);
    UserForm form = (UserForm) map.get("user");
    Assert.assertNotNull(form);
    Assert.assertNotNull(form.getUser());
    Assert.assertEquals("users.new.step1", view);
    Assert.assertEquals(other.getAccountId(),
            ((com.citrix.cpbm.access.Tenant) map.get("userTenant")).getAccountId());
}

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

@Test(expected = IllegalStateException.class)
public void testCreateAndReserveTokenKey_generate_failed() throws Exception {
    // prepare store instance
    store = new HttpSessionTransactionTokenStore(new TokenStringGenerator() {
        @Override// w  ww . ja  va2  s  . com
        public String generate(String seed) {
            // return always same value
            return "xxxxx";
        }
    }, 5, 5);

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

    session.setAttribute(HttpSessionTransactionTokenStore.TOKEN_HOLDER_SESSION_ATTRIBUTE_PREFIX + "foo"
            + TransactionToken.TOKEN_STRING_SEPARATOR + "xxxxx", "already in!");
    try {
        store.createAndReserveTokenKey("foo");
    } catch (Exception e) {
        assertThat(e.getMessage(), is("token key generation failed within retry count 5"));
        throw e;
    }
}

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

/**
 * @see RadiologyOrderFormController#postSaveRadiologyOrder(HttpServletRequest, Integer, Order,
 *      BindingResult)//from  w  ww.  j  a  v  a 2s . c  o  m
 */
@Test
@Verifies(value = "should not redirect if radiology order is not valid according to order validator", method = "postSaveRadiologyOrder(HttpServletRequest, Integer, RadiologyOrder, BindingResult)")
public void postSaveRadiologyOrder_shouldNotRedirectIfRadiologyOrderIsNotValidAccordingToOrderValidator()
        throws Exception {

    //given
    RadiologyOrder mockRadiologyOrder = RadiologyTestData.getMockRadiologyOrder1();
    User mockRadiologyScheduler = RadiologyTestData.getMockRadiologyScheduler();

    when(userContext.getAuthenticatedUser()).thenReturn(mockRadiologyScheduler);
    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(true);

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

    assertNotNull(modelAndView);
    assertThat(modelAndView.getViewName(), is("module/radiology/radiologyOrderForm"));
}