Java Code Examples for org.springframework.mock.web.MockHttpServletRequest#setAttribute()
The following examples show how to use
org.springframework.mock.web.MockHttpServletRequest#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: SecurityTokenErrorCheckTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void shouldReturnCauseMessageWhenTokenExpireException() { MockHttpServletRequest request = new MockHttpServletRequest(); TokenExpireException tokenExpireException = new TokenExpireException("TOKEN_EXPIRE"); AuthenticationException exception = new TokenExpireException(tokenExpireException.getMessage(), tokenExpireException); ZuulException exc = new ZuulException(exception, HttpStatus.GATEWAY_TIMEOUT.value(), String.valueOf(exception)); request.setAttribute(ErrorUtils.ATTR_ERROR_EXCEPTION, exc); ResponseEntity<ApiMessageView> actualResponse = securityTokenErrorCheck.checkError(request, exc); assertNotNull(actualResponse); assertEquals(HttpStatus.UNAUTHORIZED, actualResponse.getStatusCode()); List<ApiMessage> actualMessageList = actualResponse.getBody().getMessages(); assertThat(actualMessageList, hasItem(new ApiMessage<>("org.zowe.apiml.gateway.security.expiredToken", MessageType.ERROR, "ZWEAG103E", "Token is expired"))); }
Example 2
Source File: CustomRequestAttributesRequestContextHolderTests.java From spring-analysis-note with MIT License | 6 votes |
@Before public void setUp() { ServletContext servletContext = new MockServletContext(); MockHttpServletRequest mockRequest = new MockHttpServletRequest(servletContext); mockRequest.setAttribute(FROM_CUSTOM_MOCK, FROM_CUSTOM_MOCK); RequestContextHolder.setRequestAttributes(new ServletWebRequest(mockRequest, new MockHttpServletResponse())); this.wac.setServletContext(servletContext); new AnnotatedBeanDefinitionReader(this.wac).register(WebConfig.class); this.wac.refresh(); this.mockMvc = webAppContextSetup(this.wac) .defaultRequest(get("/").requestAttr(FROM_MVC_TEST_DEFAULT, FROM_MVC_TEST_DEFAULT)) .alwaysExpect(status().isOk()) .build(); }
Example 3
Source File: InspektrThrottledSubmissionByIpAddressAndUsernameHandlerInterceptorAdapterTests.java From cas4.0.x-server-wechat with Apache License 2.0 | 6 votes |
@Override protected MockHttpServletResponse loginUnsuccessfully(final String username, final String fromAddress) throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); request.setMethod("POST"); request.setParameter("username", username); request.setRemoteAddr(fromAddress); MockRequestContext context = new MockRequestContext(); context.setCurrentEvent(new Event("", "error")); request.setAttribute("flowRequestContext", context); ClientInfoHolder.setClientInfo(new ClientInfo(request)); getThrottle().preHandle(request, response, null); try { authenticationManager.authenticate(badCredentials(username)); } catch (final AuthenticationException e) { getThrottle().postHandle(request, response, null, null); return response; } fail("Expected AuthenticationException"); return null; }
Example 4
Source File: InternalServerErrorControllerTest.java From api-layer with Eclipse Public License 2.0 | 6 votes |
@Test public void testGenericError() { MessageService messageService = new YamlMessageService(); InternalServerErrorController errorController = new InternalServerErrorController(messageService); MockHttpServletRequest request = new MockHttpServletRequest(); request.setAttribute(ErrorUtils.ATTR_ERROR_EXCEPTION, new Exception("Hello")); request.setAttribute(ErrorUtils.ATTR_ERROR_STATUS_CODE, 523); request.setAttribute(RequestDispatcher.FORWARD_REQUEST_URI, "/uri"); ResponseEntity<ApiMessageView> response = errorController.error(request); assertEquals(523, response.getStatusCodeValue()); assertEquals("org.zowe.apiml.common.internalRequestError", response.getBody().getMessages().get(0).getMessageKey()); assertTrue(response.getBody().getMessages().get(0).getMessageContent().contains("Hello")); assertTrue(response.getBody().getMessages().get(0).getMessageContent().contains("/uri")); }
Example 5
Source File: AdditionalCertificateValidationsAspectShould.java From mutual-tls-ssl with Apache License 2.0 | 6 votes |
@Test public void validateCertificateForUnrecognizedCommonNameReturnsBadRequestHttpStatus() throws Throwable { var proceedingJoinPoint = mock(ProceedingJoinPoint.class); var additionalCertificateValidations = createAdditionalCertificateValidations(); X509Certificate x509Certificate = mock(X509Certificate.class); X509Certificate[] x509Certificates = new X509Certificate[]{x509Certificate}; X500Principal x500Principal = mock(X500Principal.class); MockHttpServletRequest request = new MockHttpServletRequest(); request.setAttribute("javax.servlet.request.X509Certificate", x509Certificates); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); when(x509Certificate.getSubjectX500Principal()).thenReturn(x500Principal); when(x500Principal.getName()).thenReturn("qwertyuiop"); Object response = victim.validate(proceedingJoinPoint, additionalCertificateValidations); verify(proceedingJoinPoint, times(0)).proceed(); assertThat(response).isInstanceOf(ResponseEntity.class); ResponseEntity responseEntity = (ResponseEntity) response; assertThat(responseEntity.getStatusCode().value()).isEqualTo(400); assertThat(responseEntity.getBody()).isEqualTo("This certificate is not a valid one"); }
Example 6
Source File: AdditionalCertificateValidationsAspectShould.java From mutual-tls-ssl with Apache License 2.0 | 6 votes |
@Test public void validateCertificateForAllowedCommonNameContinuesTheFlowWithProceedingJoinPoint() throws Throwable { var proceedingJoinPoint = mock(ProceedingJoinPoint.class); var additionalCertificateValidations = createAdditionalCertificateValidations(); X509Certificate x509Certificate = mock(X509Certificate.class); X509Certificate[] x509Certificates = new X509Certificate[]{x509Certificate}; X500Principal x500Principal = mock(X500Principal.class); MockHttpServletRequest request = new MockHttpServletRequest(); request.setAttribute("javax.servlet.request.X509Certificate", x509Certificates); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); when(x509Certificate.getSubjectX500Principal()).thenReturn(x500Principal); when(x500Principal.getName()).thenReturn("CN=black-hole,OU=Altindag,O=Altindag,C=NL"); victim.validate(proceedingJoinPoint, additionalCertificateValidations); verify(proceedingJoinPoint, times(1)).proceed(); }
Example 7
Source File: MolgenisUiUtilsTest.java From molgenis with GNU Lesser General Public License v3.0 | 6 votes |
@Test void getCurrentUri() { String uri = "/menu/test"; String queryString = "a=b&c=d"; MockHttpServletRequest request = new MockHttpServletRequest(); request.setAttribute("javax.servlet.forward.request_uri", uri); request.setQueryString(queryString); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); String currentUri = MolgenisUiUtils.getCurrentUri(); assertNotNull(currentUri); assertEquals(uri + "?" + queryString, currentUri); request.setQueryString(null); RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); currentUri = MolgenisUiUtils.getCurrentUri(); assertNotNull(currentUri); assertEquals(uri, currentUri); }
Example 8
Source File: ConfigControllerTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Before public void setUp() throws Exception { request = new MockHttpServletRequest(); request.setAttribute("repositoryID", repositoryId); response = new MockHttpServletResponse(); manager = mock(RepositoryManager.class); controller.setRepositoryManager(manager); }
Example 9
Source File: TimeoutErrorCheckTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void testZuulTimeoutErrorWithoutCause() { MockHttpServletRequest request = new MockHttpServletRequest(); ZuulException exc = new ZuulException("", HttpStatus.GATEWAY_TIMEOUT.value(), "TEST"); request.setAttribute(ErrorUtils.ATTR_ERROR_EXCEPTION, exc); ResponseEntity<ApiMessageView> response = errorController.error(request); assertCorrectMessage(response, TimeoutErrorCheck.DEFAULT_MESSAGE); }
Example 10
Source File: RestScriptsControllerTest.java From engine with GNU General Public License v3.0 | 5 votes |
private MockHttpServletRequest createRequest(String serviceUrl) { MockHttpServletRequest request = new MockHttpServletRequest("GET", "http://localhost:8080/api/1/services/" + serviceUrl); request.setParameter("test-param", "test"); request.addHeader("test-header", "test"); Cookie testCookie = new Cookie("test-cookie", "test"); request.setCookies(testCookie); request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, serviceUrl); return request; }
Example 11
Source File: ServletFilterRequestTest.java From vespa with Apache License 2.0 | 5 votes |
private ServletRequest newServletRequest() throws Exception { MockHttpServletRequest parent = new MockHttpServletRequest("GET", uri.toString()); parent.setProtocol(Version.HTTP_1_1.toString()); parent.setRemoteHost(host); parent.setRemotePort(port); parent.setParameter(paramName, paramValue); parent.setParameter(listParamName, listParamValue); parent.addHeader(headerName, headerValue); parent.setAttribute(attributeName, attributeValue); HttpConnection connection = Mockito.mock(HttpConnection.class); when(connection.getCreatedTimeStamp()).thenReturn(System.currentTimeMillis()); parent.setAttribute("org.eclipse.jetty.server.HttpConnection", connection); return new ServletRequest(parent, uri); }
Example 12
Source File: AbstractInMemoryThrottledSubmissionHandlerInterceptorAdapterTests.java From cas4.0.x-server-wechat with Apache License 2.0 | 5 votes |
@Override protected MockHttpServletResponse loginUnsuccessfully(final String username, final String fromAddress) throws Exception { final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); request.setMethod("POST"); request.setParameter("username", username); request.setRemoteAddr(fromAddress); MockRequestContext context = new MockRequestContext(); context.setCurrentEvent(new Event("", "error")); request.setAttribute("flowRequestContext", context); getThrottle().preHandle(request, response, null); getThrottle().postHandle(request, response, null, null); return response; }
Example 13
Source File: MockHttpUtil.java From attic-rave with Apache License 2.0 | 5 votes |
public static void setupRequestAsNonMobileUserAgent(MockHttpServletRequest mockHttpServletRequest) { mockHttpServletRequest.addHeader("User-Agent", "MSIE"); mockHttpServletRequest.setAttribute(DeviceUtils.CURRENT_DEVICE_ATTRIBUTE, new LiteDeviceResolver().resolveDevice(mockHttpServletRequest)); }
Example 14
Source File: TestStatementsController.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void shouldUseTimeoutParameterForUpdateQueries() throws Exception { // prepare StatementsController controller = new StatementsController(); final int maxExecution = 1; final MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod(HttpMethod.POST.name()); request.setContentType(Protocol.SPARQL_UPDATE_MIME_TYPE); request.addParameter(Protocol.TIMEOUT_PARAM_NAME, String.valueOf(maxExecution)); final String updateString = "delete where { <monkey:pod> ?p ?o . }"; request.setContent(updateString.getBytes(StandardCharsets.UTF_8)); // prepare mocks final Repository repMock = Mockito.mock(Repository.class); final RepositoryConnection connectionMock = Mockito.mock(RepositoryConnection.class); final ParserConfig parserConfigMock = Mockito.mock(ParserConfig.class); final Update updateMock = Mockito.mock(Update.class); Mockito.when(repMock.getConnection()).thenReturn(connectionMock); Mockito.when(connectionMock.prepareUpdate(QueryLanguage.SPARQL, updateString, null)).thenReturn(updateMock); Mockito.when(connectionMock.getParserConfig()).thenReturn(parserConfigMock); // repository interceptor uses this attribute request.setAttribute("repository", repMock); // act controller.handleRequest(request, new MockHttpServletResponse()); Mockito.verify(updateMock).setMaxExecutionTime(maxExecution); }
Example 15
Source File: ServletTestExecutionListener.java From java-technology-stack with MIT License | 5 votes |
private void setUpRequestContextIfNecessary(TestContext testContext) { if (!isActivated(testContext) || alreadyPopulatedRequestContextHolder(testContext)) { return; } ApplicationContext context = testContext.getApplicationContext(); if (context instanceof WebApplicationContext) { WebApplicationContext wac = (WebApplicationContext) context; ServletContext servletContext = wac.getServletContext(); Assert.state(servletContext instanceof MockServletContext, () -> String.format( "The WebApplicationContext for test context %s must be configured with a MockServletContext.", testContext)); if (logger.isDebugEnabled()) { logger.debug(String.format( "Setting up MockHttpServletRequest, MockHttpServletResponse, ServletWebRequest, and RequestContextHolder for test context %s.", testContext)); } MockServletContext mockServletContext = (MockServletContext) servletContext; MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext); request.setAttribute(CREATED_BY_THE_TESTCONTEXT_FRAMEWORK, Boolean.TRUE); MockHttpServletResponse response = new MockHttpServletResponse(); ServletWebRequest servletWebRequest = new ServletWebRequest(request, response); RequestContextHolder.setRequestAttributes(servletWebRequest); testContext.setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); testContext.setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); if (wac instanceof ConfigurableApplicationContext) { @SuppressWarnings("resource") ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) wac; ConfigurableListableBeanFactory bf = configurableApplicationContext.getBeanFactory(); bf.registerResolvableDependency(MockHttpServletResponse.class, response); bf.registerResolvableDependency(ServletWebRequest.class, servletWebRequest); } } }
Example 16
Source File: ErrorUtilsTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void testGetErrorStatus() { MockHttpServletRequest request = new MockHttpServletRequest(); assertEquals(500, ErrorUtils.getErrorStatus(request)); request.setAttribute(ErrorUtils.ATTR_ERROR_STATUS_CODE, 504); assertEquals(504, ErrorUtils.getErrorStatus(request)); }
Example 17
Source File: JseInformationsTagTest.java From sinavi-jfw with Apache License 2.0 | 5 votes |
@Before public void setup() throws Exception { MockServletContext sc = new MockServletContext(); request = new MockHttpServletRequest(sc); response = new MockHttpServletResponse(); page = new MockPageContext(sc, request, response); request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap()); }
Example 18
Source File: MetricsInterceptorMicrometerTest.java From kork with Apache License 2.0 | 4 votes |
@Test public void allPublishedMetricsHaveTheSameSetOfTagsAndCanBeRegisteredInMicrometer() throws Exception { MockHttpServletRequest request1 = new MockHttpServletRequest(); request1.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, Collections.emptyMap()); MockHttpServletRequest request2 = new MockHttpServletRequest(); request2.setAttribute( HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, Collections.singletonMap("path-var-1", "path-val-1")); request2.setParameter("param-1", "val-1"); interceptCall(interceptor, request1, RESPONSE, HANDLER, null); interceptCall(interceptor, request1, RESPONSE, HANDLER, new RuntimeException()); interceptCall(interceptor, request2, RESPONSE, HANDLER, null); interceptCall(interceptor, request2, RESPONSE, HANDLER, new IllegalArgumentException()); Search actual = simpleMeterRegistry.find("controller.invocations"); assertThat(getAllTagsAndRemovePercentileTag(actual)) .hasSize(4) .containsOnly( Arrays.asList( Tag.of("cause", "IllegalArgumentException"), Tag.of("controller", "TestController"), Tag.of("method", "execute"), Tag.of("param-1", "val-1"), Tag.of("param-2", "None"), Tag.of("path-var-1", "path-val-1"), Tag.of("path-var-2", "None"), Tag.of("statistic", "percentile"), Tag.of("status", "5xx"), Tag.of("statusCode", "500"), Tag.of("success", "false")), Arrays.asList( Tag.of("cause", "RuntimeException"), Tag.of("controller", "TestController"), Tag.of("method", "execute"), Tag.of("param-1", "None"), Tag.of("param-2", "None"), Tag.of("path-var-1", "None"), Tag.of("path-var-2", "None"), Tag.of("statistic", "percentile"), Tag.of("status", "5xx"), Tag.of("statusCode", "500"), Tag.of("success", "false")), Arrays.asList( Tag.of("cause", "None"), Tag.of("controller", "TestController"), Tag.of("method", "execute"), Tag.of("param-1", "val-1"), Tag.of("param-2", "None"), Tag.of("path-var-1", "path-val-1"), Tag.of("path-var-2", "None"), Tag.of("statistic", "percentile"), Tag.of("status", "2xx"), Tag.of("statusCode", "200"), Tag.of("success", "true")), Arrays.asList( Tag.of("cause", "None"), Tag.of("controller", "TestController"), Tag.of("method", "execute"), Tag.of("param-1", "None"), Tag.of("param-2", "None"), Tag.of("path-var-1", "None"), Tag.of("path-var-2", "None"), Tag.of("statistic", "percentile"), Tag.of("status", "2xx"), Tag.of("statusCode", "200"), Tag.of("success", "true"))); }
Example 19
Source File: MessageContextTest.java From sinavi-jfw with Apache License 2.0 | 4 votes |
@Before public void setUp() { MockServletContext sc = new MockServletContext(); request = new MockHttpServletRequest(sc); request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap()); }
Example 20
Source File: MockHttpServletRequestBuilderTests.java From spring-analysis-note with MIT License | 4 votes |
public MockHttpServletRequest postProcessRequest(MockHttpServletRequest request) { request.setAttribute(attr, value); return request; }