热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.sessionAttr()方法的使用及代码示例

本文整理了Java中org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.sessio

本文整理了Java中org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder.sessionAttr()方法的一些代码示例,展示了MockHttpServletRequestBuilder.sessionAttr()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。MockHttpServletRequestBuilder.sessionAttr()方法的具体详情如下:
包路径:org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder
类名称:MockHttpServletRequestBuilder
方法名:sessionAttr

MockHttpServletRequestBuilder.sessionAttr介绍

[英]Set a session attribute.
[中]设置会话属性。

代码示例

代码示例来源: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 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 authorities = (List) 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"));
}

推荐阅读
  • 本文详细探讨了在微服务架构中,使用Feign进行远程调用时出现的请求头丢失问题,并提供了具体的解决方案。重点讨论了单线程和异步调用两种场景下的处理方法。 ... [详细]
  • 深入解析SpringMVC核心组件:DispatcherServlet的工作原理
    本文详细探讨了SpringMVC的核心组件——DispatcherServlet的运作机制,旨在帮助有一定Java和Spring基础的开发人员理解HTTP请求是如何被映射到Controller并执行的。文章将解答以下问题:1. HTTP请求如何映射到Controller;2. Controller是如何被执行的。 ... [详细]
  • Java项目分层架构设计与实践
    本文探讨了Java项目中应用分层的最佳实践,不仅介绍了常见的三层架构(Controller、Service、DAO),还深入分析了各层的职责划分及优化建议。通过合理的分层设计,可以提高代码的可维护性、扩展性和团队协作效率。 ... [详细]
  • 我有一个SpringRestController,它处理API调用的版本1。继承在SpringRestControllerpackagerest.v1;RestCon ... [详细]
  • Redux入门指南
    本文介绍Redux的基本概念和工作原理,帮助初学者理解如何使用Redux管理应用程序的状态。Redux是一个用于JavaScript应用的状态管理库,特别适用于React项目。 ... [详细]
  • 深入解析ESFramework中的AgileTcp组件
    本文详细介绍了ESFramework框架中AgileTcp组件的设计与实现。AgileTcp是ESFramework提供的ITcp接口的高效实现,旨在优化TCP通信的性能和结构清晰度。 ... [详细]
  • SpringMVC RestTemplate的几种请求调用(转)
    SpringMVCRestTemplate的几种请求调用(转),Go语言社区,Golang程序员人脉社 ... [详细]
  • 在寻找轻量级Ruby Web框架的过程中,您可能会遇到Sinatra和Ramaze。两者都以简洁、轻便著称,但它们之间存在一些关键区别。本文将探讨这些差异,并提供详细的分析,帮助您做出最佳选择。 ... [详细]
  • 当unique验证运到图片上传时
    2019独角兽企业重金招聘Python工程师标准model:public$imageFile;publicfunctionrules(){return[[[na ... [详细]
  • 深入浅出TensorFlow数据读写机制
    本文详细介绍TensorFlow中的数据读写操作,包括TFRecord文件的创建与读取,以及数据集(dataset)的相关概念和使用方法。 ... [详细]
  • 本文详细介绍了JSP(Java Server Pages)的九大内置对象及其功能,探讨了JSP与Servlet之间的关系及差异,并提供了实际编码示例。此外,还讨论了网页开发中常见的编码转换问题以及JSP的两种页面跳转方式。 ... [详细]
  • 本文探讨了为何相同的HTTP请求在两台不同操作系统(Windows与Ubuntu)的机器上会分别返回200 OK和429 Too Many Requests的状态码。我们将分析代码、环境差异及可能的影响因素。 ... [详细]
  • yikesnews第11期:微软Office两个0day和一个提权0day
    点击阅读原文可点击链接根据法国大选被黑客干扰,发送了带漏洞的文档Trumps_Attack_on_Syria_English.docx而此漏洞与ESET&FireEy ... [详细]
  • 本文介绍如何配置SecureCRT以正确显示Linux终端的颜色,并解决中文显示问题。通过简单的步骤设置,可以显著提升使用体验。 ... [详细]
  • MySQL锁机制详解
    本文深入探讨了MySQL中的锁机制,包括表级锁、行级锁以及元数据锁,通过实例详细解释了各种锁的工作原理及其应用场景。同时,文章还介绍了如何通过锁来优化数据库性能,避免常见的并发问题。 ... [详细]
author-avatar
平凡洗护店
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有