congrats Icon
New! Announcing Tabnine Chat Beta
Learn More
Tabnine Logo
MockHttpServletRequestBuilder.sessionAttr
Code IndexAdd Tabnine to your IDE (free)

How to use
sessionAttr
method
in
org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder

Best Java code snippets using org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.sessionAttr (Showing top 20 results out of 315)

origin: spring-projects/spring-framework

@Test
public void sessionAttribute() {
  this.builder.sessionAttr("foo", "bar");
  MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
  assertEquals("bar", request.getSession().getAttribute("foo"));
}
origin: spring-projects/spring-framework

@Test
public void mergeSession() throws Exception {
  String attrName = "PARENT";
  String attrValue = "VALUE";
  MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController())
      .defaultRequest(get("/").sessionAttr(attrName, attrValue))
      .build();
  assertThat(mockMvc.perform(requestBuilder).andReturn().getRequest().getSession().getAttribute(attrName), equalTo(attrValue));
}
origin: spring-projects/spring-framework

@Test
public void session() {
  MockHttpSession session = new MockHttpSession(this.servletContext);
  session.setAttribute("foo", "bar");
  this.builder.session(session);
  this.builder.sessionAttr("baz", "qux");
  MockHttpServletRequest request = this.builder.buildRequest(this.servletContext);
  assertEquals(session, request.getSession());
  assertEquals("bar", request.getSession().getAttribute("foo"));
  assertEquals("qux", request.getSession().getAttribute("baz"));
}
origin: spring-projects/spring-security

@Test
public void requestWhenConnectMessageAndUsingSockJsThenUsesCsrfTokenHandshakeInterceptor() throws Exception {
  this.spring.configLocations(xml("SyncSockJsConfig")).autowire();
  WebApplicationContext context = (WebApplicationContext) this.spring.getContext();
  MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build();
  String csrfAttributeName = CsrfToken.class.getName();
  String customAttributeName = this.getClass().getName();
  MvcResult result = mvc.perform(get("/app/289/tpyx6mde/websocket")
              .requestAttr(csrfAttributeName, this.token)
              .sessionAttr(customAttributeName, "attributeValue"))
            .andReturn();
  CsrfToken handshakeToken = (CsrfToken) this.testHandshakeHandler.attributes.get(csrfAttributeName);
  String handshakeValue = (String) this.testHandshakeHandler.attributes.get(customAttributeName);
  String sessionValue = (String) result.getRequest().getSession().getAttribute(customAttributeName);
  assertThat(handshakeToken).isEqualTo(this.token)
      .withFailMessage("CsrfToken is populated");
  assertThat(handshakeValue).isEqualTo(sessionValue)
      .withFailMessage("Explicitly listed session variables are not overridden");
}
origin: spring-projects/spring-security

@Test
public void requestWhenConnectMessageThenUsesCsrfTokenHandshakeInterceptor() throws Exception {
  this.spring.configLocations(xml("SyncConfig")).autowire();
  WebApplicationContext context = (WebApplicationContext) this.spring.getContext();
  MockMvc mvc = MockMvcBuilders.webAppContextSetup(context).build();
  String csrfAttributeName = CsrfToken.class.getName();
  String customAttributeName = this.getClass().getName();
  MvcResult result = mvc.perform(get("/app")
              .requestAttr(csrfAttributeName, this.token)
              .sessionAttr(customAttributeName, "attributeValue"))
            .andReturn();
  CsrfToken handshakeToken = (CsrfToken) this.testHandshakeHandler.attributes.get(csrfAttributeName);
  String handshakeValue = (String) this.testHandshakeHandler.attributes.get(customAttributeName);
  String sessionValue = (String) result.getRequest().getSession().getAttribute(customAttributeName);
  assertThat(handshakeToken).isEqualTo(this.token)
      .withFailMessage("CsrfToken is populated");
  assertThat(handshakeValue).isEqualTo(sessionValue)
      .withFailMessage("Explicitly listed session variables are not overridden");
}
origin: spring-projects/spring-framework

@Test
public void sessionAttributesAreClearedBetweenInvocations() throws Exception {
  this.mvc.perform(get("/"))
    .andExpect(content().string(HELLO))
    .andExpect(request().sessionAttribute(FOO, nullValue()));
  this.mvc.perform(get("/").sessionAttr(FOO, BAR))
    .andExpect(content().string(HELLO))
    .andExpect(request().sessionAttribute(FOO, BAR));
  this.mvc.perform(get("/"))
    .andExpect(content().string(HELLO))
    .andExpect(request().sessionAttribute(FOO, nullValue()));
}
origin: apache/servicemix-bundles

/**
 * Set session attributes.
 * @param sessionAttributes the session attributes
 */
public MockHttpServletRequestBuilder sessionAttrs(Map<String, Object> sessionAttributes) {
  Assert.notEmpty(sessionAttributes, "'sessionAttributes' must not be empty");
  for (String name : sessionAttributes.keySet()) {
    sessionAttr(name, sessionAttributes.get(name));
  }
  return this;
}
origin: entando/entando-core

@Test
public void shouldValidateDeleteOnlinePage() throws ApsSystemException, Exception {
  UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
  String accessToken = mockOAuthInterceptor(user);
  when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
  when(this.controller.getPageValidator().getPageManager().getOnlinePage(any(String.class))).thenReturn(new Page());
  ResultActions result = mockMvc.perform(
      delete("/pages/{pageCode}", "online_page")
      .sessionAttr("user", user)
      .header("Authorization", "Bearer " + accessToken));
  result.andExpect(status().isBadRequest());
  String response = result.andReturn().getResponse().getContentAsString();
  result.andExpect(jsonPath("$.errors", hasSize(1)));
  result.andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_ONLINE_PAGE)));
}
origin: entando/entando-core

@Test
public void shouldAddUserAuthorities() throws Exception {
  UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
  String accessToken = mockOAuthInterceptor(user);
  String mockJson = "[{\"group\":\"group1\", \"role\":\"role1\"},{\"group\":\"group2\", \"role\":\"role2\"}]";
  List<UserAuthorityDto> authorities = (List<UserAuthorityDto>) this.createMetadata(mockJson, List.class);
  when(this.controller.getUserValidator().getGroupManager().getGroup(any(String.class))).thenReturn(mockedGroup());
  when(this.controller.getUserValidator().getRoleManager().getRole(any(String.class))).thenReturn(mockedRole());
  when(this.controller.getUserService().addUserAuthorities(any(String.class), any(UserAuthoritiesRequest.class))).thenReturn(authorities);
  ResultActions result = mockMvc.perform(
      put("/users/{target}/authorities", "mockuser")
          .sessionAttr("user", user)
          .content(mockJson)
          .contentType(MediaType.APPLICATION_JSON)
          .header("Authorization", "Bearer " + accessToken));
  result.andExpect(status().isOk());
}
origin: entando/entando-core

@Test
public void shouldValidateDeletePageWithChildren() throws ApsSystemException, Exception {
  UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
  String accessToken = mockOAuthInterceptor(user);
  Page page = new Page();
  page.setCode("page_with_children");
  page.addChildCode("child");
  when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
  when(this.controller.getPageValidator().getPageManager().getDraftPage(any(String.class))).thenReturn(page);
  ResultActions result = mockMvc.perform(
      delete("/pages/{pageCode}", "page_with_children")
      .sessionAttr("user", user)
      .header("Authorization", "Bearer " + accessToken));
  result.andExpect(status().isBadRequest());
  String response = result.andReturn().getResponse().getContentAsString();
  result.andExpect(jsonPath("$.errors", hasSize(1)));
  result.andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_PAGE_HAS_CHILDREN)));
}
origin: entando/entando-core

@Test
public void shouldValidateMovePageInvalidPosition() throws ApsSystemException, Exception {
  UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
  String accessToken = mockOAuthInterceptor(user);
  PagePositionRequest request = new PagePositionRequest();
  request.setCode("page_to_move");
  request.setParentCode("new_parent_page");
  request.setPosition(0);
  
  when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
  when(this.controller.getPageValidator().getPageManager().getDraftPage("new_parent_page")).thenReturn(new Page());
  
  ResultActions result = mockMvc.perform(
      put("/pages/{pageCode}/position", "page_to_move")
          .sessionAttr("user", user)
          .content(convertObjectToJsonBytes(request))
          .contentType(MediaType.APPLICATION_JSON)
          .header("Authorization", "Bearer " + accessToken));
  result.andExpect(status().isBadRequest())
      .andExpect(jsonPath("$.errors", hasSize(1)))
      .andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_CHANGE_POSITION_INVALID_REQUEST)));
}
origin: entando/entando-core

@Test
public void shouldValidateMovePageMissingParent() throws ApsSystemException, Exception {
  UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
  String accessToken = mockOAuthInterceptor(user);
  PagePositionRequest request = new PagePositionRequest();
  request.setCode("page_to_move");
  request.setParentCode("new_parent_page");
  request.setPosition(0);
  when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
  ResultActions result = mockMvc.perform(
      put("/pages/{pageCode}/position", "page_to_move")
          .sessionAttr("user", user)
          .content(convertObjectToJsonBytes(request))
          .contentType(MediaType.APPLICATION_JSON)
          .header("Authorization", "Bearer " + accessToken));
  result.andExpect(status().isBadRequest())
      .andExpect(jsonPath("$.errors", hasSize(1)))
      .andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_CHANGE_POSITION_INVALID_REQUEST)));
}
origin: entando/entando-core

@Test
public void shouldGetUsersList() throws Exception {
  UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
  String accessToken = mockOAuthInterceptor(user);
  when(this.userService.getUsers(any(RestListRequest.class), any(String.class))).thenReturn(mockUsers());
  ResultActions result = mockMvc.perform(
      get("/users")
          .param("withProfile", "0")
          .param("sort", "username")
          .param("filter[0].attribute", "username")
          .param("filter[0].operator", "like")
          .param("filter[0].value", "user")
          .sessionAttr("user", user)
          .header("Authorization", "Bearer " + accessToken));
  System.out.println("result: " + result.andReturn().getResponse().getContentAsString());
  result.andExpect(status().isOk());
}
origin: entando/entando-core

@Test
public void shouldValidateMovePageNameMismatch() throws ApsSystemException, Exception {
  UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
  String accessToken = mockOAuthInterceptor(user);
  PagePositionRequest request = new PagePositionRequest();
  request.setCode("WRONG");
  request.setParentCode("new_parent_page");
  request.setPosition(1);
  
  when(authorizationService.isAuth(any(UserDetails.class), any(String.class))).thenReturn(true);
  when(this.controller.getPageValidator().getPageManager().getDraftPage("new_parent_page")).thenReturn(new Page());
  
  ResultActions result = mockMvc.perform(
      put("/pages/{pageCode}/position", "page_to_move")
          .sessionAttr("user", user)
          .content(convertObjectToJsonBytes(request))
          .contentType(MediaType.APPLICATION_JSON)
          .header("Authorization", "Bearer " + accessToken));
  result.andExpect(status().isBadRequest())
      .andExpect(jsonPath("$.errors", hasSize(1)))
      .andExpect(jsonPath("$.errors[0].code", is(PageController.ERRCODE_URINAME_MISMATCH)));
}
origin: entando/entando-core

@Test
public void shouldAdd4CharsUsernamePost() throws Exception {
  UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
  String accessToken = mockOAuthInterceptor(user);
  String mockJson = "{\"username\": \"user\",\n"
      + "    \"password\": \"new_password\",\n"
      + "    \"status\": \"active\"\n"
      + "}";
  when(this.userService.addUser(any(UserRequest.class))).thenReturn(this.mockUser());
  ResultActions result = mockMvc.perform(
      post("/users")
          .sessionAttr("user", user)
          .content(mockJson)
          .contentType(MediaType.APPLICATION_JSON)
          .header("Authorization", "Bearer " + accessToken));
  result.andExpect(status().isOk());
  String response = result.andReturn().getResponse().getContentAsString();
  System.out.println(response);
  result.andExpect(jsonPath("$.errors", hasSize(0)));
}
origin: entando/entando-core

@Test
public void shouldValidateUserPut() throws Exception {
  UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24").grantedToRoleAdmin().build();
  String accessToken = mockOAuthInterceptor(user);
  String mockJson = "{\n"
      + "    \"username\": \"username_test\",\n"
      + "    \"status\": \"inactive\",\n"
      + "    \"password\": \"invalid spaces\"\n"
      + " }";
  when(this.userManager.getUser(any(String.class))).thenReturn(this.mockUserDetails("username_test"));
  ResultActions result = mockMvc.perform(
      put("/users/{target}", "mismach")
          .sessionAttr("user", user)
          .content(mockJson)
          .contentType(MediaType.APPLICATION_JSON)
          .header("Authorization", "Bearer " + accessToken));
  String response = result.andReturn().getResponse().getContentAsString();
  System.out.println("users: " + response);
  result.andExpect(status().isConflict());
}
origin: DanielMichalski/spring-web-rss-channels

  @Test
  public void testSendEmail() throws Exception {
    String from = "test@mail.com";
    String message = "Mail message";
    String name = "Name";

    ContactForm contactForm = new ContactForm();
    contactForm.setMail(from);
    contactForm.setMessage(message);
    contactForm.setName(name);

    Mockito.when(mailService.sendEMail(from, mailTo, "Message from " + name, message)).thenReturn(true);

    mockMvc.perform(post("/contact").accept(MediaType.APPLICATION_XHTML_XML)
        .sessionAttr("contactForm", contactForm))
        .andExpect(redirectedUrl("contact?sent=false"))
        .andExpect(model().attributeExists("contactForm"));
  }
}
origin: mstine/RefactoringTheMonolith

  @Test
  public void shouldLoadOrderWhenContinuing() throws Exception {
    this.mockMvc.perform(get("/continueOrder")
        .sessionAttr("currentOrder", 10000L))
        .andExpect(status().isOk())
        .andExpect(model().attributeExists("currentOrder"))
        .andExpect(view().name("order"));
  }
}
origin: entando/entando-core

@Test
public void shouldBeUnauthorized() throws Exception {
  UserDetails user = new OAuth2TestUtils.UserBuilder("jack_bauer", "0x24")
      .withGroup(Group.FREE_GROUP_NAME)
      .build();
  String accessToken = mockOAuthInterceptor(user);
  ResultActions result = mockMvc.perform(
      get("/pages/{parentCode}", "mock_page")
      .sessionAttr("user", user)
      .header("Authorization", "Bearer " + accessToken)
  );
  String response = result.andReturn().getResponse().getContentAsString();
  result.andExpect(status().isForbidden());
}
origin: mstine/RefactoringTheMonolith

@Test
public void startsANewPizza() throws Exception {
  this.mockMvc.perform(get("/addPizza")
      .sessionAttr("currentOrder", 10000L))
      .andExpect(status().isOk())
      .andExpect(model().attributeExists("basePizzaMenuOptions"))
      .andExpect(model().attributeExists("currentPizza"))
      .andExpect(view().name("chooseBaseOptions"));
}
org.springframework.test.web.servlet.requestMockHttpServletRequestBuildersessionAttr

Javadoc

Set a session attribute.

Popular methods of MockHttpServletRequestBuilder

  • contentType
    Set the 'Content-Type' header of the request.
  • content
    Set the request body.
  • param
    Add a request parameter to the MockHttpServletRequest.If called more than once, new values get added
  • accept
    Set the 'Accept' header to the given media type(s).
  • header
    Add a header to the request. Values are always added.
  • with
    An extension point for further initialization of MockHttpServletRequestin ways not built directly in
  • requestAttr
    Set a request attribute.
  • buildRequest
    Build a MockHttpServletRequest.
  • contextPath
    Specify the portion of the requestURI that represents the context path. The context path, if specifi
  • principal
    Set the principal of the request.
  • flashAttr
    Set an "input" flash attribute.
  • headers
    Add all headers to the request. Values are always added.
  • flashAttr,
  • headers,
  • session,
  • cookie,
  • params,
  • servletPath,
  • <init>,
  • characterEncoding,
  • locale

Popular in Java

  • Parsing JSON documents to java classes using gson
  • setScale (BigDecimal)
  • getSystemService (Context)
  • compareTo (BigDecimal)
  • InputStream (java.io)
    A readable source of bytes.Most clients will use input streams that read data from the file system (
  • Path (java.nio.file)
  • Enumeration (java.util)
    A legacy iteration interface.New code should use Iterator instead. Iterator replaces the enumeration
  • List (java.util)
    An ordered collection (also known as a sequence). The user of this interface has precise control ove
  • CountDownLatch (java.util.concurrent)
    A synchronization aid that allows one or more threads to wait until a set of operations being perfor
  • JarFile (java.util.jar)
    JarFile is used to read jar entries and their associated data from jar files.
  • Top Sublime Text plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now