List of usage examples for org.springframework.mock.web MockHttpServletRequest setSession
public void setSession(HttpSession session)
From source file:org.jasig.cas.support.oauth.web.OAuth20AuthorizeCallbackControllerTests.java
@Test public void verifyOKWhenBypassApprovalFalse() throws Exception { final Principal principal = mock(Principal.class); when(principal.getId()).thenReturn(PRINCIPAL_ID); final Authentication authentication = mock(Authentication.class); when(authentication.getPrincipal()).thenReturn(principal); final TicketGrantingTicket ticketGrantingTicket = mock(TicketGrantingTicket.class); when(ticketGrantingTicket.isExpired()).thenReturn(false); when(ticketGrantingTicket.getAuthentication()).thenReturn(authentication); final TicketRegistry ticketRegistry = mock(TicketRegistry.class); when(ticketRegistry.getTicket(TICKET_GRANTING_TICKET_ID)).thenReturn(ticketGrantingTicket); final Map<String, Scope> scopeMap = new HashMap<>(); scopeMap.put("scope1", new Scope("scope1", "description2")); scopeMap.put("scope2", new Scope("scope2", "description2")); final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class); when(centralOAuthService.getScopes(anySetOf(String.class))).thenReturn(scopeMap); final MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", CONTEXT + OAuthConstants.CALLBACK_AUTHORIZE_URL); final MockHttpSession mockSession = new MockHttpSession(); mockSession.putValue(OAuthConstants.OAUTH20_LOGIN_TICKET_ID, TICKET_GRANTING_TICKET_ID); mockSession.putValue(OAuthConstants.OAUTH20_SCOPE, SCOPE); mockSession.putValue(OAuthConstants.OAUTH20_SERVICE_NAME, SERVICE_NAME); mockSession.putValue(OAuthConstants.OAUTH20_TOKEN_TYPE, TokenType.OFFLINE); mockSession.putValue(OAuthConstants.OAUTH20_APPROVAL_PROMPT, OAuthConstants.APPROVAL_PROMPT_FORCE); mockSession.putValue(OAuthConstants.BYPASS_APPROVAL_PROMPT, false); mockRequest.setSession(mockSession); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.setTicketRegistry(ticketRegistry); oauth20WrapperController.setCentralOAuthService(centralOAuthService); 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(scopeMap.hashCode(), map.get("scopeMap").hashCode()); assertEquals(scopeMap.keySet(), mockSession.getAttribute(OAuthConstants.OAUTH20_SCOPE_SET)); }
From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java
public void testFindOperationInPHPResponseFormat() throws Exception { // Create dummy user object final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan"); // Create fixture data final List<Integer> createdItemIdList = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 5); // Set dummy user with the deletable list of items createdItemIdList.add(dummyUserId);/*from w ww.ja v a 2 s .c o m*/ try { // Execute successful login request final Subject subject = getSubjectFromASuccessfulRequest(); // Create a new servlet request final MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/service/find/q.php"); final Query query = new Query(); query.and("email", "hasan@somewherein.net"); LOG.debug("New query - " + query.buildQuery()); request.addParameter("q", query.buildQuery().toString()); // set pagination request.addParameter(WebConstants.PARAM_OFFSET, String.valueOf(0)); request.addParameter(WebConstants.PARAM_MAX, String.valueOf(2)); request.setMethod(METHOD_GET); // set session id final MockHttpSession session = new MockHttpSession(); session.setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject); request.setSession(session); final MockHttpServletResponse response = new MockHttpServletResponse(); // Execute controller final ModelAndView modelAndView = mRestfulController.handleRequest(request, response); // Verify response assertNull("Model or view is returned", modelAndView); final String responseContent = response.getContentAsString(); assertTrue("Response content is empty.", responseContent.indexOf("true") != -1); assertEquals("Resonse status is not 200", RESTfulControllerImpl.STATUS_OK_200, response.getStatus()); LOG.debug("Response content - " + responseContent); } finally { // clean up all fixed items. TestCaseRepositoryHelper.fixRemoveAllItems(mRepositoryService); } }
From source file:com.ideabase.repository.test.webservice.RESTfulControllerTest.java
/** * Test search request for findout a list of items. * @throws Exception//from w w w .j a v a 2 s. c om */ public void testFindOperation() throws Exception { // Create dummy user object final Integer dummyUserId = TestCaseRepositoryHelper.fixCreateUser(mUserService, "hasan", "hasankhan"); // Create fixture data final List<Integer> createdItemIdList = TestCaseRepositoryHelper.fixCreateItems(mRepositoryService, 5); // Set dummy user with the deletable list of items createdItemIdList.add(dummyUserId); try { // Execute successful login request final Subject subject = getSubjectFromASuccessfulRequest(); // Create a new servlet request final MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/service/find/q.xml"); final Query query = new Query(); query.and("email", "hasan@somewherein.net"); LOG.debug("New query - " + query.buildQuery()); request.addParameter("q", query.buildQuery().toString()); // set pagination request.addParameter(WebConstants.PARAM_OFFSET, String.valueOf(0)); request.addParameter(WebConstants.PARAM_MAX, String.valueOf(2)); request.setMethod(METHOD_GET); // set session id final MockHttpSession session = new MockHttpSession(); session.setAttribute(WebConstants.SESSION_ATTR_USER_SUBJECT, subject); request.setSession(session); final MockHttpServletResponse response = new MockHttpServletResponse(); // Execute controller final ModelAndView modelAndView = mRestfulController.handleRequest(request, response); // Verify response assertNull("Model or view is returned", modelAndView); final String responseContent = response.getContentAsString(); assertTrue("Response content is empty.", responseContent.indexOf("true") != -1); assertEquals("Resonse status is not 200", RESTfulControllerImpl.STATUS_OK_200, response.getStatus()); LOG.debug("Response content - " + responseContent); } finally { // clean up all fixed items. TestCaseRepositoryHelper.fixRemoveAllItems(mRepositoryService); } }
From source file:org.openmrs.web.controller.ConceptFormControllerTest.java
/** * Test to make sure a new patient form can save a person relationship * /* www . j a va2 s .com*/ * @throws Exception */ @Test public void shouldNotDeleteConceptsWhenConceptsAreLocked() throws Exception { // this dataset should lock the concepts executeDataSet("org/openmrs/web/include/ConceptFormControllerTest.xml"); ConceptService cs = Context.getConceptService(); // set up the controller ConceptFormController controller = (ConceptFormController) applicationContext.getBean("conceptForm"); controller.setApplicationContext(applicationContext); controller.setSuccessView("index.htm"); controller.setFormView("concept.form"); // set up the request and do an initial "get" as if the user loaded the // page for the first time MockHttpServletRequest request = new MockHttpServletRequest("GET", "/dictionary/concept.form?conceptId=3"); request.setSession(new MockHttpSession(null)); HttpServletResponse response = new MockHttpServletResponse(); controller.handleRequest(request, response); // set this to be a page submission request.setMethod("POST"); request.addParameter("action", "Delete Concept"); // so that the form is processed // send the parameters to the controller ModelAndView mav = controller.handleRequest(request, response); Assert.assertNotSame("The purge attempt should have failed!", "index.htm", mav.getViewName()); Assert.assertNotNull(cs.getConcept(3)); }
From source file:org.fao.geonet.kernel.SpringLocalServiceInvoker.java
/** * prepareMockRequestFromUri will search for spring services that match * the request and execute them. Typically used for the local:// xlink * speed up. Accepts urls prefixed with local://<nodename> eg. * local://srv/api/records/.. /*from w ww . j a v a 2 s .c om*/ * but also urls prefixed with the nodename only eg. '/srv/api/records/..' */ private MockHttpServletRequest prepareMockRequestFromUri(String uri) { String requestURI = uri.replace("local:/", "").replace("/" + nodeId, "").split("\\?")[0]; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestURI); request.setSession(new MockHttpSession()); String[] splits = uri.split("\\?"); if (splits.length > 1) { String params = splits[1]; for (String param : params.split("&")) { String[] parts = param.split("="); String name = parts[0]; request.addParameter(name, parts.length == 2 ? parts[1] : ""); } } return request; }
From source file:org.finra.dm.ui.RequestLoggingFilterTest.java
private MockHttpServletRequest createServletRequest() { MockHttpServletRequest request = new MockHttpServletRequest(null, "/test"); request.setQueryString("param=value"); request.setMethod("POST"); MockHttpSession session = new MockHttpSession(); request.setContent(PAYLOAD_CONTENT.getBytes()); request.setSession(session); request.setRemoteUser("Test Remote User"); return request; }
From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_8.SessionController1_8Test.java
@Before public void before() { controller = new SessionController1_8(); MockHttpServletRequest hsr = new MockHttpServletRequest(); hsr.setSession(new MockHttpSession(new MockServletContext(), SESSION_ID)); request = new ServletWebRequest(hsr); Context.getAdministrationService().saveGlobalProperty( new GlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOCALE_ALLOWED_LIST, "en_GB, sp, fr")); }
From source file:org.pentaho.test.platform.web.ui.servlet.MondrianCatalogPublisherTests.java
protected MockHttpServletResponse simulateRequest(Map<String, String> map) throws Exception { // prepare request MockHttpServletRequest request = new MockHttpServletRequest(); request.setContentType("multipart/form-data; boundary=---1234"); //$NON-NLS-1$ request.setCharacterEncoding("UTF-8"); //$NON-NLS-1$ String mondrianSchemaFile = map.get("mondrianSchemaFile"); if (logger.isDebugEnabled()) { logger.debug("uploading mondrian schema file named \"" + mondrianSchemaFile + "\""); }/* w w w .j a v a2 s . c o m*/ String content = MessageFormat.format(DEFAULT_CONTENT_TEMPLATE, mondrianSchemaFile, DEFAULT_FILE_CONTENT); if (logger.isDebugEnabled()) { logger.debug("content=" + content); //$NON-NLS-1$ } request.setContent(content.getBytes("UTF-8")); //$NON-NLS-1$ request.addParameter("publishPath", map.get("publishPath")); //$NON-NLS-1$ //$NON-NLS-2$ request.addParameter("publishKey", map.get("publishKey")); //$NON-NLS-1$ //$NON-NLS-2$ request.addParameter("overwrite", map.get("overwrite")); //$NON-NLS-1$ //$NON-NLS-2$ request.addParameter("jndiName", map.get("jndiName")); //$NON-NLS-1$ //$NON-NLS-2$ MockHttpSession httpSession = new MockHttpSession(); httpSession.setAttribute("pentaho-session", pentahoSession); //$NON-NLS-1$ request.setSession(httpSession); // prepare response MockHttpServletResponse response = new MockHttpServletResponse(); // prepare mondrian catalog service MondrianCatalogHelper catService = new MondrianCatalogHelper(); catService.setDataSourcesConfig("file:" + destFile.getAbsolutePath()); //$NON-NLS-1$ // catService.afterPropertiesSet(); // prepare mondrian catalog publisher MondrianCatalogPublisher pub = new MondrianCatalogPublisher(); pub.setMondrianCatalogService(catService); pub.setFullyQualifiedServerURL("http://localhost:8080/pentaho"); //$NON-NLS-1$ // pub.afterPropertiesSet(); // process request // TODO We need to figure out how to test this . doGet is a protected method now //pub.doGet(request, response); // assertions response.getWriter().flush(); String responseContent = response.getContentAsString(); if (logger.isDebugEnabled()) { logger.debug("response=" + responseContent); //$NON-NLS-1$ } return response; }
From source file:org.springframework.security.web.authentication.www.BasicAuthenticationFilterTests.java
@Test public void testInvalidBasicAuthorizationTokenIsIgnored() throws Exception { String token = "NOT_A_VALID_TOKEN_AS_MISSING_COLON"; MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes()))); request.setServletPath("/some_file.html"); request.setSession(new MockHttpSession()); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); }
From source file:org.springframework.security.web.authentication.www.BasicAuthenticationFilterTests.java
@Test public void invalidBase64IsIgnored() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); request.addHeader("Authorization", "Basic NOT_VALID_BASE64"); request.setServletPath("/some_file.html"); request.setSession(new MockHttpSession()); final MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain chain = mock(FilterChain.class); filter.doFilter(request, response, chain); // The filter chain shouldn't proceed verify(chain, never()).doFilter(any(ServletRequest.class), any(ServletResponse.class)); assertThat(SecurityContextHolder.getContext().getAuthentication()).isNull(); assertThat(response.getStatus()).isEqualTo(401); }