Here are the examples of the java api org.springframework.mock.web.MockServletContext taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
76 Examples
19
View Source File : DefaultMockMvcBuilderTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Tests for {@link DefaultMockMvcBuilder}.
*
* @author Rob Winch
* @author Sebastien Deleuze
* @author Sam Brannen
* @author Stephane Nicoll
*/
public clreplaced DefaultMockMvcBuilderTests {
private final MockServletContext servletContext = new MockServletContext();
@Test
public void webAppContextSetupWithNullWac() {
replacedertThatIllegalArgumentException().isThrownBy(() -> webAppContextSetup(null)).withMessage("WebApplicationContext is required");
}
@Test
public void webAppContextSetupWithNullServletContext() {
replacedertThatIllegalArgumentException().isThrownBy(() -> webAppContextSetup(new StubWebApplicationContext(null))).withMessage("WebApplicationContext must have a ServletContext");
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributePreviouslySet() {
StubWebApplicationContext child = new StubWebApplicationContext(this.servletContext);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, child);
DefaultMockMvcBuilder builder = webAppContextSetup(child);
replacedertSame(builder.initWebAppContext(), WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributePreviouslySetWithContextHierarchy() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, root);
StaticWebApplicationContext child = new StaticWebApplicationContext();
child.setParent(root);
child.setServletContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(child);
replacedertSame(builder.initWebAppContext().getParent(), WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributeNotPreviouslySet() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
WebApplicationContext wac = builder.initWebAppContext();
replacedertSame(root, wac);
replacedertSame(root, WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributeNotPreviouslySetWithContextHierarchy() {
StaticApplicationContext ear = new StaticApplicationContext();
StaticWebApplicationContext root = new StaticWebApplicationContext();
root.setParent(ear);
root.setServletContext(this.servletContext);
StaticWebApplicationContext dispatcher = new StaticWebApplicationContext();
dispatcher.setParent(root);
dispatcher.setServletContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(dispatcher);
WebApplicationContext wac = builder.initWebAppContext();
replacedertSame(dispatcher, wac);
replacedertSame(root, wac.getParent());
replacedertSame(ear, wac.getParent().getParent());
replacedertSame(root, WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See /SPR-14277
*/
@Test
public void dispatcherServletCustomizer() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("test-id"));
builder.dispatchOptions(true);
MockMvc mvc = builder.build();
DispatcherServlet ds = (DispatcherServlet) new DirectFieldAccessor(mvc).getPropertyValue("servlet");
replacedertEquals("test-id", ds.getContextId());
}
@Test
public void dispatcherServletCustomizerProcessedInOrder() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("test-id"));
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("override-id"));
builder.dispatchOptions(true);
MockMvc mvc = builder.build();
DispatcherServlet ds = (DispatcherServlet) new DirectFieldAccessor(mvc).getPropertyValue("servlet");
replacedertEquals("override-id", ds.getContextId());
}
}
19
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : tillias
License : MIT License
Project Creator : tillias
/**
* Unit tests for the {@link WebConfigurer} clreplaced.
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot()).isEqualTo(new File("target/clreplacedes/static/"));
}
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
19
View Source File : DefaultMockMvcBuilderTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Tests for {@link DefaultMockMvcBuilder}.
*
* @author Rob Winch
* @author Sebastien Deleuze
* @author Sam Brannen
* @author Stephane Nicoll
*/
public clreplaced DefaultMockMvcBuilderTests {
private final MockServletContext servletContext = new MockServletContext();
@Test
public void webAppContextSetupWithNullWac() {
replacedertThatIllegalArgumentException().isThrownBy(() -> webAppContextSetup(null)).withMessage("WebApplicationContext is required");
}
@Test
public void webAppContextSetupWithNullServletContext() {
replacedertThatIllegalArgumentException().isThrownBy(() -> webAppContextSetup(new StubWebApplicationContext(null))).withMessage("WebApplicationContext must have a ServletContext");
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributePreviouslySet() {
StubWebApplicationContext child = new StubWebApplicationContext(this.servletContext);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, child);
DefaultMockMvcBuilder builder = webAppContextSetup(child);
replacedertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)).isSameAs(builder.initWebAppContext());
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributePreviouslySetWithContextHierarchy() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, root);
StaticWebApplicationContext child = new StaticWebApplicationContext();
child.setParent(root);
child.setServletContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(child);
replacedertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)).isSameAs(builder.initWebAppContext().getParent());
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributeNotPreviouslySet() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
WebApplicationContext wac = builder.initWebAppContext();
replacedertThat(wac).isSameAs(root);
replacedertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)).isSameAs(root);
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributeNotPreviouslySetWithContextHierarchy() {
StaticApplicationContext ear = new StaticApplicationContext();
StaticWebApplicationContext root = new StaticWebApplicationContext();
root.setParent(ear);
root.setServletContext(this.servletContext);
StaticWebApplicationContext dispatcher = new StaticWebApplicationContext();
dispatcher.setParent(root);
dispatcher.setServletContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(dispatcher);
WebApplicationContext wac = builder.initWebAppContext();
replacedertThat(wac).isSameAs(dispatcher);
replacedertThat(wac.getParent()).isSameAs(root);
replacedertThat(wac.getParent().getParent()).isSameAs(ear);
replacedertThat(WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext)).isSameAs(root);
}
/**
* See /SPR-14277
*/
@Test
public void dispatcherServletCustomizer() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("test-id"));
builder.dispatchOptions(true);
MockMvc mvc = builder.build();
DispatcherServlet ds = (DispatcherServlet) new DirectFieldAccessor(mvc).getPropertyValue("servlet");
replacedertThat(ds.getContextId()).isEqualTo("test-id");
}
@Test
public void dispatcherServletCustomizerProcessedInOrder() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("test-id"));
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("override-id"));
builder.dispatchOptions(true);
MockMvc mvc = builder.build();
DispatcherServlet ds = (DispatcherServlet) new DirectFieldAccessor(mvc).getPropertyValue("servlet");
replacedertThat(ds.getContextId()).isEqualTo("override-id");
}
}
19
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
/**
* Unit tests for the {@link WebConfigurer} clreplaced.
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot()).isEqualTo(new File("build/resources/main/static/"));
}
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
19
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
/**
* Unit tests for the {@link WebConfigurer} clreplaced.
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot()).isEqualTo(new File("target/clreplacedes/static/"));
}
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
19
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
/**
* Unit tests for the {@link WebConfigurer} clreplaced.
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
19
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
/**
* Unit tests for the {@link WebConfigurer} clreplaced.
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
19
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : otto-de
License : Apache License 2.0
Project Creator : otto-de
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("build/www"));
}
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
19
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : OpenArchitex
License : MIT License
Project Creator : OpenArchitex
/**
* Unit tests for the {@link WebConfigurer} clreplaced.
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot()).isEqualTo(new File("target/clreplacedes/static/"));
}
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
19
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : oktadeveloper
License : Apache License 2.0
Project Creator : oktadeveloper
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("build/www"));
}
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
19
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : oktadeveloper
License : Apache License 2.0
Project Creator : oktadeveloper
/**
* Unit tests for the {@link WebConfigurer} clreplaced.
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
19
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : oktadeveloper
License : Apache License 2.0
Project Creator : oktadeveloper
/**
* Unit tests for the {@link WebConfigurer} clreplaced.
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
19
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : jhipster
License : Apache License 2.0
Project Creator : jhipster
/**
* Unit tests for the {@link WebConfigurer} clreplaced.
*/
clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
}
@Test
void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
}
@Test
void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot()).isEqualTo(new File("target/clreplacedes/static/"));
}
}
@Test
void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
18
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : yodamad
License : Apache License 2.0
Project Creator : yodamad
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www"));
}
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
18
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : xebialabs
License : Apache License 2.0
Project Creator : xebialabs
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("build/www"));
}
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
18
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : xebialabs
License : Apache License 2.0
Project Creator : xebialabs
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
18
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : xebialabs
License : Apache License 2.0
Project Creator : xebialabs
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
18
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : viz-centric
License : Apache License 2.0
Project Creator : viz-centric
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(new MockFilterRegistration()).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(new MockServletRegistration()).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www"));
}
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
static clreplaced MockFilterRegistration implements FilterRegistration, FilterRegistration.Dynamic {
@Override
public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames) {
}
@Override
public Collection<String> getServletNameMappings() {
return null;
}
@Override
public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... urlPatterns) {
}
@Override
public Collection<String> getUrlPatternMappings() {
return null;
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
static clreplaced MockServletRegistration implements ServletRegistration, ServletRegistration.Dynamic {
@Override
public void setLoadOnStartup(int loadOnStartup) {
}
@Override
public Set<String> setServletSecurity(ServletSecurityElement constraint) {
return null;
}
@Override
public void setMultipartConfig(MultipartConfigElement multipartConfig) {
}
@Override
public void setRunAsRole(String roleName) {
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public Set<String> addMapping(String... urlPatterns) {
return null;
}
@Override
public Collection<String> getMappings() {
return null;
}
@Override
public String getRunAsRole() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
public static clreplaced MockHazelcastInstance implements HazelcastInstance {
@Override
public String getName() {
return "HazelcastInstance";
}
@Override
public <E> IQueue<E> getQueue(String s) {
return null;
}
@Override
public <E> ITopic<E> getTopic(String s) {
return null;
}
@Override
public <E> ISet<E> getSet(String s) {
return null;
}
@Override
public <E> IList<E> getList(String s) {
return null;
}
@Override
public <K, V> IMap<K, V> getMap(String s) {
return null;
}
@Override
public <K, V> ReplicatedMap<K, V> getReplicatedMap(String s) {
return null;
}
@Override
public JobTracker getJobTracker(String s) {
return null;
}
@Override
public <K, V> MultiMap<K, V> getMultiMap(String s) {
return null;
}
@Override
public ILock getLock(String s) {
return null;
}
@Override
public <E> Ringbuffer<E> getRingbuffer(String s) {
return null;
}
@Override
public <E> ITopic<E> getReliableTopic(String s) {
return null;
}
@Override
public Cluster getCluster() {
return null;
}
@Override
public Endpoint getLocalEndpoint() {
return null;
}
@Override
public IExecutorService getExecutorService(String s) {
return null;
}
@Override
public DurableExecutorService getDurableExecutorService(String s) {
return null;
}
@Override
public <T> T executeTransaction(TransactionalTask<T> transactionalTask) throws TransactionException {
return null;
}
@Override
public <T> T executeTransaction(TransactionOptions transactionOptions, TransactionalTask<T> transactionalTask) throws TransactionException {
return null;
}
@Override
public TransactionContext newTransactionContext() {
return null;
}
@Override
public TransactionContext newTransactionContext(TransactionOptions transactionOptions) {
return null;
}
@Override
public IdGenerator getIdGenerator(String s) {
return null;
}
@Override
public IAtomicLong getAtomicLong(String s) {
return null;
}
@Override
public <E> IAtomicReference<E> getAtomicReference(String s) {
return null;
}
@Override
public ICountDownLatch getCountDownLatch(String s) {
return null;
}
@Override
public ISemapreplaced getSemapreplaced(String s) {
return null;
}
@Override
public Collection<DistributedObject> getDistributedObjects() {
return null;
}
@Override
public String addDistributedObjectListener(DistributedObjectListener distributedObjectListener) {
return null;
}
@Override
public boolean removeDistributedObjectListener(String s) {
return false;
}
@Override
public Config getConfig() {
return null;
}
@Override
public ParreplacedionService getParreplacedionService() {
return null;
}
@Override
public QuorumService getQuorumService() {
return null;
}
@Override
public ClientService getClientService() {
return null;
}
@Override
public LoggingService getLoggingService() {
return null;
}
@Override
public LifecycleService getLifecycleService() {
return null;
}
@Override
public <T extends DistributedObject> T getDistributedObject(String s, String s1) {
return null;
}
@Override
public ConcurrentMap<String, Object> getUserContext() {
return null;
}
@Override
public HazelcastXAResource getXAResource() {
return null;
}
@Override
public ICacheManager getCacheManager() {
return null;
}
@Override
public void shutdown() {
}
}
}
18
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www"));
}
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
18
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www"));
}
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
18
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(new MockFilterRegistration()).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(new MockServletRegistration()).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
static clreplaced MockFilterRegistration implements FilterRegistration, FilterRegistration.Dynamic {
@Override
public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames) {
}
@Override
public Collection<String> getServletNameMappings() {
return null;
}
@Override
public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... urlPatterns) {
}
@Override
public Collection<String> getUrlPatternMappings() {
return null;
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
static clreplaced MockServletRegistration implements ServletRegistration, ServletRegistration.Dynamic {
@Override
public void setLoadOnStartup(int loadOnStartup) {
}
@Override
public Set<String> setServletSecurity(ServletSecurityElement constraint) {
return null;
}
@Override
public void setMultipartConfig(MultipartConfigElement multipartConfig) {
}
@Override
public void setRunAsRole(String roleName) {
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public Set<String> addMapping(String... urlPatterns) {
return null;
}
@Override
public Collection<String> getMappings() {
return null;
}
@Override
public String getRunAsRole() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
}
18
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(new MockFilterRegistration()).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(new MockServletRegistration()).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props, null);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
static clreplaced MockFilterRegistration implements FilterRegistration, FilterRegistration.Dynamic {
@Override
public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames) {
}
@Override
public Collection<String> getServletNameMappings() {
return null;
}
@Override
public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... urlPatterns) {
}
@Override
public Collection<String> getUrlPatternMappings() {
return null;
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
static clreplaced MockServletRegistration implements ServletRegistration, ServletRegistration.Dynamic {
@Override
public void setLoadOnStartup(int loadOnStartup) {
}
@Override
public Set<String> setServletSecurity(ServletSecurityElement constraint) {
return null;
}
@Override
public void setMultipartConfig(MultipartConfigElement multipartConfig) {
}
@Override
public void setRunAsRole(String roleName) {
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public Set<String> addMapping(String... urlPatterns) {
return null;
}
@Override
public Collection<String> getMappings() {
return null;
}
@Override
public String getRunAsRole() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
}
18
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(new MockFilterRegistration()).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(new MockServletRegistration()).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props, null);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www"));
}
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
static clreplaced MockFilterRegistration implements FilterRegistration, FilterRegistration.Dynamic {
@Override
public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames) {
}
@Override
public Collection<String> getServletNameMappings() {
return null;
}
@Override
public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... urlPatterns) {
}
@Override
public Collection<String> getUrlPatternMappings() {
return null;
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
static clreplaced MockServletRegistration implements ServletRegistration, ServletRegistration.Dynamic {
@Override
public void setLoadOnStartup(int loadOnStartup) {
}
@Override
public Set<String> setServletSecurity(ServletSecurityElement constraint) {
return null;
}
@Override
public void setMultipartConfig(MultipartConfigElement multipartConfig) {
}
@Override
public void setRunAsRole(String roleName) {
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public Set<String> addMapping(String... urlPatterns) {
return null;
}
@Override
public Collection<String> getMappings() {
return null;
}
@Override
public String getRunAsRole() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
}
18
View Source File : WebConfigurerTest.java
License : MIT License
Project Creator : PacktPublishing
License : MIT License
Project Creator : PacktPublishing
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(new MockFilterRegistration()).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(new MockServletRegistration()).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props, null);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("build/www"));
}
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
static clreplaced MockFilterRegistration implements FilterRegistration, FilterRegistration.Dynamic {
@Override
public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames) {
}
@Override
public Collection<String> getServletNameMappings() {
return null;
}
@Override
public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... urlPatterns) {
}
@Override
public Collection<String> getUrlPatternMappings() {
return null;
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
static clreplaced MockServletRegistration implements ServletRegistration, ServletRegistration.Dynamic {
@Override
public void setLoadOnStartup(int loadOnStartup) {
}
@Override
public Set<String> setServletSecurity(ServletSecurityElement constraint) {
return null;
}
@Override
public void setMultipartConfig(MultipartConfigElement multipartConfig) {
}
@Override
public void setRunAsRole(String roleName) {
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public Set<String> addMapping(String... urlPatterns) {
return null;
}
@Override
public Collection<String> getMappings() {
return null;
}
@Override
public String getRunAsRole() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
}
18
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : oktadeveloper
License : Apache License 2.0
Project Creator : oktadeveloper
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(new MockFilterRegistration()).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(new MockServletRegistration()).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props, new MockHazelcastInstance());
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext, never()).addFilter(eq("cachingHttpHeadersFilter"), any(CachingHttpHeadersFilter.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www"));
}
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
static clreplaced MockFilterRegistration implements FilterRegistration, FilterRegistration.Dynamic {
@Override
public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames) {
}
@Override
public Collection<String> getServletNameMappings() {
return null;
}
@Override
public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... urlPatterns) {
}
@Override
public Collection<String> getUrlPatternMappings() {
return null;
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
static clreplaced MockServletRegistration implements ServletRegistration, ServletRegistration.Dynamic {
@Override
public void setLoadOnStartup(int loadOnStartup) {
}
@Override
public Set<String> setServletSecurity(ServletSecurityElement constraint) {
return null;
}
@Override
public void setMultipartConfig(MultipartConfigElement multipartConfig) {
}
@Override
public void setRunAsRole(String roleName) {
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public Set<String> addMapping(String... urlPatterns) {
return null;
}
@Override
public Collection<String> getMappings() {
return null;
}
@Override
public String getRunAsRole() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
public static clreplaced MockHazelcastInstance implements HazelcastInstance {
@Override
public String getName() {
return "HazelcastInstance";
}
@Override
public <E> IQueue<E> getQueue(String s) {
return null;
}
@Override
public <E> ITopic<E> getTopic(String s) {
return null;
}
@Override
public <E> ISet<E> getSet(String s) {
return null;
}
@Override
public <E> IList<E> getList(String s) {
return null;
}
@Override
public <K, V> IMap<K, V> getMap(String s) {
return null;
}
@Override
public <K, V> ReplicatedMap<K, V> getReplicatedMap(String s) {
return null;
}
@Override
public JobTracker getJobTracker(String s) {
return null;
}
@Override
public <K, V> MultiMap<K, V> getMultiMap(String s) {
return null;
}
@Override
public ILock getLock(String s) {
return null;
}
@Override
public <E> Ringbuffer<E> getRingbuffer(String s) {
return null;
}
@Override
public <E> ITopic<E> getReliableTopic(String s) {
return null;
}
@Override
public Cluster getCluster() {
return null;
}
@Override
public Endpoint getLocalEndpoint() {
return null;
}
@Override
public IExecutorService getExecutorService(String s) {
return null;
}
@Override
public DurableExecutorService getDurableExecutorService(String s) {
return null;
}
@Override
public <T> T executeTransaction(TransactionalTask<T> transactionalTask) throws TransactionException {
return null;
}
@Override
public <T> T executeTransaction(TransactionOptions transactionOptions, TransactionalTask<T> transactionalTask) throws TransactionException {
return null;
}
@Override
public TransactionContext newTransactionContext() {
return null;
}
@Override
public TransactionContext newTransactionContext(TransactionOptions transactionOptions) {
return null;
}
@Override
public IdGenerator getIdGenerator(String s) {
return null;
}
@Override
public IAtomicLong getAtomicLong(String s) {
return null;
}
@Override
public <E> IAtomicReference<E> getAtomicReference(String s) {
return null;
}
@Override
public ICountDownLatch getCountDownLatch(String s) {
return null;
}
@Override
public ISemapreplaced getSemapreplaced(String s) {
return null;
}
@Override
public Collection<DistributedObject> getDistributedObjects() {
return null;
}
@Override
public String addDistributedObjectListener(DistributedObjectListener distributedObjectListener) {
return null;
}
@Override
public boolean removeDistributedObjectListener(String s) {
return false;
}
@Override
public Config getConfig() {
return null;
}
@Override
public ParreplacedionService getParreplacedionService() {
return null;
}
@Override
public QuorumService getQuorumService() {
return null;
}
@Override
public ClientService getClientService() {
return null;
}
@Override
public LoggingService getLoggingService() {
return null;
}
@Override
public LifecycleService getLifecycleService() {
return null;
}
@Override
public <T extends DistributedObject> T getDistributedObject(String s, String s1) {
return null;
}
@Override
public ConcurrentMap<String, Object> getUserContext() {
return null;
}
@Override
public HazelcastXAResource getXAResource() {
return null;
}
@Override
public ICacheManager getCacheManager() {
return null;
}
@Override
public void shutdown() {
}
}
}
18
View Source File : SafeContextLoaderListenerTests.java
License : Apache License 2.0
Project Creator : luotuo
License : Apache License 2.0
Project Creator : luotuo
/**
* Test case for SafeContextLoaderListener.
*
* @author Andrew Petro
* @since 3.0
*/
public clreplaced SafeContextLoaderListenerTests {
private MockServletContext servletContext;
private ServletContextEvent servletContextEvent;
private SafeContextLoaderListener listener;
@Before
public void setUp() throws Exception {
this.listener = new SafeContextLoaderListener();
this.servletContext = new MockServletContext();
this.servletContextEvent = new ServletContextEvent(this.servletContext);
}
/**
* Test that SafeContextLoaderListener does not propagate exceptions thrown
* by its delegate in contextInitialized().
*/
@Test
public void testContextInitialized() {
/*
* this testcase relies upon the fact that ContextLoaderListener()
* throws a FileNotFound exception when invoked in the context of this
* testcase because it does not find the resource
* /WEB-INF/applicationContext.xml if our SafeContextLoaderListener
* instance also throws the exception its delegate threw, this testcase
* will fail. If it catches the exception, this test method will return
* without having failed and so indicate success.
*/
this.listener.contextInitialized(this.servletContextEvent);
}
@Test
public void testContextDestroy() {
this.listener.contextDestroyed(this.servletContextEvent);
}
}
18
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : jhipster
License : Apache License 2.0
Project Creator : jhipster
/**
* Unit tests for the {@link WebConfigurer} clreplaced.
*/
clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("application/json");
if (container.getDoreplacedentRoot() != null) {
replacedertThat(container.getDoreplacedentRoot()).isEqualTo(new File("target/clreplacedes/static/"));
}
}
@Test
void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
18
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : jhipster
License : Apache License 2.0
Project Creator : jhipster
/**
* Unit tests for the {@link WebConfigurer} clreplaced.
*/
clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
@BeforeEach
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(mock(FilterRegistration.Dynamic.clreplaced)).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(mock(ServletRegistration.Dynamic.clreplaced)).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
webConfigurer = new WebConfigurer(env, props);
}
@Test
void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
}
18
View Source File : BasicSpringResourceSample.java
License : Apache License 2.0
Project Creator : Illusionist80
License : Apache License 2.0
Project Creator : Illusionist80
public static void main(String[] args) throws IOException {
// Resource res=new ClreplacedPathResource("abc2.txt");
// Resource res=new FileSystemResource("src/abc2.txt");
// Resource res=new UrlResource("file:///C:/Trainings/Spring3.0/Chapter1 - CORE/SpringWS/SpringChapter1-CorePartB-Resources/src/abc2.txt");
// Resource res=new UrlResource("http://www.google.com");
InputStream is = new ByteArrayInputStream("testbytesfromastring".getBytes());
Resource res = new InputStreamResource(is, "bais");
MockServletContext msc = new MockServletContext();
Resource resWeb = new ServletContextResource(msc, "org/springframework/core/io/Resource.clreplaced");
showFileContent(resWeb.getInputStream());
}
18
View Source File : MockHttpServletRequest.java
License : Apache License 2.0
Project Creator : elastic
License : Apache License 2.0
Project Creator : elastic
public clreplaced MockHttpServletRequest implements HttpServletRequest {
private final Map<String, String> headers = new HashMap<>();
private final Map<String, String[]> parameters = new HashMap<>();
private final Map<String, Object> attributes = new HashMap<>();
private final String method;
private final String requestUrl;
private String contextPath;
private String pathInfo;
private String queryString;
private String requestURI;
private String servletPath;
private String serverName;
private MockServletContext servletContext = new MockServletContext();
public MockHttpServletRequest(String method, String requestUrl) {
this.method = method;
this.requestUrl = requestUrl;
}
public void setHeader(String name, String value) {
headers.put(name, value);
}
public void setParameter(String name, String value) {
parameters.put(name, new String[] { value });
}
public void setParameter(String name, String... values) {
parameters.put(name, values);
}
@Override
public String getAuthType() {
return null;
}
@Override
public Cookie[] getCookies() {
return new Cookie[0];
}
@Override
public long getDateHeader(String name) {
return 0;
}
@Override
public String getHeader(String name) {
return headers.get(name);
}
@Override
public Enumeration<String> getHeaders(String name) {
return Collections.enumeration(Collections.singletonList(headers.get(name)));
}
@Override
public Enumeration<String> getHeaderNames() {
return Collections.enumeration(headers.keySet());
}
@Override
public int getIntHeader(String name) {
return 0;
}
@Override
public String getMethod() {
return method;
}
@Override
public String getPathInfo() {
return pathInfo;
}
@Override
public String getPathTranslated() {
return null;
}
@Override
public String getContextPath() {
return contextPath;
}
@Override
public String getQueryString() {
return queryString;
}
@Override
public String getRemoteUser() {
return null;
}
@Override
public boolean isUserInRole(String role) {
return false;
}
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public String getRequestedSessionId() {
return null;
}
@Override
public String getRequestURI() {
return requestURI;
}
@Override
public StringBuffer getRequestURL() {
return new StringBuffer(requestUrl);
}
@Override
public String getServletPath() {
return servletPath;
}
@Override
public HttpSession getSession(boolean create) {
return null;
}
@Override
public HttpSession getSession() {
return null;
}
@Override
public boolean isRequestedSessionIdValid() {
return false;
}
@Override
public boolean isRequestedSessionIdFromCookie() {
return false;
}
@Override
public boolean isRequestedSessionIdFromURL() {
return false;
}
@Override
public boolean isRequestedSessionIdFromUrl() {
return false;
}
@Override
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
return false;
}
@Override
public void login(String username, String preplacedword) throws ServletException {
}
@Override
public void logout() throws ServletException {
}
@Override
public Collection<Part> getParts() throws IOException, ServletException {
return null;
}
@Override
public Part getPart(String name) throws IOException, ServletException {
return null;
}
@Override
public Object getAttribute(String name) {
return attributes.get(name);
}
@Override
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(attributes.keySet());
}
@Override
public String getCharacterEncoding() {
return null;
}
@Override
public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
}
@Override
public int getContentLength() {
return 0;
}
@Override
public String getContentType() {
return null;
}
@Override
public ServletInputStream getInputStream() throws IOException {
return null;
}
@Override
public String getParameter(String name) {
final String[] parameters = this.parameters.get(name);
return parameters != null ? parameters[0] : null;
}
@Override
public Enumeration<String> getParameterNames() {
return Collections.enumeration(parameters.keySet());
}
@Override
public String[] getParameterValues(String name) {
return new String[0];
}
@Override
public Map<String, String[]> getParameterMap() {
return parameters;
}
@Override
public String getProtocol() {
return "HTTP/1.1";
}
@Override
public String getScheme() {
return "http";
}
@Override
public String getServerName() {
return serverName;
}
@Override
public int getServerPort() {
return 80;
}
@Override
public BufferedReader getReader() throws IOException {
return null;
}
@Override
public String getRemoteAddr() {
return "127.0.0.1";
}
@Override
public String getRemoteHost() {
return "localhost";
}
@Override
public void setAttribute(String name, Object o) {
attributes.put(name, o);
}
@Override
public void removeAttribute(String name) {
attributes.remove(name);
}
@Override
public Locale getLocale() {
return null;
}
@Override
public Enumeration<Locale> getLocales() {
return null;
}
@Override
public boolean isSecure() {
return false;
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
return null;
}
@Override
public String getRealPath(String path) {
return null;
}
@Override
public int getRemotePort() {
return 0;
}
@Override
public String getLocalName() {
return null;
}
@Override
public String getLocalAddr() {
return "127.0.0.1";
}
@Override
public int getLocalPort() {
return 80;
}
@Override
public ServletContext getServletContext() {
return servletContext;
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
return null;
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
return null;
}
@Override
public boolean isAsyncStarted() {
return false;
}
@Override
public boolean isAsyncSupported() {
return false;
}
@Override
public AsyncContext getAsyncContext() {
return null;
}
@Override
public DispatcherType getDispatcherType() {
return DispatcherType.REQUEST;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public void setPathInfo(String pathInfo) {
this.pathInfo = pathInfo;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public void setRequestURI(String requestURI) {
this.requestURI = requestURI;
}
public void setServletPath(String servletPath) {
this.servletPath = servletPath;
}
public void setServerName(String serverName) {
this.serverName = serverName;
}
}
18
View Source File : WebMvcUtilsTest.java
License : GNU General Public License v3.0
Project Creator : alibaba
License : GNU General Public License v3.0
Project Creator : alibaba
@Test
public void testAppendGlobalInitializerClreplacedInitParameter() {
MockServletContext servletContext = new MockServletContext();
WebMvcUtils.appendGlobalInitializerClreplacedInitParameter(servletContext, ApplicationContextInitializer.clreplaced);
replacedert.replacedertEquals(ApplicationContextInitializer.clreplaced.getName(), servletContext.getInitParameter(GLOBAL_INITIALIZER_CLreplacedES_PARAM));
}
18
View Source File : WebMvcUtilsTest.java
License : GNU General Public License v3.0
Project Creator : alibaba
License : GNU General Public License v3.0
Project Creator : alibaba
@Test
public void testAppendContextInitializerClreplacedInitParameter() {
MockServletContext servletContext = new MockServletContext();
WebMvcUtils.appendContextInitializerClreplacedInitParameter(servletContext, ApplicationContextInitializer.clreplaced);
replacedert.replacedertEquals(ApplicationContextInitializer.clreplaced.getName(), servletContext.getInitParameter(CONTEXT_INITIALIZER_CLreplacedES_PARAM));
}
17
View Source File : WebConfigurerTest.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private ServerProperties serverProperties;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(new MockFilterRegistration()).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(new MockServletRegistration()).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
serverProperties = new ServerProperties();
webConfigurer = new WebConfigurer(env, props, serverProperties);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(ArgumentMatchers.eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(ArgumentMatchers.eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext, never()).addServlet(ArgumentMatchers.eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(ArgumentMatchers.eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(ArgumentMatchers.eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext).addServlet(ArgumentMatchers.eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
serverProperties.getHttp2().setEnabled(true);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
static clreplaced MockFilterRegistration implements FilterRegistration, FilterRegistration.Dynamic {
@Override
public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames) {
}
@Override
public Collection<String> getServletNameMappings() {
return null;
}
@Override
public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... urlPatterns) {
}
@Override
public Collection<String> getUrlPatternMappings() {
return null;
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
static clreplaced MockServletRegistration implements ServletRegistration, ServletRegistration.Dynamic {
@Override
public void setLoadOnStartup(int loadOnStartup) {
}
@Override
public Set<String> setServletSecurity(ServletSecurityElement constraint) {
return null;
}
@Override
public void setMultipartConfig(MultipartConfigElement multipartConfig) {
}
@Override
public void setRunAsRole(String roleName) {
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public Set<String> addMapping(String... urlPatterns) {
return null;
}
@Override
public Collection<String> getMappings() {
return null;
}
@Override
public String getRunAsRole() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
}
17
View Source File : WebConfigurerIntTest.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerIntTest extends AbstractUnitTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private ServerProperties serverProperties;
private MetricRegistry metricRegistry;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(new MockFilterRegistration()).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(new MockServletRegistration()).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
serverProperties = new ServerProperties();
webConfigurer = new WebConfigurer(env, serverProperties, props);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext, never()).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
verify(servletContext).addServlet(eq("H2Console"), any(WebServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
serverProperties.getHttp2().setEnabled(true);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
static clreplaced MockFilterRegistration implements FilterRegistration, FilterRegistration.Dynamic {
@Override
public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames) {
}
@Override
public Collection<String> getServletNameMappings() {
return null;
}
@Override
public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... urlPatterns) {
}
@Override
public Collection<String> getUrlPatternMappings() {
return null;
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
static clreplaced MockServletRegistration implements ServletRegistration, ServletRegistration.Dynamic {
@Override
public void setLoadOnStartup(int loadOnStartup) {
}
@Override
public Set<String> setServletSecurity(ServletSecurityElement constraint) {
return null;
}
@Override
public void setMultipartConfig(MultipartConfigElement multipartConfig) {
}
@Override
public void setRunAsRole(String roleName) {
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public Set<String> addMapping(String... urlPatterns) {
return null;
}
@Override
public Collection<String> getMappings() {
return null;
}
@Override
public String getRunAsRole() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
}
17
View Source File : WebConfigurerUnitTest.java
License : Apache License 2.0
Project Creator : xm-online
License : Apache License 2.0
Project Creator : xm-online
/**
* Unit tests for the WebConfigurer clreplaced.
*
* @see WebConfigurer
*/
public clreplaced WebConfigurerUnitTest {
private WebConfigurer webConfigurer;
private MockServletContext servletContext;
private MockEnvironment env;
private JHipsterProperties props;
private MetricRegistry metricRegistry;
private ServerProperties serverProperties;
@Before
public void setup() {
servletContext = spy(new MockServletContext());
doReturn(new MockFilterRegistration()).when(servletContext).addFilter(anyString(), any(Filter.clreplaced));
doReturn(new MockServletRegistration()).when(servletContext).addServlet(anyString(), any(Servlet.clreplaced));
env = new MockEnvironment();
props = new JHipsterProperties();
serverProperties = new ServerProperties();
webConfigurer = new WebConfigurer(env, props, serverProperties);
metricRegistry = new MetricRegistry();
webConfigurer.setMetricRegistry(metricRegistry);
}
@Test
public void testStartUpProdServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
}
@Test
public void testStartUpDevServletContext() throws ServletException {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT);
webConfigurer.onStartup(servletContext);
replacedertThat(servletContext.getAttribute(InstrumentedFilter.REGISTRY_ATTRIBUTE)).isEqualTo(metricRegistry);
replacedertThat(servletContext.getAttribute(MetricsServlet.METRICS_REGISTRY)).isEqualTo(metricRegistry);
verify(servletContext).addFilter(eq("webappMetricsFilter"), any(InstrumentedFilter.clreplaced));
verify(servletContext).addServlet(eq("metricsServlet"), any(MetricsServlet.clreplaced));
}
@Test
public void testCustomizeServletContainer() {
env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
replacedertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
replacedertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
replacedertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
@Test
public void testUndertowHttp2Enabled() {
serverProperties.getHttp2().setEnabled(true);
UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
webConfigurer.customize(container);
Builder builder = Undertow.builder();
container.getBuilderCustomizers().forEach(c -> c.customize(builder));
OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
replacedertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
@Test
public void testCorsFilterOnApiPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(options("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com").header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com")).andExpect(header().string(HttpHeaders.VARY, "Origin")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET,POST,PUT,DELETE")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true")).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "1800"));
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().string(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "other.domain.com"));
}
@Test
public void testCorsFilterOnOtherPath() throws Exception {
props.getCors().setAllowedOrigins(Collections.singletonList("*"));
props.getCors().setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
props.getCors().setAllowedHeaders(Collections.singletonList("*"));
props.getCors().setMaxAge(1800L);
props.getCors().setAllowCredentials(true);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/test/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated() throws Exception {
props.getCors().setAllowedOrigins(null);
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
@Test
public void testCorsFilterDeactivated2() throws Exception {
props.getCors().setAllowedOrigins(new ArrayList<>());
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new WebConfigurerTestController()).addFilters(webConfigurer.corsFilter()).build();
mockMvc.perform(get("/api/test-cors").header(HttpHeaders.ORIGIN, "other.domain.com")).andExpect(status().isOk()).andExpect(header().doesNotExist(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN));
}
static clreplaced MockFilterRegistration implements FilterRegistration, FilterRegistration.Dynamic {
@Override
public void addMappingForServletNames(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames) {
}
@Override
public Collection<String> getServletNameMappings() {
return null;
}
@Override
public void addMappingForUrlPatterns(EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... urlPatterns) {
}
@Override
public Collection<String> getUrlPatternMappings() {
return null;
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
static clreplaced MockServletRegistration implements ServletRegistration, ServletRegistration.Dynamic {
@Override
public void setLoadOnStartup(int loadOnStartup) {
}
@Override
public Set<String> setServletSecurity(ServletSecurityElement constraint) {
return null;
}
@Override
public void setMultipartConfig(MultipartConfigElement multipartConfig) {
}
@Override
public void setRunAsRole(String roleName) {
}
@Override
public void setAsyncSupported(boolean isAsyncSupported) {
}
@Override
public Set<String> addMapping(String... urlPatterns) {
return null;
}
@Override
public Collection<String> getMappings() {
return null;
}
@Override
public String getRunAsRole() {
return null;
}
@Override
public String getName() {
return null;
}
@Override
public String getClreplacedName() {
return null;
}
@Override
public boolean setInitParameter(String name, String value) {
return false;
}
@Override
public String getInitParameter(String name) {
return null;
}
@Override
public Set<String> setInitParameters(Map<String, String> initParameters) {
return null;
}
@Override
public Map<String, String> getInitParameters() {
return null;
}
}
}
17
View Source File : ServletTestExecutionListenerTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Unit tests for {@link ServletTestExecutionListener}.
*
* @author Sam Brannen
* @author Phillip Webb
* @since 3.2.6
*/
public clreplaced ServletTestExecutionListenerTests {
private static final String SET_UP_OUTSIDE_OF_STEL = "setUpOutsideOfStel";
private final WebApplicationContext wac = mock(WebApplicationContext.clreplaced);
private final MockServletContext mockServletContext = new MockServletContext();
private final TestContext testContext = mock(TestContext.clreplaced);
private final ServletTestExecutionListener listener = new ServletTestExecutionListener();
@Before
public void setUp() {
given(wac.getServletContext()).willReturn(mockServletContext);
given(testContext.getApplicationContext()).willReturn(wac);
MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
MockHttpServletResponse response = new MockHttpServletResponse();
ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
request.setAttribute(SET_UP_OUTSIDE_OF_STEL, "true");
RequestContextHolder.setRequestAttributes(servletWebRequest);
replacedertSetUpOutsideOfStelAttributeExists();
}
@Test
public void standardApplicationContext() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(getClreplaced());
given(testContext.getApplicationContext()).willReturn(mock(ApplicationContext.clreplaced));
listener.beforeTestClreplaced(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
listener.prepareTestInstance(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
listener.beforeTestMethod(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
listener.afterTestMethod(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
}
@Test
public void legacyWebTestCaseWithoutExistingRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(LegacyWebTestCase.clreplaced);
RequestContextHolder.resetRequestAttributes();
replacedertRequestAttributesDoNotExist();
listener.beforeTestClreplaced(testContext);
listener.prepareTestInstance(testContext);
replacedertRequestAttributesDoNotExist();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null);
listener.beforeTestMethod(testContext);
replacedertRequestAttributesDoNotExist();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
listener.afterTestMethod(testContext);
verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
replacedertRequestAttributesDoNotExist();
}
@Test
public void legacyWebTestCaseWithPresetRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(LegacyWebTestCase.clreplaced);
listener.beforeTestClreplaced(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
listener.prepareTestInstance(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null);
listener.beforeTestMethod(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null);
listener.afterTestMethod(testContext);
verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
replacedertSetUpOutsideOfStelAttributeExists();
}
@Test
public void atWebAppConfigTestCaseWithoutExistingRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(AtWebAppConfigWebTestCase.clreplaced);
RequestContextHolder.resetRequestAttributes();
listener.beforeTestClreplaced(testContext);
replacedertRequestAttributesDoNotExist();
replacedertWebAppConfigTestCase();
}
@Test
public void atWebAppConfigTestCaseWithPresetRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(AtWebAppConfigWebTestCase.clreplaced);
listener.beforeTestClreplaced(testContext);
replacedertRequestAttributesExist();
replacedertWebAppConfigTestCase();
}
/**
* @since 4.3
*/
@Test
public void activateListenerWithoutExistingRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(NoAtWebAppConfigWebTestCase.clreplaced);
given(testContext.getAttribute(ServletTestExecutionListener.ACTIVATE_LISTENER)).willReturn(true);
RequestContextHolder.resetRequestAttributes();
listener.beforeTestClreplaced(testContext);
replacedertRequestAttributesDoNotExist();
replacedertWebAppConfigTestCase();
}
private RequestAttributes replacedertRequestAttributesExist() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
replacedertNotNull("request attributes should exist", requestAttributes);
return requestAttributes;
}
private void replacedertRequestAttributesDoNotExist() {
replacedertNull("request attributes should not exist", RequestContextHolder.getRequestAttributes());
}
private void replacedertSetUpOutsideOfStelAttributeExists() {
RequestAttributes requestAttributes = replacedertRequestAttributesExist();
Object setUpOutsideOfStel = requestAttributes.getAttribute(SET_UP_OUTSIDE_OF_STEL, RequestAttributes.SCOPE_REQUEST);
replacedertNotNull(SET_UP_OUTSIDE_OF_STEL + " should exist as a request attribute", setUpOutsideOfStel);
}
private void replacedertSetUpOutsideOfStelAttributeDoesNotExist() {
RequestAttributes requestAttributes = replacedertRequestAttributesExist();
Object setUpOutsideOfStel = requestAttributes.getAttribute(SET_UP_OUTSIDE_OF_STEL, RequestAttributes.SCOPE_REQUEST);
replacedertNull(SET_UP_OUTSIDE_OF_STEL + " should NOT exist as a request attribute", setUpOutsideOfStel);
}
private void replacedertWebAppConfigTestCase() throws Exception {
listener.prepareTestInstance(testContext);
replacedertRequestAttributesExist();
replacedertSetUpOutsideOfStelAttributeDoesNotExist();
verify(testContext, times(1)).setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
verify(testContext, times(1)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(Boolean.TRUE);
listener.beforeTestMethod(testContext);
replacedertRequestAttributesExist();
replacedertSetUpOutsideOfStelAttributeDoesNotExist();
verify(testContext, times(1)).setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
verify(testContext, times(1)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
listener.afterTestMethod(testContext);
verify(testContext).removeAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
verify(testContext).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
replacedertRequestAttributesDoNotExist();
}
static clreplaced LegacyWebTestCase {
}
@WebAppConfiguration
static clreplaced AtWebAppConfigWebTestCase {
}
static clreplaced NoAtWebAppConfigWebTestCase {
}
}
17
View Source File : ServletTestExecutionListenerTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Unit tests for {@link ServletTestExecutionListener}.
*
* @author Sam Brannen
* @author Phillip Webb
* @since 3.2.6
*/
clreplaced ServletTestExecutionListenerTests {
private static final String SET_UP_OUTSIDE_OF_STEL = "setUpOutsideOfStel";
private final WebApplicationContext wac = mock(WebApplicationContext.clreplaced);
private final MockServletContext mockServletContext = new MockServletContext();
private final TestContext testContext = mock(TestContext.clreplaced);
private final ServletTestExecutionListener listener = new ServletTestExecutionListener();
@BeforeEach
void setUp() {
given(wac.getServletContext()).willReturn(mockServletContext);
given(testContext.getApplicationContext()).willReturn(wac);
MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
MockHttpServletResponse response = new MockHttpServletResponse();
ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
request.setAttribute(SET_UP_OUTSIDE_OF_STEL, "true");
RequestContextHolder.setRequestAttributes(servletWebRequest);
replacedertSetUpOutsideOfStelAttributeExists();
}
@Test
void standardApplicationContext() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(getClreplaced());
given(testContext.getApplicationContext()).willReturn(mock(ApplicationContext.clreplaced));
listener.beforeTestClreplaced(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
listener.prepareTestInstance(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
listener.beforeTestMethod(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
listener.afterTestMethod(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
}
@Test
void legacyWebTestCaseWithoutExistingRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(LegacyWebTestCase.clreplaced);
RequestContextHolder.resetRequestAttributes();
replacedertRequestAttributesDoNotExist();
listener.beforeTestClreplaced(testContext);
listener.prepareTestInstance(testContext);
replacedertRequestAttributesDoNotExist();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null);
listener.beforeTestMethod(testContext);
replacedertRequestAttributesDoNotExist();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
listener.afterTestMethod(testContext);
verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
replacedertRequestAttributesDoNotExist();
}
@Test
void legacyWebTestCaseWithPresetRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(LegacyWebTestCase.clreplaced);
listener.beforeTestClreplaced(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
listener.prepareTestInstance(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null);
listener.beforeTestMethod(testContext);
replacedertSetUpOutsideOfStelAttributeExists();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null);
listener.afterTestMethod(testContext);
verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
replacedertSetUpOutsideOfStelAttributeExists();
}
@Test
void atWebAppConfigTestCaseWithoutExistingRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(AtWebAppConfigWebTestCase.clreplaced);
RequestContextHolder.resetRequestAttributes();
listener.beforeTestClreplaced(testContext);
replacedertRequestAttributesDoNotExist();
replacedertWebAppConfigTestCase();
}
@Test
void atWebAppConfigTestCaseWithPresetRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(AtWebAppConfigWebTestCase.clreplaced);
listener.beforeTestClreplaced(testContext);
replacedertRequestAttributesExist();
replacedertWebAppConfigTestCase();
}
/**
* @since 4.3
*/
@Test
void activateListenerWithoutExistingRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(NoAtWebAppConfigWebTestCase.clreplaced);
given(testContext.getAttribute(ServletTestExecutionListener.ACTIVATE_LISTENER)).willReturn(true);
RequestContextHolder.resetRequestAttributes();
listener.beforeTestClreplaced(testContext);
replacedertRequestAttributesDoNotExist();
replacedertWebAppConfigTestCase();
}
private RequestAttributes replacedertRequestAttributesExist() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
replacedertThat(requestAttributes).as("request attributes should exist").isNotNull();
return requestAttributes;
}
private void replacedertRequestAttributesDoNotExist() {
replacedertThat(RequestContextHolder.getRequestAttributes()).as("request attributes should not exist").isNull();
}
private void replacedertSetUpOutsideOfStelAttributeExists() {
RequestAttributes requestAttributes = replacedertRequestAttributesExist();
Object setUpOutsideOfStel = requestAttributes.getAttribute(SET_UP_OUTSIDE_OF_STEL, RequestAttributes.SCOPE_REQUEST);
replacedertThat(setUpOutsideOfStel).as(SET_UP_OUTSIDE_OF_STEL + " should exist as a request attribute").isNotNull();
}
private void replacedertSetUpOutsideOfStelAttributeDoesNotExist() {
RequestAttributes requestAttributes = replacedertRequestAttributesExist();
Object setUpOutsideOfStel = requestAttributes.getAttribute(SET_UP_OUTSIDE_OF_STEL, RequestAttributes.SCOPE_REQUEST);
replacedertThat(setUpOutsideOfStel).as(SET_UP_OUTSIDE_OF_STEL + " should NOT exist as a request attribute").isNull();
}
private void replacedertWebAppConfigTestCase() throws Exception {
listener.prepareTestInstance(testContext);
replacedertRequestAttributesExist();
replacedertSetUpOutsideOfStelAttributeDoesNotExist();
verify(testContext, times(1)).setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
verify(testContext, times(1)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(Boolean.TRUE);
listener.beforeTestMethod(testContext);
replacedertRequestAttributesExist();
replacedertSetUpOutsideOfStelAttributeDoesNotExist();
verify(testContext, times(1)).setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
verify(testContext, times(1)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
listener.afterTestMethod(testContext);
verify(testContext).removeAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
verify(testContext).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
replacedertRequestAttributesDoNotExist();
}
static clreplaced LegacyWebTestCase {
}
@WebAppConfiguration
static clreplaced AtWebAppConfigWebTestCase {
}
static clreplaced NoAtWebAppConfigWebTestCase {
}
}
17
View Source File : DefaultMockMvcBuilderTests.java
License : MIT License
Project Creator : mindcarver
License : MIT License
Project Creator : mindcarver
/**
* Tests for {@link DefaultMockMvcBuilder}.
*
* @author Rob Winch
* @author Sebastien Deleuze
* @author Sam Brannen
* @author Stephane Nicoll
*/
public clreplaced DefaultMockMvcBuilderTests {
private final MockServletContext servletContext = new MockServletContext();
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void webAppContextSetupWithNullWac() {
exception.expect(IllegalArgumentException.clreplaced);
exception.expectMessage(equalTo("WebApplicationContext is required"));
webAppContextSetup(null);
}
@Test
public void webAppContextSetupWithNullServletContext() {
exception.expect(IllegalArgumentException.clreplaced);
exception.expectMessage(equalTo("WebApplicationContext must have a ServletContext"));
webAppContextSetup(new StubWebApplicationContext(null));
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributePreviouslySet() {
StubWebApplicationContext child = new StubWebApplicationContext(this.servletContext);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, child);
DefaultMockMvcBuilder builder = webAppContextSetup(child);
replacedertSame(builder.initWebAppContext(), WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributePreviouslySetWithContextHierarchy() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, root);
StaticWebApplicationContext child = new StaticWebApplicationContext();
child.setParent(root);
child.setServletContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(child);
replacedertSame(builder.initWebAppContext().getParent(), WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributeNotPreviouslySet() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
WebApplicationContext wac = builder.initWebAppContext();
replacedertSame(root, wac);
replacedertSame(root, WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributeNotPreviouslySetWithContextHierarchy() {
StaticApplicationContext ear = new StaticApplicationContext();
StaticWebApplicationContext root = new StaticWebApplicationContext();
root.setParent(ear);
root.setServletContext(this.servletContext);
StaticWebApplicationContext dispatcher = new StaticWebApplicationContext();
dispatcher.setParent(root);
dispatcher.setServletContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(dispatcher);
WebApplicationContext wac = builder.initWebAppContext();
replacedertSame(dispatcher, wac);
replacedertSame(root, wac.getParent());
replacedertSame(ear, wac.getParent().getParent());
replacedertSame(root, WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See /SPR-14277
*/
@Test
public void dispatcherServletCustomizer() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("test-id"));
builder.dispatchOptions(true);
MockMvc mvc = builder.build();
DispatcherServlet ds = (DispatcherServlet) new DirectFieldAccessor(mvc).getPropertyValue("servlet");
replacedertEquals("test-id", ds.getContextId());
}
@Test
public void dispatcherServletCustomizerProcessedInOrder() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("test-id"));
builder.addDispatcherServletCustomizer(ds -> ds.setContextId("override-id"));
builder.dispatchOptions(true);
MockMvc mvc = builder.build();
DispatcherServlet ds = (DispatcherServlet) new DirectFieldAccessor(mvc).getPropertyValue("servlet");
replacedertEquals("override-id", ds.getContextId());
}
}
17
View Source File : DefaultMockMvcBuilderTests.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* Tests for {@link DefaultMockMvcBuilder}.
*
* @author Rob Winch
* @author Sebastien Deleuze
* @author Sam Brannen
*/
public clreplaced DefaultMockMvcBuilderTests {
private final MockServletContext servletContext = new MockServletContext();
@Rule
public final ExpectedException exception = ExpectedException.none();
@Test
public void webAppContextSetupWithNullWac() {
exception.expect(IllegalArgumentException.clreplaced);
exception.expectMessage(equalTo("WebApplicationContext is required"));
webAppContextSetup(null);
}
@Test
public void webAppContextSetupWithNullServletContext() {
exception.expect(IllegalArgumentException.clreplaced);
exception.expectMessage(equalTo("WebApplicationContext must have a ServletContext"));
webAppContextSetup(new StubWebApplicationContext(null));
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributePreviouslySet() {
StubWebApplicationContext child = new StubWebApplicationContext(this.servletContext);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, child);
DefaultMockMvcBuilder builder = webAppContextSetup(child);
replacedertSame(builder.initWebAppContext(), WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributePreviouslySetWithContextHierarchy() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, root);
StaticWebApplicationContext child = new StaticWebApplicationContext();
child.setParent(root);
child.setServletContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(child);
replacedertSame(builder.initWebAppContext().getParent(), WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributeNotPreviouslySet() {
StubWebApplicationContext root = new StubWebApplicationContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(root);
WebApplicationContext wac = builder.initWebAppContext();
replacedertSame(root, wac);
replacedertSame(root, WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
/**
* See SPR-12553 and SPR-13075.
*/
@Test
public void rootWacServletContainerAttributeNotPreviouslySetWithContextHierarchy() {
StaticApplicationContext ear = new StaticApplicationContext();
StaticWebApplicationContext root = new StaticWebApplicationContext();
root.setParent(ear);
root.setServletContext(this.servletContext);
StaticWebApplicationContext dispatcher = new StaticWebApplicationContext();
dispatcher.setParent(root);
dispatcher.setServletContext(this.servletContext);
DefaultMockMvcBuilder builder = webAppContextSetup(dispatcher);
WebApplicationContext wac = builder.initWebAppContext();
replacedertSame(dispatcher, wac);
replacedertSame(root, wac.getParent());
replacedertSame(ear, wac.getParent().getParent());
replacedertSame(root, WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext));
}
}
17
View Source File : WebMvcUtilsTest.java
License : GNU General Public License v3.0
Project Creator : alibaba
License : GNU General Public License v3.0
Project Creator : alibaba
/**
* {@link WebMvcUtils} Test
*
* @author <a href="mailto:[email protected]">Mercy</a>
* @see WebMvcUtils
* @since 2017.01.13
*/
@ControllerAdvice
public clreplaced WebMvcUtilsTest {
private MockServletContext servletContext;
private MockHttpServletRequest request;
@Before
public void init() {
servletContext = new MockServletContext();
request = new MockHttpServletRequest(servletContext);
RequestContextHolder.resetRequestAttributes();
}
@Test
public void testIsControllerAdviceBeanType() {
replacedert.replacedertFalse(WebMvcUtils.isControllerAdviceBeanType(WebMvcUtils.clreplaced));
replacedert.replacedertTrue(WebMvcUtils.isControllerAdviceBeanType(WebMvcUtilsTest.clreplaced));
}
@Test
public void testCurrentRequest() {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
HttpServletRequest httpServletRequest = WebMvcUtils.currentRequest();
replacedert.replacedertEquals(request, httpServletRequest);
}
@Test(expected = IllegalStateException.clreplaced)
public void testCurrentRequestWithoutRequestAttributes() {
WebMvcUtils.currentRequest();
}
@Test(expected = IllegalStateException.clreplaced)
public void testCurrentRequestInNotServletContainer() {
RequestContextHolder.setRequestAttributes(new RequestAttributes() {
@Override
public Object getAttribute(String name, int scope) {
return null;
}
@Override
public void setAttribute(String name, Object value, int scope) {
}
@Override
public void removeAttribute(String name, int scope) {
}
@Override
public String[] getAttributeNames(int scope) {
return new String[0];
}
@Override
public void registerDestructionCallback(String name, Runnable callback, int scope) {
}
@Override
public Object resolveReference(String key) {
return null;
}
@Override
public String getSessionId() {
return null;
}
@Override
public Object getSessionMutex() {
return null;
}
});
WebMvcUtils.currentRequest();
}
@Test
public void testCurrentServletContext() {
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
ServletContext servletContext = WebMvcUtils.currentServletContext();
replacedert.replacedertNotNull(servletContext);
request = new MockHttpServletRequest(new MockServletContext());
requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
servletContext = WebMvcUtils.currentServletContext();
replacedert.replacedertNotNull(servletContext);
}
@Test
public void testAppendInitParameter() {
String parameterValue = WebMvcUtils.appendInitParameter("value1");
replacedert.replacedertEquals("value1", parameterValue);
parameterValue = WebMvcUtils.appendInitParameter("value1", "value2");
replacedert.replacedertEquals("value1,value2", parameterValue);
}
@Test
public void testAppendInitParameters() {
MockServletContext servletContext = new MockServletContext();
String parameterName = "name";
String parameterValue = "value";
replacedert.replacedertNull(servletContext.getInitParameter(parameterName));
WebMvcUtils.appendInitParameters(servletContext, parameterName);
replacedert.replacedertNull(servletContext.getInitParameter(parameterName));
WebMvcUtils.appendInitParameters(servletContext, parameterName, parameterValue, parameterValue);
replacedert.replacedertEquals("value,value", servletContext.getInitParameter(parameterName));
}
@Test
public void testAppendGlobalInitializerClreplacedInitParameter() {
MockServletContext servletContext = new MockServletContext();
WebMvcUtils.appendGlobalInitializerClreplacedInitParameter(servletContext, ApplicationContextInitializer.clreplaced);
replacedert.replacedertEquals(ApplicationContextInitializer.clreplaced.getName(), servletContext.getInitParameter(GLOBAL_INITIALIZER_CLreplacedES_PARAM));
}
@Test
public void testAppendContextInitializerClreplacedInitParameter() {
MockServletContext servletContext = new MockServletContext();
WebMvcUtils.appendContextInitializerClreplacedInitParameter(servletContext, ApplicationContextInitializer.clreplaced);
replacedert.replacedertEquals(ApplicationContextInitializer.clreplaced.getName(), servletContext.getInitParameter(CONTEXT_INITIALIZER_CLreplacedES_PARAM));
}
// @Test
// public void testAppendFrameworkServletContextInitializerClreplacedInitParameter() {
//
// MockServletContext servletContext = new MockServletContext();
//
// WebMvcUtils.appendFrameworkServletContextInitializerClreplacedInitParameter(servletContext, ApplicationContextInitializer.clreplaced);
//
// replacedert.replacedertEquals(ApplicationContextInitializer.clreplaced.getName(),
// servletContext.getInitParameter(GLOBAL_INITIALIZER_CLreplacedES_PARAM));
//
// }
@Test
public void testIsPageRenderRequest() {
replacedert.replacedertFalse(WebMvcUtils.isPageRenderRequest(null));
ModelAndView modelAndView = new ModelAndView();
replacedert.replacedertFalse(WebMvcUtils.isPageRenderRequest(modelAndView));
modelAndView.setViewName("hello");
replacedert.replacedertTrue(WebMvcUtils.isPageRenderRequest(modelAndView));
}
@Test(expected = IllegalStateException.clreplaced)
public void testGetWebApplicationContextWithoutServletContext() {
WebMvcUtils.getWebApplicationContext(request, null);
}
@Test(expected = IllegalStateException.clreplaced)
public void testGetWebApplicationContextWithoutWebApplicationContext() {
WebMvcUtils.getWebApplicationContext(request, servletContext);
}
@Test
public void testGetWebApplicationContext() {
WebApplicationContext webApplicationContext = new GenericWebApplicationContext();
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
WebApplicationContext applicationContext = WebMvcUtils.getWebApplicationContext(request, servletContext);
replacedert.replacedertEquals(webApplicationContext, applicationContext);
applicationContext = WebMvcUtils.getWebApplicationContext(request);
replacedert.replacedertEquals(webApplicationContext, applicationContext);
}
@Test
public void testCurrentWebApplicationContext() {
WebApplicationContext webApplicationContext = new GenericWebApplicationContext();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
servletContext.setAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
WebApplicationContext applicationContext = WebMvcUtils.currentWebApplicationContext();
replacedert.replacedertEquals(webApplicationContext, applicationContext);
}
@Test
public void testGetRequestMappingHandlerMapping() {
AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
servletContext.setAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
webApplicationContext.setServletContext(servletContext);
webApplicationContext.register(TestController.clreplaced);
webApplicationContext.register(DelegatingWebMvcConfiguration.clreplaced);
webApplicationContext.register(TestWebMvcConfigurer.clreplaced);
webApplicationContext.refresh();
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
RequestMappingHandlerMapping requestMappingHandlerMapping = WebMvcUtils.getRequestMappingHandlerMapping(request, servletContext);
replacedert.replacedertNotNull(requestMappingHandlerMapping);
replacedert.replacedertFalse(requestMappingHandlerMapping.getHandlerMethods().isEmpty());
requestMappingHandlerMapping = WebMvcUtils.getRequestMappingHandlerMapping(request);
replacedert.replacedertNotNull(requestMappingHandlerMapping);
replacedert.replacedertFalse(requestMappingHandlerMapping.getHandlerMethods().isEmpty());
}
}
17
View Source File : WebMvcUtilsTest.java
License : GNU General Public License v3.0
Project Creator : alibaba
License : GNU General Public License v3.0
Project Creator : alibaba
@Test
public void testAppendInitParameters() {
MockServletContext servletContext = new MockServletContext();
String parameterName = "name";
String parameterValue = "value";
replacedert.replacedertNull(servletContext.getInitParameter(parameterName));
WebMvcUtils.appendInitParameters(servletContext, parameterName);
replacedert.replacedertNull(servletContext.getInitParameter(parameterName));
WebMvcUtils.appendInitParameters(servletContext, parameterName, parameterValue, parameterValue);
replacedert.replacedertEquals("value,value", servletContext.getInitParameter(parameterName));
}
17
View Source File : HandlerMethodResolverTest.java
License : GNU General Public License v3.0
Project Creator : alibaba
License : GNU General Public License v3.0
Project Creator : alibaba
/**
* {@link HandlerMethodResolver}
*
* @author <a href="mailto:[email protected]">Mercy</a>
* @see HandlerMethodResolver
* @since 2017.02.02
*/
public clreplaced HandlerMethodResolverTest {
private HandlerMethodResolver handlerMethodResolver;
private MockServletContext servletContext;
private MockHttpServletRequest request;
private AnnotationConfigWebApplicationContext webApplicationContext;
@Before
public void init() {
handlerMethodResolver = new HandlerMethodResolver();
servletContext = new MockServletContext();
request = new MockHttpServletRequest(servletContext);
webApplicationContext = new AnnotationConfigWebApplicationContext();
webApplicationContext.setServletContext(servletContext);
request.setAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
servletContext.setAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, webApplicationContext);
webApplicationContext.register(TestController.clreplaced);
webApplicationContext.register(DelegatingWebMvcConfiguration.clreplaced);
webApplicationContext.register(TestWebMvcConfigurer.clreplaced);
webApplicationContext.refresh();
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request), true);
}
@After
public void destroy() {
webApplicationContext.destroy();
request.removeAttribute(WEB_APPLICATION_CONTEXT_ATTRIBUTE);
servletContext.removeAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
RequestContextHolder.resetRequestAttributes();
}
@Test
public void testResolveHandlerMethods() {
Collection<HandlerMethod> handlerMethods = handlerMethodResolver.resolveHandlerMethods(request, servletContext);
replacedert.replacedertEquals(1, handlerMethods.size());
handlerMethods = handlerMethodResolver.resolveHandlerMethods(request);
replacedert.replacedertEquals(1, handlerMethods.size());
}
@Test
public void testResolveHandlerMethod() {
HandlerMethod handlerMethod = handlerMethodResolver.resolveHandlerMethod(request, servletContext);
replacedert.replacedertNull(handlerMethod);
request.setRequestURI("/echo");
handlerMethod = handlerMethodResolver.resolveHandlerMethod(request, servletContext);
replacedert.replacedertNotNull(handlerMethod);
Method method = handlerMethod.getMethod();
replacedert.replacedertEquals("echo", method.getName());
handlerMethod = handlerMethodResolver.resolveHandlerMethod(request);
replacedert.replacedertNotNull(handlerMethod);
method = handlerMethod.getMethod();
replacedert.replacedertEquals("echo", method.getName());
}
}
17
View Source File : ExclusiveViewResolverApplicationListenerTest.java
License : GNU General Public License v3.0
Project Creator : alibaba
License : GNU General Public License v3.0
Project Creator : alibaba
/**
* {@link ExclusiveViewResolverApplicationListener} Test
*
* @author <a href="mailto:[email protected]">Mercy</a>
* @see ExclusiveViewResolverApplicationListener
* @since 2017.03.23
*/
public clreplaced ExclusiveViewResolverApplicationListenerTest {
private AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
private ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
private MockServletContext servletContext = new MockServletContext();
private BeanNameViewResolver viewResolver = new BeanNameViewResolver();
@Before
public void init() {
applicationContext.setServletContext(servletContext);
applicationContext.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.registerSingleton("resolver", resolver);
beanFactory.registerSingleton("viewResolver", viewResolver);
}
});
}
@Component("test-view-resolver")
private static clreplaced TestViewResolver implements ViewResolver {
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
@Test(expected = NoSuchBeanDefinitionException.clreplaced)
public void testOnApplicationContextOnNoSuchBeanDefinitionException() {
// Register ViewResolver Beans
applicationContext.register(ContentNegotiatingViewResolver.clreplaced);
ApplicationListener<ContextRefreshedEvent> applicationListener = new ExclusiveViewResolverApplicationListener("not-existed-view-resolver");
applicationContext.addApplicationListener(applicationListener);
applicationContext.refresh();
}
@Test
public void testOnApplicationContext() {
// Register ViewResolver Beans
applicationContext.register(TestViewResolver.clreplaced);
ApplicationListener<ContextRefreshedEvent> applicationListener = new ExclusiveViewResolverApplicationListener("test-view-resolver");
applicationContext.addApplicationListener(applicationListener);
applicationContext.refresh();
List<ViewResolver> viewResolvers = FieldUtils.getFieldValue(resolver, "viewResolvers");
replacedert.replacedertEquals(1, viewResolvers.size());
replacedert.replacedertEquals(TestViewResolver.clreplaced, viewResolvers.get(0).getClreplaced());
}
}
16
View Source File : MustacheViewTests.java
License : Apache License 2.0
Project Creator : yuanmabiji
License : Apache License 2.0
Project Creator : yuanmabiji
@Before
public void init() {
this.context.refresh();
MockServletContext servletContext = new MockServletContext();
this.context.setServletContext(servletContext);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
}
16
View Source File : MetaAnnotationConfigWacTests.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* Integration test that verifies meta-annotation support for {@link WebAppConfiguration}
* and {@link ContextConfiguration}.
*
* @author Sam Brannen
* @since 4.0
* @see WebTestConfiguration
*/
@RunWith(SpringJUnit4ClreplacedRunner.clreplaced)
@WebTestConfiguration
public clreplaced MetaAnnotationConfigWacTests {
@Autowired
protected WebApplicationContext wac;
@Autowired
protected MockServletContext mockServletContext;
@Autowired
protected String foo;
@Test
public void fooEnigmaAutowired() {
replacedertEquals("enigma", foo);
}
@Test
public void basicWacFeatures() throws Exception {
replacedertNotNull("ServletContext should be set in the WAC.", wac.getServletContext());
replacedertNotNull("ServletContext should have been autowired from the WAC.", mockServletContext);
Object rootWac = mockServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
replacedertNotNull("Root WAC must be stored in the ServletContext as: " + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, rootWac);
replacedertSame("test WAC and Root WAC in ServletContext must be the same object.", wac, rootWac);
replacedertSame("ServletContext instances must be the same object.", mockServletContext, wac.getServletContext());
replacedertEquals("Getting real path for ServletContext resource.", new File("src/main/webapp/index.jsp").getCanonicalPath(), mockServletContext.getRealPath("index.jsp"));
}
}
16
View Source File : StandaloneMockMvcBuilder.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
@Override
protected WebApplicationContext initWebAppContext() {
MockServletContext servletContext = new MockServletContext();
StubWebApplicationContext wac = new StubWebApplicationContext(servletContext);
registerMvcSingletons(wac);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
return wac;
}
16
View Source File : StaticResourcesWebConfigurerTest.java
License : MIT License
Project Creator : tillias
License : MIT License
Project Creator : tillias
public clreplaced StaticResourcesWebConfigurerTest {
public static final int MAX_AGE_TEST = 5;
public StaticResourcesWebConfiguration staticResourcesWebConfiguration;
private ResourceHandlerRegistry resourceHandlerRegistry;
private MockServletContext servletContext;
private WebApplicationContext applicationContext;
private JHipsterProperties props;
@BeforeEach
void setUp() {
servletContext = spy(new MockServletContext());
applicationContext = mock(WebApplicationContext.clreplaced);
resourceHandlerRegistry = spy(new ResourceHandlerRegistry(applicationContext, servletContext));
props = new JHipsterProperties();
staticResourcesWebConfiguration = spy(new StaticResourcesWebConfiguration(props));
}
@Test
public void shouldAppendResourceHandlerAndInitiliazeIt() {
staticResourcesWebConfiguration.addResourceHandlers(resourceHandlerRegistry);
verify(resourceHandlerRegistry, times(1)).addResourceHandler(RESOURCE_PATHS);
verify(staticResourcesWebConfiguration, times(1)).initializeResourceHandler(any(ResourceHandlerRegistration.clreplaced));
for (String testingPath : RESOURCE_PATHS) {
replacedertThat(resourceHandlerRegistry.hasMappingForPattern(testingPath)).isTrue();
}
}
@Test
public void shouldInitializeResourceHandlerWithCacheControlAndLocations() {
CacheControl ccExpected = CacheControl.maxAge(5, TimeUnit.DAYS).cachePublic();
when(staticResourcesWebConfiguration.getCacheControl()).thenReturn(ccExpected);
ResourceHandlerRegistration resourceHandlerRegistration = spy(new ResourceHandlerRegistration(RESOURCE_PATHS));
staticResourcesWebConfiguration.initializeResourceHandler(resourceHandlerRegistration);
verify(staticResourcesWebConfiguration, times(1)).getCacheControl();
verify(resourceHandlerRegistration, times(1)).setCacheControl(ccExpected);
verify(resourceHandlerRegistration, times(1)).addResourceLocations(RESOURCE_LOCATIONS);
}
@Test
public void shoudCreateCacheControlBasedOnJhipsterDefaultProperties() {
CacheControl cacheExpected = CacheControl.maxAge(JHipsterDefaults.Http.Cache.timeToLiveInDays, TimeUnit.DAYS).cachePublic();
replacedertThat(staticResourcesWebConfiguration.getCacheControl()).extracting(CacheControl::getHeaderValue).isEqualTo(cacheExpected.getHeaderValue());
}
@Test
public void shoudCreateCacheControlWithSpecificConfigurationInProperties() {
props.getHttp().getCache().setTimeToLiveInDays(MAX_AGE_TEST);
CacheControl cacheExpected = CacheControl.maxAge(MAX_AGE_TEST, TimeUnit.DAYS).cachePublic();
replacedertThat(staticResourcesWebConfiguration.getCacheControl()).extracting(CacheControl::getHeaderValue).isEqualTo(cacheExpected.getHeaderValue());
}
}
16
View Source File : MetaAnnotationConfigWacTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* Integration test that verifies meta-annotation support for {@link WebAppConfiguration}
* and {@link ContextConfiguration}.
*
* @author Sam Brannen
* @since 4.0
* @see WebTestConfiguration
*/
@ExtendWith(SpringExtension.clreplaced)
@WebTestConfiguration
clreplaced MetaAnnotationConfigWacTests {
@Autowired
WebApplicationContext wac;
@Autowired
MockServletContext mockServletContext;
@Autowired
String foo;
@Test
void fooEnigmaAutowired() {
replacedertThat(foo).isEqualTo("enigma");
}
@Test
void basicWacFeatures() throws Exception {
replacedertThat(wac.getServletContext()).as("ServletContext should be set in the WAC.").isNotNull();
replacedertThat(mockServletContext).as("ServletContext should have been autowired from the WAC.").isNotNull();
Object rootWac = mockServletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
replacedertThat(rootWac).as("Root WAC must be stored in the ServletContext as: " + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE).isNotNull();
replacedertThat(rootWac).as("test WAC and Root WAC in ServletContext must be the same object.").isSameAs(wac);
replacedertThat(wac.getServletContext()).as("ServletContext instances must be the same object.").isSameAs(mockServletContext);
replacedertThat(mockServletContext.getRealPath("index.jsp")).as("Getting real path for ServletContext resource.").isEqualTo(new File("src/main/webapp/index.jsp").getCanonicalPath());
}
}
16
View Source File : ServletTestExecutionListenerTests.java
License : Apache License 2.0
Project Creator : langtianya
License : Apache License 2.0
Project Creator : langtianya
/**
* Unit tests for {@link ServletTestExecutionListener}.
*
* @author Sam Brannen
* @since 3.2.6
*/
public clreplaced ServletTestExecutionListenerTests {
private static final String SET_UP_OUTSIDE_OF_STEL = "SET_UP_OUTSIDE_OF_STEL";
private final WebApplicationContext wac = mock(WebApplicationContext.clreplaced);
private final MockServletContext mockServletContext = new MockServletContext();
private final TestContext testContext = mock(TestContext.clreplaced);
private final ServletTestExecutionListener listener = new ServletTestExecutionListener();
private void replacedertAttributesAvailable() {
replacedertNotNull("request attributes should be available", RequestContextHolder.getRequestAttributes());
}
private void replacedertAttributesNotAvailable() {
replacedertNull("request attributes should not be available", RequestContextHolder.getRequestAttributes());
}
private void replacedertAttributeExists() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
replacedertNotNull("request attributes should exist", requestAttributes);
Object setUpOutsideOfStel = requestAttributes.getAttribute(SET_UP_OUTSIDE_OF_STEL, RequestAttributes.SCOPE_REQUEST);
replacedertNotNull(SET_UP_OUTSIDE_OF_STEL + " should exist as a request attribute", setUpOutsideOfStel);
}
private void replacedertAttributeDoesNotExist() {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
replacedertNotNull("request attributes should exist", requestAttributes);
Object setUpOutsideOfStel = requestAttributes.getAttribute(SET_UP_OUTSIDE_OF_STEL, RequestAttributes.SCOPE_REQUEST);
replacedertNull(SET_UP_OUTSIDE_OF_STEL + " should NOT exist as a request attribute", setUpOutsideOfStel);
}
@Before
public void setUp() {
given(wac.getServletContext()).willReturn(mockServletContext);
given(testContext.getApplicationContext()).willReturn(wac);
MockHttpServletRequest request = new MockHttpServletRequest(mockServletContext);
MockHttpServletResponse response = new MockHttpServletResponse();
ServletWebRequest servletWebRequest = new ServletWebRequest(request, response);
request.setAttribute(SET_UP_OUTSIDE_OF_STEL, "true");
RequestContextHolder.setRequestAttributes(servletWebRequest);
replacedertAttributeExists();
}
@Test
public void standardApplicationContext() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(getClreplaced());
given(testContext.getApplicationContext()).willReturn(mock(ApplicationContext.clreplaced));
listener.beforeTestClreplaced(testContext);
replacedertAttributeExists();
listener.prepareTestInstance(testContext);
replacedertAttributeExists();
listener.beforeTestMethod(testContext);
replacedertAttributeExists();
listener.afterTestMethod(testContext);
replacedertAttributeExists();
}
@Test
public void legacyWebTestCaseWithoutExistingRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(LegacyWebTestCase.clreplaced);
RequestContextHolder.resetRequestAttributes();
replacedertAttributesNotAvailable();
listener.beforeTestClreplaced(testContext);
listener.prepareTestInstance(testContext);
replacedertAttributesNotAvailable();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null);
listener.beforeTestMethod(testContext);
replacedertAttributesNotAvailable();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
listener.afterTestMethod(testContext);
verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
replacedertAttributesNotAvailable();
}
@Test
public void legacyWebTestCaseWithPresetRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(LegacyWebTestCase.clreplaced);
listener.beforeTestClreplaced(testContext);
replacedertAttributeExists();
listener.prepareTestInstance(testContext);
replacedertAttributeExists();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null);
listener.beforeTestMethod(testContext);
replacedertAttributeExists();
verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null);
listener.afterTestMethod(testContext);
verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
replacedertAttributeExists();
}
@Test
public void atWebAppConfigTestCaseWithoutExistingRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(AtWebAppConfigWebTestCase.clreplaced);
RequestContextHolder.resetRequestAttributes();
listener.beforeTestClreplaced(testContext);
replacedertAttributesNotAvailable();
replacedertWebAppConfigTestCase();
}
@Test
public void atWebAppConfigTestCaseWithPresetRequestAttributes() throws Exception {
BDDMockito.<Clreplaced<?>>given(testContext.getTestClreplaced()).willReturn(AtWebAppConfigWebTestCase.clreplaced);
listener.beforeTestClreplaced(testContext);
replacedertAttributesAvailable();
replacedertWebAppConfigTestCase();
}
private void replacedertWebAppConfigTestCase() throws Exception {
listener.prepareTestInstance(testContext);
replacedertAttributeDoesNotExist();
verify(testContext, times(1)).setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
verify(testContext, times(1)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
given(testContext.getAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(Boolean.TRUE);
given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(Boolean.TRUE);
listener.beforeTestMethod(testContext);
replacedertAttributeDoesNotExist();
verify(testContext, times(1)).setAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
verify(testContext, times(1)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE);
listener.afterTestMethod(testContext);
verify(testContext).removeAttribute(POPULATED_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
verify(testContext).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE);
replacedertAttributesNotAvailable();
}
static clreplaced LegacyWebTestCase {
}
@WebAppConfiguration
static clreplaced AtWebAppConfigWebTestCase {
}
}
16
View Source File : WebUtilsTest.java
License : GNU General Public License v3.0
Project Creator : alibaba
License : GNU General Public License v3.0
Project Creator : alibaba
@Test
public void testGetServletContext() {
MockServletContext servletContext = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
replacedert.replacedertEquals(servletContext, WebUtils.getServletContext(request));
}
See More Examples