Java Code Examples for org.springframework.mock.web.MockHttpSession#setAttribute()

The following examples show how to use org.springframework.mock.web.MockHttpSession#setAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestDataNodeControl.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public void testDatanodeControl() {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    MockHttpSession session = new MockHttpSession();
    UserDO user = new UserDO();
    user.setStatus(ConstantDefine.NORMAL);
    user.setUser_role(ConstantDefine.CLUSTER_ADMIN);
    session.setAttribute("user", user);
    request.setSession(session);
    request.addParameter("clusterId", "1");
    try {
        ModelAndView mav = datanodeControl.handleRequest(request, new MockHttpServletResponse());
        Assert.assertEquals("1", String.valueOf(mav.getModel().get("clusterId")));
        Assert.assertEquals("true", String.valueOf(mav.getModel().get("uniform")));
        Assert.assertEquals("true", String.valueOf(mav.getModel().get("connecitonFlag")));
        Assert.assertEquals(1, ((List) mav.getModel().get("cList")).size());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        Assert.fail();
    }
}
 
Example 2
Source File: TestAddCobar.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
public void testAddCobar() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    MockHttpSession session = new MockHttpSession();
    UserDO user = new UserDO();
    user.setStatus(ConstantDefine.NORMAL);
    user.setUser_role(ConstantDefine.CLUSTER_ADMIN);
    session.setAttribute("user", user);
    request.setSession(session);
    request.addParameter("clusterId", "1");
    request.addParameter("host", "1.2.4.3");
    request.addParameter("cobarName", "test");
    request.addParameter("port", "8066");
    request.addParameter("userName", "test");
    request.addParameter("password", "TTT");
    request.addParameter("status", "ACTIVE");

    ModelAndView mav = addcobar.handleRequest(request, new MockHttpServletResponse());
    Assert.assertEquals("add cobar success", String.valueOf(mav.getModel().get("info")));
}
 
Example 3
Source File: CommonTestSupport.java    From spring-boot-security-saml-sample with Apache License 2.0 6 votes vote down vote up
public MockHttpSession mockHttpSession(boolean secured) {
    MockHttpSession mockSession = new MockHttpSession();

    SecurityContext mockSecurityContext = mock(SecurityContext.class);

    if (secured) {
        ExpiringUsernameAuthenticationToken principal =
                new ExpiringUsernameAuthenticationToken(null, USER_DETAILS, USER_NAME, AUTHORITIES);
        principal.setDetails(USER_DETAILS);
        when(mockSecurityContext.getAuthentication()).thenReturn(principal);
    }

    SecurityContextHolder.setContext(mockSecurityContext);
    mockSession.setAttribute(
            HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
            mockSecurityContext);

    return mockSession;
}
 
Example 4
Source File: CommonTestSupport.java    From spring-boot-security-saml-sample with Apache License 2.0 6 votes vote down vote up
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);

    return mockSession;
}
 
Example 5
Source File: ManualLogoutIntegrationTest.java    From tutorials with MIT License 6 votes vote down vote up
@WithMockUser(value = "spring")
@Test
public void givenLoggedUserWhenUserLogoutThenSessionClearedAndAllCookiesCleared() throws Exception {

    MockHttpSession session = new MockHttpSession();
    session.setAttribute(ATTRIBUTE_NAME, ATTRIBUTE_VALUE);

    Cookie randomCookie = new Cookie(COOKIE_NAME, COOKIE_VALUE);
    randomCookie.setMaxAge(EXPIRY); // 10 minutes

    MockHttpServletRequest requestStateAfterLogout = this.mockMvc.perform(post("/cookies/cookielogout").secure(true).with(csrf()).session(session).cookie(randomCookie))
            .andExpect(status().is3xxRedirection())
            .andExpect(unauthenticated())
            .andExpect(cookie().maxAge(COOKIE_NAME, 0))
            .andReturn()
            .getRequest();

    HttpSession sessionStateAfterLogout = requestStateAfterLogout.getSession();
    assertNull(sessionStateAfterLogout.getAttribute(ATTRIBUTE_NAME));
}
 
Example 6
Source File: UserControllerTest.java    From SpringAll with MIT License 5 votes vote down vote up
@Before
  public void setupMockMvc(){
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
session = new MockHttpSession();
User user =new User();
user.setUsername("Dopa");
user.setPasswd("ac3af72d9f95161a502fd326865c2f15");
   session.setAttribute("user",user); 
  }
 
Example 7
Source File: ClientActionTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@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));
}
 
Example 8
Source File: AbstractTest4TSS.java    From boubei-tss with Apache License 2.0 5 votes vote down vote up
protected void initContext() {
	Global.setContext(super.applicationContext);
	
	Context.setResponse(response = new MockHttpServletResponse());
	
	request = new MockHttpServletRequest();
	MockHttpSession session = new MockHttpSession();
	session.setAttribute(SSOConstants.RANDOM_KEY, 100);
	request.setSession(session);
	
	Context.initRequestContext(request);
}
 
Example 9
Source File: ClientActionTests.java    From cas4.0.x-server-wechat with Apache License 2.0 5 votes vote down vote up
@Test
public void testFinishAuthentication() 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 ClientAction action = new ClientAction(mock(CentralAuthenticationService.class), 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));
    final MutableAttributeMap flowScope = mockRequestContext.getFlowScope();
    assertEquals(service, flowScope.get(ClientAction.SERVICE));
}
 
Example 10
Source File: DhisWebSpringTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public MockHttpSession getSession( String... authorities )
{
    SecurityContextHolder.getContext().setAuthentication( getPrincipal( authorities ) );
    MockHttpSession session = new MockHttpSession();

    session.setAttribute(
        HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
        SecurityContextHolder.getContext() );

    return session;
}
 
Example 11
Source File: PermissionInterceptorTest.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
public void testPermissionInter() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setServletPath("/cobarDetail.htm");
    MockHttpSession session = new MockHttpSession();
    UserDO user = new UserDO();
    user.setStatus(ConstantDefine.NORMAL);
    user.setUser_role(ConstantDefine.SYSTEM_ADMIN);
    session.setAttribute("user", user);
    request.setSession(session);

    boolean rst = permissionInterceptor.preHandle(request, new MockHttpServletResponse(), null);
    Assert.assertTrue(rst);
}
 
Example 12
Source File: HomeControllerTest.java    From playground with Apache License 2.0 5 votes vote down vote up
@Test
public void testToggleExceptions() throws Exception {
	MockHttpSession session = new MockHttpSession();
	session.setAttribute("exceptionsToggle", false);
	this.mockMvc.perform(post("/exceptions").session(session)).andExpect(status().isOk())
			.andExpect(model().attribute("exceptionsState", true));
	this.mockMvc.perform(post("/exceptions").session(session)).andExpect(status().isOk())
			.andExpect(model().attribute("exceptionsState", false));
	this.mockMvc.perform(post("/exceptions").session(session)).andExpect(status().isOk())
			.andExpect(model().attribute("exceptionsState", true));
	this.mockMvc.perform(post("/exceptions").session(session)).andExpect(status().isOk())
			.andExpect(model().attribute("exceptionsState", false));
}
 
Example 13
Source File: UserRestControllerTest.java    From jeecg with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	MockHttpServletRequestBuilder requestBuilder = post("/");
	MockHttpServletRequest request = requestBuilder.buildRequest(this.wac.getServletContext());
	session = (MockHttpSession) request.getSession();

	Client c = new Client();
	TSUser u = new TSUser();
	u.setUserName("admin");
	c.setUser(u);
	session.setAttribute(session.getId(), c);

	this.mockMvc = webAppContextSetup(this.wac).build();
	this.testLogin();
}
 
Example 14
Source File: RequestUtil.java    From singleton with Eclipse Public License 2.0 4 votes vote down vote up
public static MockHttpSession getSession(WebApplicationContext webApplicationContext) {
    MockServletContext application = (MockServletContext) webApplicationContext.getServletContext();
    MockHttpSession session=new MockHttpSession();
    session.setAttribute("token", application.getAttribute("token"));
    return session;
}
 
Example 15
Source File: RequestUtil.java    From singleton with Eclipse Public License 2.0 4 votes vote down vote up
public static MockHttpSession getSession(WebApplicationContext webApplicationContext) {
    MockServletContext application = (MockServletContext) webApplicationContext.getServletContext();
    MockHttpSession session=new MockHttpSession();
    session.setAttribute("token", application.getAttribute("token"));
    return session;
}
 
Example 16
Source File: UserMvcTests.java    From jakduk-api with MIT License 4 votes vote down vote up
@Test
@WithMockUser
public void createSocialUserTest() throws Exception {

    this.whenCustomValdation();

    AttemptSocialUser attemptSocialUser = new AttemptSocialUser();
    attemptSocialUser.setUsername("daumUser01");
    attemptSocialUser.setProviderId(Constants.ACCOUNT_TYPE.FACEBOOK);
    attemptSocialUser.setProviderUserId("abc123");
    attemptSocialUser.setExternalSmallPictureUrl("https://img1.daumcdn.net/thumb/R55x55/?fname=http%3A%2F%2Ftwg.tset.daumcdn.net%2Fprofile%2F6enovyMT1pI0&t=1507478752861");
    attemptSocialUser.setExternalLargePictureUrl("https://img1.daumcdn.net/thumb/R158x158/?fname=http%3A%2F%2Ftwg.tset.daumcdn.net%2Fprofile%2F6enovyMT1pI0&t=1507478752861");

    MockHttpSession mockHttpSession = new MockHttpSession();
    mockHttpSession.setAttribute(Constants.PROVIDER_SIGNIN_ATTEMPT_SESSION_ATTRIBUTE, attemptSocialUser);

    SocialUserForm form = new SocialUserForm();
    form.setEmail("[email protected]");
    form.setUsername("SocialUser");
    form.setAbout("안녕하세요.");
    form.setFootballClub(footballClub.getId());
    form.setUserPictureId(userPicture.getId());
    form.setExternalLargePictureUrl("https://img1.daumcdn.net/thumb/R158x158/?fname=http%3A%2F%2Ftwg.tset.daumcdn.net%2Fprofile%2FSjuNejHmr8o0&t=1488000722876");

    User expectUser = new User();
    expectUser.setId("597df86caaf4fc0545d4f3e9");
    expectUser.setEmail(form.getEmail());
    expectUser.setUsername(form.getUsername());
    expectUser.setPassword("841db2bc28e4730906bd82d79e69c80633747570d96ffade7dd77f58270f31a222e129e005cb70d2");
    expectUser.setProviderId(attemptSocialUser.getProviderId());
    expectUser.setProviderUserId(attemptSocialUser.getProviderUserId());
    expectUser.setAbout(form.getAbout());
    expectUser.setRoles(Arrays.asList(JakdukAuthority.ROLE_USER_02.getCode()));
    expectUser.setSupportFC(footballClub);
    expectUser.setLastLogged(LocalDateTime.now());

    when(userService.createSocialUser(anyString(), anyString(), any(Constants.ACCOUNT_TYPE.class), anyString(),
            anyString(), anyString(), anyString(), anyString()))
            .thenReturn(expectUser);

    ConstraintDescriptions userConstraints = new ConstraintDescriptions(SocialUserForm.class, new ValidatorConstraintResolver(),
            new ResourceBundleConstraintDescriptionResolver(ResourceBundle.getBundle("ValidationMessages")));

    mvc.perform(
            post("/api/user/social")
                    .session(mockHttpSession)
                    .contentType(MediaType.APPLICATION_JSON)
                    .with(csrf())
                    .content(ObjectMapperUtils.writeValueAsString(form)))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
            .andExpect(content().json(ObjectMapperUtils.writeValueAsString(EmptyJsonResponse.newInstance())))
            .andDo(
                    document("create-sns-user",
                            requestFields(
                                    fieldWithPath("email").type(JsonFieldType.STRING).description("이메일 주소. " +
                                            userConstraints.descriptionsForProperty("email")),
                                    fieldWithPath("username").type(JsonFieldType.STRING).description("별명. " +
                                            userConstraints.descriptionsForProperty("username")),
                                    fieldWithPath("footballClub").type(JsonFieldType.STRING).description("(optional) 축구단 ID"),
                                    fieldWithPath("about").type(JsonFieldType.STRING).description("(optional) 자기 소개"),
                                    fieldWithPath("userPictureId").type(JsonFieldType.STRING).description("(optional) 프로필 사진 ID"),
                                    fieldWithPath("externalLargePictureUrl").type(JsonFieldType.STRING)
                                            .description("(optional) SNS계정에서 제공하는 회원 큰 사진 URL. userPictureId가 null 이어야 한다.")
                            ),
                            responseHeaders(
                                    headerWithName("Set-Cookie").description("인증 쿠키. value는 JSESSIONID=키값").optional()
                            )
                    ));
}