Skip to content

Commit 4119ef5

Browse files
author
Phillip Webb
committed
Use random ports for tests
Update remaining tests to use random ports. Fixes gh-337
1 parent af33cc2 commit 4119ef5

File tree

10 files changed

+122
-53
lines changed

10 files changed

+122
-53
lines changed

spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/EndpointWebMvcAutoConfigurationTests.java

Lines changed: 65 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,15 @@
2222
import java.nio.charset.Charset;
2323

2424
import org.junit.After;
25+
import org.junit.Before;
2526
import org.junit.Test;
2627
import org.springframework.boot.actuate.endpoint.Endpoint;
2728
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint;
2829
import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration;
2930
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
3031
import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration;
3132
import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration;
33+
import org.springframework.boot.autoconfigure.web.ServerProperties;
3234
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
3335
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
3436
import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
@@ -45,6 +47,7 @@
4547
import org.springframework.http.client.ClientHttpResponse;
4648
import org.springframework.http.client.SimpleClientHttpRequestFactory;
4749
import org.springframework.stereotype.Controller;
50+
import org.springframework.util.SocketUtils;
4851
import org.springframework.util.StreamUtils;
4952
import org.springframework.web.bind.annotation.RequestMapping;
5053
import org.springframework.web.bind.annotation.ResponseBody;
@@ -55,14 +58,21 @@
5558

5659
/**
5760
* Tests for {@link EndpointWebMvcAutoConfiguration}.
58-
*
61+
*
5962
* @author Phillip Webb
6063
* @author Greg Turnquist
6164
*/
6265
public class EndpointWebMvcAutoConfigurationTests {
6366

6467
private final AnnotationConfigEmbeddedWebApplicationContext applicationContext = new AnnotationConfigEmbeddedWebApplicationContext();
6568

69+
private static ThreadLocal<Ports> ports = new ThreadLocal<Ports>();
70+
71+
@Before
72+
public void grabPorts() {
73+
ports.set(new Ports());
74+
}
75+
6676
@After
6777
public void close() {
6878
if (this.applicationContext != null) {
@@ -73,12 +83,13 @@ public void close() {
7383
@Test
7484
public void onSamePort() throws Exception {
7585
this.applicationContext.register(RootConfig.class, BaseConfiguration.class,
86+
ServerPortConfig.class,
7687
EndpointWebMvcAutoConfiguration.class);
7788
this.applicationContext.refresh();
78-
assertContent("/controller", 8080, "controlleroutput");
79-
assertContent("/endpoint", 8080, "endpointoutput");
80-
assertContent("/controller", 8081, null);
81-
assertContent("/endpoint", 8081, null);
89+
assertContent("/controller", ports.get().server, "controlleroutput");
90+
assertContent("/endpoint", ports.get().server, "endpointoutput");
91+
assertContent("/controller", ports.get().management, null);
92+
assertContent("/endpoint", ports.get().management, null);
8293
this.applicationContext.close();
8394
assertAllClosed();
8495
}
@@ -89,10 +100,10 @@ public void onDifferentPort() throws Exception {
89100
BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class,
90101
ErrorMvcAutoConfiguration.class);
91102
this.applicationContext.refresh();
92-
assertContent("/controller", 8080, "controlleroutput");
93-
assertContent("/endpoint", 8080, null);
94-
assertContent("/controller", 8081, null);
95-
assertContent("/endpoint", 8081, "endpointoutput");
103+
assertContent("/controller", ports.get().server, "controlleroutput");
104+
assertContent("/endpoint", ports.get().server, null);
105+
assertContent("/controller", ports.get().management, null);
106+
assertContent("/endpoint", ports.get().management, "endpointoutput");
96107
this.applicationContext.close();
97108
assertAllClosed();
98109
}
@@ -107,9 +118,9 @@ public void onRandomPort() throws Exception {
107118
this.applicationContext.addApplicationListener(grabManagementPort);
108119
this.applicationContext.refresh();
109120
int managementPort = grabManagementPort.getServletContainer().getPort();
110-
assertThat(managementPort, not(equalTo(8080)));
111-
assertContent("/controller", 8080, "controlleroutput");
112-
assertContent("/endpoint", 8080, null);
121+
assertThat(managementPort, not(equalTo(ports.get().server)));
122+
assertContent("/controller", ports.get().server, "controlleroutput");
123+
assertContent("/endpoint", ports.get().server, null);
113124
assertContent("/controller", managementPort, null);
114125
assertContent("/endpoint", managementPort, "endpointoutput");
115126
}
@@ -119,25 +130,25 @@ public void disabled() throws Exception {
119130
this.applicationContext.register(RootConfig.class, DisableConfig.class,
120131
BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class);
121132
this.applicationContext.refresh();
122-
assertContent("/controller", 8080, "controlleroutput");
123-
assertContent("/endpoint", 8080, null);
124-
assertContent("/controller", 8081, null);
125-
assertContent("/endpoint", 8081, null);
133+
assertContent("/controller", ports.get().server, "controlleroutput");
134+
assertContent("/endpoint", ports.get().server, null);
135+
assertContent("/controller", ports.get().management, null);
136+
assertContent("/endpoint", ports.get().management, null);
126137
this.applicationContext.close();
127138
assertAllClosed();
128139
}
129140

130141
@Test
131142
public void specificPortsViaProperties() throws Exception {
132-
EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:7070",
133-
"management.port:7071");
143+
EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:"
144+
+ ports.get().server, "management.port:" + ports.get().management);
134145
this.applicationContext.register(RootConfig.class, BaseConfiguration.class,
135146
EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class);
136147
this.applicationContext.refresh();
137-
assertContent("/controller", 7070, "controlleroutput");
138-
assertContent("/endpoint", 7070, null);
139-
assertContent("/controller", 7071, null);
140-
assertContent("/endpoint", 7071, "endpointoutput");
148+
assertContent("/controller", ports.get().server, "controlleroutput");
149+
assertContent("/endpoint", ports.get().server, null);
150+
assertContent("/controller", ports.get().management, null);
151+
assertContent("/endpoint", ports.get().management, "endpointoutput");
141152
this.applicationContext.close();
142153
assertAllClosed();
143154
}
@@ -146,7 +157,7 @@ public void specificPortsViaProperties() throws Exception {
146157
public void contextPath() throws Exception {
147158
EnvironmentTestUtils.addEnvironment(this.applicationContext,
148159
"management.contextPath:/test");
149-
this.applicationContext.register(RootConfig.class,
160+
this.applicationContext.register(RootConfig.class, ServerPortConfig.class,
150161
PropertyPlaceholderAutoConfiguration.class,
151162
ManagementServerPropertiesAutoConfiguration.class,
152163
ServerPropertiesAutoConfiguration.class,
@@ -155,17 +166,17 @@ public void contextPath() throws Exception {
155166
DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class,
156167
EndpointWebMvcAutoConfiguration.class);
157168
this.applicationContext.refresh();
158-
assertContent("/controller", 8080, "controlleroutput");
159-
assertContent("/test/endpoint", 8080, "endpointoutput");
169+
assertContent("/controller", ports.get().server, "controlleroutput");
170+
assertContent("/test/endpoint", ports.get().server, "endpointoutput");
160171
this.applicationContext.close();
161172
assertAllClosed();
162173
}
163174

164175
private void assertAllClosed() throws Exception {
165-
assertContent("/controller", 8080, null);
166-
assertContent("/endpoint", 8080, null);
167-
assertContent("/controller", 8081, null);
168-
assertContent("/endpoint", 8081, null);
176+
assertContent("/controller", ports.get().server, null);
177+
assertContent("/endpoint", ports.get().server, null);
178+
assertContent("/controller", ports.get().management, null);
179+
assertContent("/endpoint", ports.get().management, null);
169180
}
170181

171182
public void assertContent(String url, int port, Object expected) throws Exception {
@@ -194,6 +205,14 @@ public void assertContent(String url, int port, Object expected) throws Exceptio
194205
}
195206
}
196207

208+
private static class Ports {
209+
210+
int server = SocketUtils.findAvailableTcpPort();
211+
212+
int management = SocketUtils.findAvailableTcpPort();
213+
214+
}
215+
197216
@Configuration
198217
@Import({ PropertyPlaceholderAutoConfiguration.class,
199218
EmbeddedServletContainerAutoConfiguration.class,
@@ -217,6 +236,19 @@ public TestController testController() {
217236
public TestEndpoint testEndpoint() {
218237
return new TestEndpoint();
219238
}
239+
240+
}
241+
242+
@Configuration
243+
public static class ServerPortConfig {
244+
245+
@Bean
246+
public ServerProperties serverProperties() {
247+
ServerProperties properties = new ServerProperties();
248+
properties.setPort(ports.get().server);
249+
return properties;
250+
}
251+
220252
}
221253

222254
@Controller
@@ -231,18 +263,20 @@ public String requestMappedMethod() {
231263
}
232264

233265
@Configuration
266+
@Import(ServerPortConfig.class)
234267
public static class DifferentPortConfig {
235268

236269
@Bean
237270
public ManagementServerProperties managementServerProperties() {
238271
ManagementServerProperties properties = new ManagementServerProperties();
239-
properties.setPort(8081);
272+
properties.setPort(ports.get().management);
240273
return properties;
241274
}
242275

243276
}
244277

245278
@Configuration
279+
@Import(ServerPortConfig.class)
246280
public static class RandomPortConfig {
247281

248282
@Bean
@@ -255,6 +289,7 @@ public ManagementServerProperties managementServerProperties() {
255289
}
256290

257291
@Configuration
292+
@Import(ServerPortConfig.class)
258293
public static class DisableConfig {
259294

260295
@Bean

spring-boot-actuator/src/test/java/org/springframework/boot/actuate/autoconfigure/SpringApplicationHierarchyTests.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,13 @@ public void after() {
4747
public void testParent() {
4848
SpringApplicationBuilder builder = new SpringApplicationBuilder(Child.class);
4949
builder.parent(Parent.class);
50-
this.context = builder.run();
50+
this.context = builder.run("--server.port=0");
5151
}
5252

5353
@Test
5454
public void testChild() {
55-
this.context = new SpringApplicationBuilder(Parent.class).child(Child.class)
56-
.run();
55+
this.context = new SpringApplicationBuilder(Parent.class).child(Child.class).run(
56+
"--server.port=0");
5757
}
5858

5959
@EnableAutoConfiguration

spring-boot-actuator/src/test/java/org/springframework/boot/actuate/web/BasicErrorControllerSpecialIntegrationTests.java

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,8 @@ public void setup(ConfigurableWebApplicationContext context) {
6060
@Test
6161
public void errorPageAvailableWithParentContext() throws Exception {
6262
setup((ConfigurableWebApplicationContext) new SpringApplicationBuilder(
63-
ParentConfiguration.class).child(ChildConfiguration.class).run());
63+
ParentConfiguration.class).child(ChildConfiguration.class).run(
64+
"--server.port=0"));
6465
MvcResult response = this.mockMvc
6566
.perform(get("/error").accept(MediaType.TEXT_HTML))
6667
.andExpect(status().isOk()).andReturn();
@@ -70,8 +71,8 @@ public void errorPageAvailableWithParentContext() throws Exception {
7071

7172
@Test
7273
public void errorPageAvailableWithMvcIncluded() throws Exception {
73-
setup((ConfigurableWebApplicationContext) SpringApplication
74-
.run(WebMvcIncludedConfiguration.class));
74+
setup((ConfigurableWebApplicationContext) new SpringApplication(
75+
WebMvcIncludedConfiguration.class).run("--server.port=0"));
7576
MvcResult response = this.mockMvc
7677
.perform(get("/error").accept(MediaType.TEXT_HTML))
7778
.andExpect(status().isOk()).andReturn();

spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/AutoConfigurationReproTests.java

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import org.junit.Test;
2121
import org.springframework.boot.SpringApplication;
2222
import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration;
23+
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
2324
import org.springframework.context.ConfigurableApplicationContext;
2425
import org.springframework.context.annotation.Configuration;
2526
import org.springframework.context.annotation.ImportResource;
@@ -48,8 +49,9 @@ public void cleanup() {
4849
public void doesNotEarlyInitializeFactoryBeans() throws Exception {
4950
SpringApplication application = new SpringApplication(EarlyInitConfig.class,
5051
PropertySourcesPlaceholderConfigurer.class,
51-
EmbeddedServletContainerAutoConfiguration.class);
52-
this.context = application.run();
52+
EmbeddedServletContainerAutoConfiguration.class,
53+
ServerPropertiesAutoConfiguration.class);
54+
this.context = application.run("--server.port=0");
5355
String bean = (String) this.context.getBean("earlyInit");
5456
assertThat(bean, equalTo("bucket"));
5557
}

spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/MultipartAutoConfigurationTests.java

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,9 @@ public void containerWithAutomatedMultipartJettyConfiguration() {
131131
public void containerWithAutomatedMultipartTomcatConfiguration() throws Exception {
132132
this.context = new AnnotationConfigEmbeddedWebApplicationContext(
133133
ContainerWithEverythingTomcat.class, BaseConfiguration.class);
134-
new RestTemplate().getForObject("http://localhost:8080/", String.class);
134+
new RestTemplate().getForObject("http://localhost:"
135+
+ this.context.getEmbeddedServletContainer().getPort() + "/",
136+
String.class);
135137
this.context.getBean(MultipartConfigElement.class);
136138
assertSame(this.context.getBean(DispatcherServlet.class).getMultipartResolver(),
137139
this.context.getBean(StandardServletMultipartResolver.class));
@@ -140,8 +142,9 @@ public void containerWithAutomatedMultipartTomcatConfiguration() throws Exceptio
140142

141143
private void verifyServletWorks() {
142144
RestTemplate restTemplate = new RestTemplate();
143-
assertEquals(restTemplate.getForObject("http://localhost:8080/", String.class),
144-
"Hello");
145+
assertEquals(restTemplate.getForObject("http://localhost:"
146+
+ this.context.getEmbeddedServletContainer().getPort() + "/",
147+
String.class), "Hello");
145148
}
146149

147150
@Configuration
@@ -150,6 +153,13 @@ private void verifyServletWorks() {
150153
ServerPropertiesAutoConfiguration.class })
151154
protected static class BaseConfiguration {
152155

156+
@Bean
157+
public ServerProperties serverProperties() {
158+
ServerProperties properties = new ServerProperties();
159+
properties.setPort(0);
160+
return properties;
161+
}
162+
153163
}
154164

155165
@Configuration

spring-boot-cli/src/test/java/org/springframework/boot/cli/CliTester.java

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
import org.springframework.boot.cli.command.run.RunCommand;
4040
import org.springframework.boot.cli.command.test.TestCommand;
4141
import org.springframework.boot.cli.util.OutputCapture;
42+
import org.springframework.util.SocketUtils;
4243

4344
/**
4445
* {@link TestRule} that can be used to invoke CLI commands.
@@ -57,6 +58,8 @@ public class CliTester implements TestRule {
5758

5859
private final String prefix;
5960

61+
private final int port = SocketUtils.findAvailableTcpPort();
62+
6063
public CliTester(String prefix) {
6164
this.prefix = prefix;
6265
}
@@ -96,11 +99,13 @@ private <T extends OptionParsingCommand> Future<T> submitCommand(final T command
9699
@Override
97100
public T call() throws Exception {
98101
ClassLoader loader = Thread.currentThread().getContextClassLoader();
102+
System.setProperty("server.port", String.valueOf(CliTester.this.port));
99103
try {
100104
command.run(sources);
101105
return command;
102106
}
103107
finally {
108+
System.clearProperty("server.port");
104109
Thread.currentThread().setContextClassLoader(loader);
105110
}
106111
}
@@ -148,12 +153,13 @@ public void evaluate() throws Throwable {
148153
}
149154

150155
public String getHttpOutput() {
151-
return getHttpOutput("http://localhost:8080");
156+
return getHttpOutput("/");
152157
}
153158

154159
public String getHttpOutput(String uri) {
155160
try {
156-
InputStream stream = URI.create(uri).toURL().openStream();
161+
InputStream stream = URI.create("http://localhost:" + this.port + uri)
162+
.toURL().openStream();
157163
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
158164
String line;
159165
StringBuilder result = new StringBuilder();

spring-boot-cli/src/test/java/org/springframework/boot/cli/SampleIntegrationTests.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ public void uiSample() throws Exception {
9999
this.cli.run("ui.groovy", "--classpath=.:src/test/resources");
100100
String result = this.cli.getHttpOutput();
101101
assertTrue("Wrong output: " + result, result.contains("Hello World"));
102-
result = this.cli.getHttpOutput("http://localhost:8080/css/bootstrap.min.css");
102+
result = this.cli.getHttpOutput("/css/bootstrap.min.css");
103103
assertTrue("Wrong output: " + result, result.contains("container"));
104104
}
105105

spring-boot-samples/spring-boot-sample-actuator-log4j/src/main/resources/application.properties

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
logging.file: /tmp/logs/app.log
2-
management.port: 8080
2+
#server.port: 8080
3+
#management.port: 8080
34
management.address: 127.0.0.1
45
endpoints.shutdown.enabled: true
5-
server.port: 8080
66
server.tomcat.basedir: target/tomcat
77
server.tomcat.access_log_pattern: %h %t "%r" %s %b
88
security.require_ssl: false
@@ -14,4 +14,4 @@ shell.ssh.port: 2222
1414
shell.auth: spring
1515
#shell.auth: key
1616
#shell.auth.key.path: ${user.home}/test/id_rsa.pub.pem
17-
#shell.auth: simple
17+
#shell.auth: simple

0 commit comments

Comments
 (0)