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:ch.ralscha.extdirectspring.controller.RouterControllerFormPostCrossDomainUploadTest.java

@Test
public void testUpload() throws Exception {
    MockMultipartHttpServletRequestBuilder request = fileUpload("/router");
    request.accept(MediaType.ALL).characterEncoding("UTF-8").session(new MockHttpSession());

    request.param("extTID", "1");
    request.param("extAction", "uploadService");
    request.param("extMethod", "upload");
    request.param("extType", "rpc");
    request.param("result", "theResult");

    request.file("fileUpload", "the content of the file".getBytes());

    MvcResult resultMvc = mockMvc.perform(request).andExpect(status().isOk())
            .andExpect(content().contentType("text/html;charset=UTF-8")).andExpect(content().encoding("UTF-8"))
            .andReturn();//www .  j  a v a 2s  .  com

    String response = resultMvc.getResponse().getContentAsString();
    String prefix = "<html><body><textarea>";
    String suffix = "</textarea><script type=\"text/javascript\">document.domain = 'rootdomain.com';</script></body></html>";
    assertThat(response).startsWith(prefix).endsWith(suffix);
    String json = response.substring(prefix.length(), response.indexOf(suffix));

    ExtDirectResponse edsResponse = ControllerUtil
            .readDirectResponse(json.getBytes(ExtDirectSpringUtil.UTF8_CHARSET));

    assertThat(edsResponse.getType()).isEqualTo("rpc");
    assertThat(edsResponse.getMessage()).isNull();
    assertThat(edsResponse.getWhere()).isNull();
    assertThat(edsResponse.getTid()).isEqualTo(1);
    assertThat(edsResponse.getAction()).isEqualTo("uploadService");
    assertThat(edsResponse.getMethod()).isEqualTo("upload");
}

From source file:org.tonguetied.web.PaginationUtilsTest.java

License:asdf

/**
 * @throws java.lang.Exception/*from w  w w  .j a  v a2s .  com*/
 */
@Before
public void setUp() throws Exception {
    request = new MockHttpServletRequest();
    request.setParameter(PAGE_PARAM, "3");
    request.setParameter(PAGE_SORT, "test");
    request.setParameter(PAGE_ORDER, "2");

    MockHttpSession session = new MockHttpSession();
    session.setAttribute(PAGE_PARAM_SESSION, Integer.valueOf("9"));
    request.setSession(session);
}

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

@Test
public void tokenRequest() throws IOException, ServletException {
    request.setParameter(Protocol.CAS2.getArtifactParameterName(), TICKET);
    request.setQueryString(Protocol.CAS2.getArtifactParameterName() + "=" + TICKET);
    final MockHttpSession session = new MockHttpSession();
    request.setSession(session);/*from   w  w w  . j  a va 2s . c  om*/
    filter.doFilter(request, response, filterChain);
    assertEquals(session, SingleSignOutFilter.getSingleSignOutHandler().getSessionMappingStorage()
            .removeSessionByMappingId(TICKET));
}

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

/**
 * @see ChangePasswordFormController#handleSubmission(HttpSession, String, String, String, String, String, User, BindingResult)
 *//*from www .ja v a2s.  c o m*/
@Test
@Verifies(value = "display an error message when the password and confirm password entries are different", method = "handleSubmission()")
public void handleSubmission_shouldDisplayErrorMessageWhenPasswordAndConfirmPasswordAreNotSame()
        throws Exception {
    ChangePasswordFormController controller = new ChangePasswordFormController();
    BindException errors = new BindException(controller.formBackingObject(), "user");

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

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

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

License:asdf

/**
 * @see PersonAttributeTypeListController#moveDown(null,HttpSession)
 */// w w  w .java  2  s.  co m
@Test
@Verifies(value = "should move selected ids down in the list", method = "moveDown(null,HttpSession)")
public void moveDown_shouldMoveSelectedIdsDownInTheList() throws Exception {
    // sanity check
    List<PersonAttributeType> allTypes = Context.getPersonService().getAllPersonAttributeTypes();
    Assert.assertEquals(1, allTypes.get(0).getId().intValue());

    // the test
    Integer[] ids = new Integer[] { 1 };
    new PersonAttributeTypeListController().moveDown(ids, new MockHttpSession());
    allTypes = Context.getPersonService().getAllPersonAttributeTypes();
    Assert.assertEquals("The types didn't move correctly", 8, allTypes.get(0).getId().intValue());
}

From source file:org.jasig.cas.client.util.HttpServletRequestWrapperFilterTests.java

public void testIsUserInRole() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    final MockHttpSession session = new MockHttpSession();
    final MockFilterConfig config = new MockFilterConfig();

    config.addInitParameter("roleAttribute", "memberOf");
    final HttpServletRequestWrapperFilter filter = new HttpServletRequestWrapperFilter();
    filter.init(config);//from  ww  w.ja v  a2s  . c o m

    final Map<String, Object> attributes = new HashMap<String, Object>();
    attributes.put("memberOf", "administrators");
    final AttributePrincipal principal = new AttributePrincipalImpl("alice", attributes);
    session.setAttribute(AbstractCasFilter.CONST_CAS_ASSERTION, new AssertionImpl(principal));

    request.setSession(session);

    filter.doFilter(request, new MockHttpServletResponse(), createFilterChain());
    assertEquals("alice", this.mockRequest.getRemoteUser());
    assertTrue(this.mockRequest.isUserInRole("administrators"));
    assertFalse(this.mockRequest.isUserInRole("ADMINISTRATORS"));
    assertFalse(this.mockRequest.isUserInRole("users"));
    assertFalse(this.mockRequest.isUserInRole(null));

    filter.destroy();
}

From source file:org.openmrs.web.controller.concept.ConceptStopWordFormControllerTest.java

/**
 * @see {@link ConceptStopWordFormController#handleSubmission(HttpSession, ConceptStopWordFormBackingObject, org.springframework.validation.BindingResult)
 *//*from   w w  w . ja va 2  s  .c o  m*/
@Test
@Verifies(value = "should return error message for an empty ConceptStopWord", method = "handleSubmission(HttpSession, ConceptStopWordFormBackingObject, BindingResult)")
public void handleSubmission_shouldReturnErrorMessageForAnEmptyConceptStopWord() throws Exception {
    ConceptStopWordFormController controller = (ConceptStopWordFormController) applicationContext
            .getBean("conceptStopWordFormController");

    HttpSession mockSession = new MockHttpSession();

    ConceptStopWord conceptStopWord = new ConceptStopWord("", Locale.CANADA);

    mockSession.setAttribute("value", conceptStopWord.getValue());
    BindException errors = new BindException(conceptStopWord, "value");

    controller.handleSubmission(mockSession, conceptStopWord, errors);
    ObjectError objectError = (ObjectError) errors.getAllErrors().get(0);

    Assert.assertTrue(errors.hasErrors());
    Assert.assertEquals(1, errors.getErrorCount());
    Assert.assertEquals("ConceptStopWord.error.value.empty", objectError.getCode());
}

From source file:com.vdenotaris.spring.boot.security.saml.web.CommonTestSupport.java

public MockHttpSession mockAnonymousHttpSession() {
    MockHttpSession mockSession = new MockHttpSession();
    SecurityContext mockSecurityContext = mock(SecurityContext.class);

    AnonymousAuthenticationToken principal = new AnonymousAuthenticationToken(ANONYMOUS_USER_KEY,
            ANONYMOUS_USER_PRINCIPAL, AUTHORITIES);

    when(mockSecurityContext.getAuthentication()).thenReturn(principal);

    SecurityContextHolder.setContext(mockSecurityContext);
    mockSession.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            mockSecurityContext);// w ww  .  j  a  v  a2 s .  c om

    return mockSession;
}

From source file:org.openmrs.module.formfilter.web.controller.ViewFormFilterControllerTest.java

/**
 * @see {@link ViewFormFilterController#deleteFormFilterProperty(ModelMap, javax.servlet.http.HttpSession, int, int)}
 *//* w  w w .  jav a 2s  .co m*/
@Test
@Verifies(value = "should delete FormFilterProperty by id", method = "deleteFormFilterProperty(ModelMap, javax.servlet.http.HttpSession, int, int)")
public void deleteFormFilterProperty_shouldDeleteFormFilterPropertyById() {
    FormFilterService formFilterService = Context.getService(FormFilterService.class);
    ViewFormFilterController controller = new ViewFormFilterController();
    controller.deleteFormFilterProperty(null, new MockHttpSession(), 1, 0);
    Assert.assertNull(formFilterService.getFormFilterProperty(1));
}

From source file:ch.ralscha.extdirectspring.controller.ControllerUtil.java

public static ExtDirectPollResponse performPollRequest(MockMvc mockMvc, String bean, String method,
        String event, Map<String, String> params, HttpHeaders headers, List<Cookie> cookies,
        boolean withSession) throws Exception {
    MockHttpServletRequestBuilder request = post("/poll/" + bean + "/" + method + "/" + event)
            .accept(MediaType.ALL).contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8");

    if (cookies != null) {
        request.cookie(cookies.toArray(new Cookie[cookies.size()]));
    }/*from  ww  w  . j  a v a  2s.  c  om*/

    if (withSession) {
        request.session(new MockHttpSession());
    }

    if (params != null) {
        for (String paramName : params.keySet()) {
            request.param(paramName, params.get(paramName));
        }
    }

    if (headers != null) {
        request.headers(headers);
    }

    MvcResult result = mockMvc.perform(request).andExpect(status().isOk())
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(content().encoding("UTF-8")).andReturn();

    return readDirectPollResponse(result.getResponse().getContentAsByteArray());
}