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:ltistarter.BaseApplicationTest.java

/**
 * Makes a new session which contains authentication roles,
 * this allows us to test requests with varying types of security
 *
 * @param username the username to set for the session
 * @param roles    all the roles to grant for this session
 * @return the session object to pass to mockMvc (e.g. mockMvc.perform(get("/").session(session))
 *//*from  w  ww.j  a  v  a2  s  .  c  o m*/
public MockHttpSession makeAuthSession(String username, String... roles) {
    if (StringUtils.isEmpty(username)) {
        username = "azeckoski";
    }
    MockHttpSession session = new MockHttpSession();
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            SecurityContextHolder.getContext());
    Collection<GrantedAuthority> authorities = new HashSet<>();
    if (roles != null && roles.length > 0) {
        for (String role : roles) {
            authorities.add(new SimpleGrantedAuthority(role));
        }
    }
    //Authentication authToken = new UsernamePasswordAuthenticationToken("azeckoski", "password", authorities); // causes a NPE when it tries to access the Principal
    Principal principal = new MyOAuthAuthenticationHandler.NamedOAuthPrincipal(username, authorities, "key",
            "signature", "HMAC-SHA-1", "signaturebase", "token");
    Authentication authToken = new UsernamePasswordAuthenticationToken(principal, null, authorities);
    SecurityContextHolder.getContext().setAuthentication(authToken);
    return session;
}

From source file:org.sventon.web.filter.ConfigAuthorizationFilterTest.java

@Test
public void testDoFilterInternalApplicationConfiguredEditEnabledAlreadyLoggedIn() throws Exception {
    final ConfigAuthorizationFilter filter = new ConfigAuthorizationFilter(application);

    final MockHttpSession session = new MockHttpSession();
    session.setAttribute("isAdminLoggedIn", true);

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setSession(session);//from   w w  w .j  ava  2  s. co  m

    final HttpServletResponse response = new MockHttpServletResponse();
    final MockFilterChain filterChain = new MockFilterChain();

    application.setConfigured(true);
    application.setEditableConfig(true);

    filter.doFilterInternal(request, response, filterChain);

    assertSame(request, filterChain.getRequest());
    assertSame(response, filterChain.getResponse());
    assertTrue((Boolean) request.getAttribute("isEdit"));
}

From source file:fragment.web.AuthenticationControllerTest.java

@Before
public void init() {
    map = new ModelMap();
    session = new MockHttpSession();
    asAnonymous();
}

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

@Test
public void tokenRequestFailsIfBadParameter() {
    final MockHttpSession session = new MockHttpSession();
    request.setSession(session);/* w  ww  .  j a  v a  2  s.  c  o  m*/
    request.setParameter(ANOTHER_PARAMETER, TICKET);
    request.setQueryString(ANOTHER_PARAMETER + "=" + TICKET);
    assertTrue(handler.process(request, response));
    final SessionMappingStorage storage = handler.getSessionMappingStorage();
    assertNull(storage.removeSessionByMappingId(TICKET));
}

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

@Test
public void testOKWithState() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET",
            CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL);
    mockRequest.addParameter(OAuthConstants.TICKET, SERVICE_TICKET);
    final MockHttpSession mockSession = new MockHttpSession();
    mockSession.putValue(OAuthConstants.OAUTH20_CALLBACKURL, REDIRECT_URI);
    mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME);
    mockSession.putValue(OAuthConstants.OAUTH20_STATE, STATE);
    mockRequest.setSession(mockSession);
    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController();
    oauth20WrapperController.afterPropertiesSet();
    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertEquals(OAuthConstants.CONFIRM_VIEW, modelAndView.getViewName());
    final Map<String, Object> map = modelAndView.getModel();
    assertEquals(SERVICE_NAME, map.get("serviceName"));
    assertEquals(REDIRECT_URI + "?" + OAuthConstants.CODE + "=" + SERVICE_TICKET + "&" + OAuthConstants.STATE
            + "=" + STATE, map.get("callbackUrl"));
}

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

@Test
public void verifyActionDenied() 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_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, SCOPE);
    mockRequest.setSession(mockSession);
    mockRequest.setParameter(OAuthConstants.OAUTH20_APPROVAL_PROMPT_ACTION, "deny");

    final MockHttpServletResponse mockResponse = new MockHttpServletResponse();

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

    final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse);
    assertTrue(modelAndView.getView() instanceof RedirectView);
    final RedirectView redirectView = (RedirectView) modelAndView.getView();
    assertTrue(redirectView.getUrl()//from  w ww  . j av  a2  s  . c om
            .endsWith(REDIRECT_URI + "?" + OAuthConstants.ERROR + "=" + OAuthConstants.ACCESS_DENIED));

    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.SingleSignOutFilterTests.java

@Test
public void backChannelRequest() throws IOException, ServletException {
    request.setParameter(ConfigurationKeys.LOGOUT_PARAMETER_NAME.getDefaultValue(),
            LogoutMessageGenerator.generateBackChannelLogoutMessage(TICKET));
    request.setMethod("POST");
    final MockHttpSession session = new MockHttpSession();
    SingleSignOutFilter.getSingleSignOutHandler().getSessionMappingStorage().addSessionById(TICKET, session);
    filter.doFilter(request, response, filterChain);
    assertNull(SingleSignOutFilter.getSingleSignOutHandler().getSessionMappingStorage()
            .removeSessionByMappingId(TICKET));
}

From source file:com.comcast.video.dawg.show.video.VideoSnapTest.java

@Test
public void testAddImagesToZipFile() throws IOException {
    String imageIds[] = { "", "", "" };
    MockHttpSession session = new MockHttpSession();
    MockHttpServletResponse response = new MockHttpServletResponse();
    UniqueIndexedCache<BufferedImage> imgCache = ClientCache.getClientCache(session).getImgCache();
    imageIds[0] = imgCache.storeItem(PC_IMG);
    imageIds[1] = imgCache.storeItem(PC_IMG);
    imageIds[2] = null;//from w ww .ja v  a2s  . c  o  m
    String deviceIds[] = { "000000000001", "000000000002", "000000000003" };
    int expectedZipSizeInBytes = 28954;

    VideoSnap videoSnap = new VideoSnap();

    videoSnap.addImagesToZipFile(imageIds, deviceIds, response, session);
    Assert.assertEquals(response.getContentType(), "application/zip", "Content type is not in zip format");
    String header = response.getHeader("Content-Disposition");
    Assert.assertTrue(header.contains("attachment"), "Response header does not indicates attachment");
    Assert.assertTrue(header.contains(".zip"), "Attached file is not in zip format");
    Assert.assertEquals(response.getContentAsByteArray().length, expectedZipSizeInBytes,
            "Zip file size in http response is not matching with expected zip size.");

}

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

/**
 * tokenHolder is null//from w ww .j  a  va 2  s  .c  om
 */
@Test
public void testGetAndClear01() {
    // setup parameters
    HttpSession session = new MockHttpSession();
    request.setSession(session);
    TransactionToken token = new TransactionToken("TransactionToken");

    // prepare store instance
    store = new HttpSessionTransactionTokenStore();

    // run
    String actuals = store.getAndClear(token);

    // assert
    assertNull(actuals);
}

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

/**
 * @see UserFormController#handleSubmission(WebRequest,HttpSession,String,String,String,null, String, User,BindingResult)
 *
 *///from ww w.ja  v  a  2 s  . c o m
@Test
@Verifies(value = "Creates Provider Account when Provider Account Checkbox is selected", method = "handleSubmission(WebRequest,HttpSession,String,String,String,null, String, User,BindingResult)")
public void handleSubmission_createUserProviderAccountWhenProviderAccountCheckboxIsSelected() throws Exception {
    executeDataSet(TEST_DATA);
    WebRequest request = new ServletWebRequest(new MockHttpServletRequest());
    //A user with userId=2 is preset in the Test DataSet and the relevant details are passed
    User user = Context.getUserService().getUser(2);
    Assert.assertTrue(Context.getProviderService().getProvidersByPerson(user.getPerson()).isEmpty());
    ModelMap model = new ModelMap();
    model.addAttribute("isProvider", false);
    controller.showForm(2, "true", user, model);
    controller.handleSubmission(request, new MockHttpSession(), new ModelMap(), "", null, "Test1234",
            "valid secret question", "valid secret answer", "Test1234", false, new String[] { "Provider" },
            "true", "addToProviderTable", user, new BindException(user, "user"));
    Assert.assertFalse(Context.getProviderService().getProvidersByPerson(user.getPerson()).isEmpty());
}