-
Notifications
You must be signed in to change notification settings - Fork 40.1k
/
SpringBootServletInitializerTests.java
335 lines (274 loc) · 11.7 KB
/
SpringBootServletInitializerTests.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.web.servlet.support;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.logging.LoggingApplicationListener;
import org.springframework.boot.testsupport.system.CapturedOutput;
import org.springframework.boot.testsupport.system.OutputCaptureExtension;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.env.PropertySource;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StandardServletEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* Tests for {@link SpringBootServletInitializer}.
*
* @author Phillip Webb
* @author Andy Wilkinson
*/
@ExtendWith(OutputCaptureExtension.class)
class SpringBootServletInitializerTests {
private ServletContext servletContext = new MockServletContext();
private SpringApplication application;
@AfterEach
void verifyLoggingOutput(CapturedOutput output) {
assertThat(output).doesNotContain(StandardServletEnvironment.class.getSimpleName());
}
@Test
void failsWithoutConfigure() {
assertThatIllegalStateException()
.isThrownBy(
() -> new MockSpringBootServletInitializer().createRootApplicationContext(this.servletContext))
.withMessageContaining("No SpringApplication sources have been defined");
}
@Test
void withConfigurationAnnotation() {
new WithConfigurationAnnotation().createRootApplicationContext(this.servletContext);
assertThat(this.application.getAllSources()).containsOnly(WithConfigurationAnnotation.class,
ErrorPageFilterConfiguration.class);
}
@Test
void withConfiguredSource() {
new WithConfiguredSource().createRootApplicationContext(this.servletContext);
assertThat(this.application.getAllSources()).containsOnly(Config.class, ErrorPageFilterConfiguration.class);
}
@Test
void applicationBuilderCanBeCustomized() {
CustomSpringBootServletInitializer servletInitializer = new CustomSpringBootServletInitializer();
servletInitializer.createRootApplicationContext(this.servletContext);
assertThat(servletInitializer.applicationBuilder.built).isTrue();
}
@Test
void mainClassHasSensibleDefault() {
new WithConfigurationAnnotation().createRootApplicationContext(this.servletContext);
assertThat(this.application).hasFieldOrPropertyWithValue("mainApplicationClass",
WithConfigurationAnnotation.class);
}
@Test
void shutdownHooksAreNotRegistered() throws ServletException {
new WithConfigurationAnnotation().onStartup(this.servletContext);
assertThat(this.servletContext.getAttribute(LoggingApplicationListener.REGISTER_SHUTDOWN_HOOK_PROPERTY))
.isEqualTo(false);
assertThat(this.application).hasFieldOrPropertyWithValue("registerShutdownHook", false);
}
@Test
void errorPageFilterRegistrationCanBeDisabled() {
WebServer webServer = new UndertowServletWebServerFactory(0).getWebServer((servletContext) -> {
try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilterNotRegistered()
.createRootApplicationContext(servletContext)) {
assertThat(context.getBeansOfType(ErrorPageFilter.class)).hasSize(0);
}
});
try {
webServer.start();
}
finally {
webServer.stop();
}
}
@Test
@SuppressWarnings("rawtypes")
void errorPageFilterIsRegisteredWithNearHighestPrecedence() {
WebServer webServer = new UndertowServletWebServerFactory(0).getWebServer((servletContext) -> {
try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilter()
.createRootApplicationContext(servletContext)) {
Map<String, FilterRegistrationBean> registrations = context
.getBeansOfType(FilterRegistrationBean.class);
assertThat(registrations).hasSize(1);
FilterRegistrationBean errorPageFilterRegistration = registrations.get("errorPageFilterRegistration");
assertThat(errorPageFilterRegistration.getOrder()).isEqualTo(Ordered.HIGHEST_PRECEDENCE + 1);
}
});
try {
webServer.start();
}
finally {
webServer.stop();
}
}
@Test
@SuppressWarnings("rawtypes")
void errorPageFilterIsRegisteredForRequestAndAsyncDispatch() {
WebServer webServer = new UndertowServletWebServerFactory(0).getWebServer((servletContext) -> {
try (AbstractApplicationContext context = (AbstractApplicationContext) new WithErrorPageFilter()
.createRootApplicationContext(servletContext)) {
Map<String, FilterRegistrationBean> registrations = context
.getBeansOfType(FilterRegistrationBean.class);
assertThat(registrations).hasSize(1);
FilterRegistrationBean errorPageFilterRegistration = registrations.get("errorPageFilterRegistration");
assertThat(errorPageFilterRegistration).hasFieldOrPropertyWithValue("dispatcherTypes",
EnumSet.of(DispatcherType.ASYNC, DispatcherType.REQUEST));
}
});
try {
webServer.start();
}
finally {
webServer.stop();
}
}
@Test
void executableWarThatUsesServletInitializerDoesNotHaveErrorPageFilterConfigured() {
try (ConfigurableApplicationContext context = new SpringApplication(ExecutableWar.class).run()) {
assertThat(context.getBeansOfType(ErrorPageFilter.class)).hasSize(0);
}
}
@Test
void servletContextPropertySourceIsAvailablePriorToRefresh() {
ServletContext servletContext = mock(ServletContext.class);
given(servletContext.getInitParameterNames())
.willReturn(Collections.enumeration(Collections.singletonList("spring.profiles.active")));
given(servletContext.getInitParameter("spring.profiles.active")).willReturn("from-servlet-context");
given(servletContext.getAttributeNames()).willReturn(Collections.emptyEnumeration());
try (ConfigurableApplicationContext context = (ConfigurableApplicationContext) new PropertySourceVerifyingSpringBootServletInitializer()
.createRootApplicationContext(servletContext)) {
assertThat(context.getEnvironment().getActiveProfiles()).containsExactly("from-servlet-context");
}
}
@Test
void whenServletContextIsDestroyedThenJdbcDriversAreDeregistered() throws ServletException {
ServletContext servletContext = mock(ServletContext.class);
given(servletContext.getInitParameterNames()).willReturn(new Vector<String>().elements());
given(servletContext.getAttributeNames()).willReturn(new Vector<String>().elements());
AtomicBoolean driversDeregistered = new AtomicBoolean();
new SpringBootServletInitializer() {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(Config.class);
}
@Override
protected void deregisterJdbcDrivers(ServletContext servletContext) {
driversDeregistered.set(true);
}
}.onStartup(servletContext);
ArgumentCaptor<ServletContextListener> captor = ArgumentCaptor.forClass(ServletContextListener.class);
verify(servletContext).addListener(captor.capture());
captor.getValue().contextDestroyed(new ServletContextEvent(servletContext));
assertThat(driversDeregistered).isTrue();
}
static class PropertySourceVerifyingSpringBootServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(TestApp.class).listeners(new PropertySourceVerifyingApplicationListener());
}
}
@Configuration(proxyBeanMethods = false)
static class TestApp {
}
private class MockSpringBootServletInitializer extends SpringBootServletInitializer {
@Override
protected WebApplicationContext run(SpringApplication application) {
SpringBootServletInitializerTests.this.application = application;
return null;
}
}
private class CustomSpringBootServletInitializer extends MockSpringBootServletInitializer {
private final CustomSpringApplicationBuilder applicationBuilder = new CustomSpringApplicationBuilder();
@Override
protected SpringApplicationBuilder createSpringApplicationBuilder() {
return this.applicationBuilder;
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Config.class);
}
}
@Configuration(proxyBeanMethods = false)
public class WithConfigurationAnnotation extends MockSpringBootServletInitializer {
}
public class WithConfiguredSource extends MockSpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Config.class);
}
}
@Configuration(proxyBeanMethods = false)
static class WithErrorPageFilterNotRegistered extends SpringBootServletInitializer {
WithErrorPageFilterNotRegistered() {
setRegisterErrorPageFilter(false);
}
}
@Configuration(proxyBeanMethods = false)
static class WithErrorPageFilter extends SpringBootServletInitializer {
}
@Configuration(proxyBeanMethods = false)
static class ExecutableWar extends SpringBootServletInitializer {
@Bean
ServletWebServerFactory webServerFactory() {
return new UndertowServletWebServerFactory(0);
}
}
@Configuration(proxyBeanMethods = false)
static class Config {
}
static class CustomSpringApplicationBuilder extends SpringApplicationBuilder {
private boolean built;
@Override
public SpringApplication build() {
this.built = true;
return super.build();
}
}
private static final class PropertySourceVerifyingApplicationListener
implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
PropertySource<?> propertySource = event.getEnvironment().getPropertySources()
.get(StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME);
assertThat(propertySource.getProperty("spring.profiles.active")).isEqualTo("from-servlet-context");
}
}
}