Use random ports for tests

Update remaining tests to use random ports.

Fixes gh-337
This commit is contained in:
Phillip Webb 2014-04-23 19:10:25 +01:00
parent af33cc2b97
commit 4119ef5cf4
10 changed files with 122 additions and 53 deletions

View File

@ -22,6 +22,7 @@ import java.net.URI;
import java.nio.charset.Charset;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.actuate.endpoint.Endpoint;
import org.springframework.boot.actuate.endpoint.mvc.MvcEndpoint;
@ -29,6 +30,7 @@ import org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfigurati
import org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration;
import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration;
import org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration;
import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
@ -45,6 +47,7 @@ import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.SocketUtils;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@ -55,7 +58,7 @@ import static org.junit.Assert.assertThat;
/**
* Tests for {@link EndpointWebMvcAutoConfiguration}.
*
*
* @author Phillip Webb
* @author Greg Turnquist
*/
@ -63,6 +66,13 @@ public class EndpointWebMvcAutoConfigurationTests {
private final AnnotationConfigEmbeddedWebApplicationContext applicationContext = new AnnotationConfigEmbeddedWebApplicationContext();
private static ThreadLocal<Ports> ports = new ThreadLocal<Ports>();
@Before
public void grabPorts() {
ports.set(new Ports());
}
@After
public void close() {
if (this.applicationContext != null) {
@ -73,12 +83,13 @@ public class EndpointWebMvcAutoConfigurationTests {
@Test
public void onSamePort() throws Exception {
this.applicationContext.register(RootConfig.class, BaseConfiguration.class,
ServerPortConfig.class,
EndpointWebMvcAutoConfiguration.class);
this.applicationContext.refresh();
assertContent("/controller", 8080, "controlleroutput");
assertContent("/endpoint", 8080, "endpointoutput");
assertContent("/controller", 8081, null);
assertContent("/endpoint", 8081, null);
assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/endpoint", ports.get().server, "endpointoutput");
assertContent("/controller", ports.get().management, null);
assertContent("/endpoint", ports.get().management, null);
this.applicationContext.close();
assertAllClosed();
}
@ -89,10 +100,10 @@ public class EndpointWebMvcAutoConfigurationTests {
BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class,
ErrorMvcAutoConfiguration.class);
this.applicationContext.refresh();
assertContent("/controller", 8080, "controlleroutput");
assertContent("/endpoint", 8080, null);
assertContent("/controller", 8081, null);
assertContent("/endpoint", 8081, "endpointoutput");
assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/endpoint", ports.get().server, null);
assertContent("/controller", ports.get().management, null);
assertContent("/endpoint", ports.get().management, "endpointoutput");
this.applicationContext.close();
assertAllClosed();
}
@ -107,9 +118,9 @@ public class EndpointWebMvcAutoConfigurationTests {
this.applicationContext.addApplicationListener(grabManagementPort);
this.applicationContext.refresh();
int managementPort = grabManagementPort.getServletContainer().getPort();
assertThat(managementPort, not(equalTo(8080)));
assertContent("/controller", 8080, "controlleroutput");
assertContent("/endpoint", 8080, null);
assertThat(managementPort, not(equalTo(ports.get().server)));
assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/endpoint", ports.get().server, null);
assertContent("/controller", managementPort, null);
assertContent("/endpoint", managementPort, "endpointoutput");
}
@ -119,25 +130,25 @@ public class EndpointWebMvcAutoConfigurationTests {
this.applicationContext.register(RootConfig.class, DisableConfig.class,
BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class);
this.applicationContext.refresh();
assertContent("/controller", 8080, "controlleroutput");
assertContent("/endpoint", 8080, null);
assertContent("/controller", 8081, null);
assertContent("/endpoint", 8081, null);
assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/endpoint", ports.get().server, null);
assertContent("/controller", ports.get().management, null);
assertContent("/endpoint", ports.get().management, null);
this.applicationContext.close();
assertAllClosed();
}
@Test
public void specificPortsViaProperties() throws Exception {
EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:7070",
"management.port:7071");
EnvironmentTestUtils.addEnvironment(this.applicationContext, "server.port:"
+ ports.get().server, "management.port:" + ports.get().management);
this.applicationContext.register(RootConfig.class, BaseConfiguration.class,
EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class);
this.applicationContext.refresh();
assertContent("/controller", 7070, "controlleroutput");
assertContent("/endpoint", 7070, null);
assertContent("/controller", 7071, null);
assertContent("/endpoint", 7071, "endpointoutput");
assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/endpoint", ports.get().server, null);
assertContent("/controller", ports.get().management, null);
assertContent("/endpoint", ports.get().management, "endpointoutput");
this.applicationContext.close();
assertAllClosed();
}
@ -146,7 +157,7 @@ public class EndpointWebMvcAutoConfigurationTests {
public void contextPath() throws Exception {
EnvironmentTestUtils.addEnvironment(this.applicationContext,
"management.contextPath:/test");
this.applicationContext.register(RootConfig.class,
this.applicationContext.register(RootConfig.class, ServerPortConfig.class,
PropertyPlaceholderAutoConfiguration.class,
ManagementServerPropertiesAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class,
@ -155,17 +166,17 @@ public class EndpointWebMvcAutoConfigurationTests {
DispatcherServletAutoConfiguration.class, WebMvcAutoConfiguration.class,
EndpointWebMvcAutoConfiguration.class);
this.applicationContext.refresh();
assertContent("/controller", 8080, "controlleroutput");
assertContent("/test/endpoint", 8080, "endpointoutput");
assertContent("/controller", ports.get().server, "controlleroutput");
assertContent("/test/endpoint", ports.get().server, "endpointoutput");
this.applicationContext.close();
assertAllClosed();
}
private void assertAllClosed() throws Exception {
assertContent("/controller", 8080, null);
assertContent("/endpoint", 8080, null);
assertContent("/controller", 8081, null);
assertContent("/endpoint", 8081, null);
assertContent("/controller", ports.get().server, null);
assertContent("/endpoint", ports.get().server, null);
assertContent("/controller", ports.get().management, null);
assertContent("/endpoint", ports.get().management, null);
}
public void assertContent(String url, int port, Object expected) throws Exception {
@ -194,6 +205,14 @@ public class EndpointWebMvcAutoConfigurationTests {
}
}
private static class Ports {
int server = SocketUtils.findAvailableTcpPort();
int management = SocketUtils.findAvailableTcpPort();
}
@Configuration
@Import({ PropertyPlaceholderAutoConfiguration.class,
EmbeddedServletContainerAutoConfiguration.class,
@ -217,6 +236,19 @@ public class EndpointWebMvcAutoConfigurationTests {
public TestEndpoint testEndpoint() {
return new TestEndpoint();
}
}
@Configuration
public static class ServerPortConfig {
@Bean
public ServerProperties serverProperties() {
ServerProperties properties = new ServerProperties();
properties.setPort(ports.get().server);
return properties;
}
}
@Controller
@ -231,18 +263,20 @@ public class EndpointWebMvcAutoConfigurationTests {
}
@Configuration
@Import(ServerPortConfig.class)
public static class DifferentPortConfig {
@Bean
public ManagementServerProperties managementServerProperties() {
ManagementServerProperties properties = new ManagementServerProperties();
properties.setPort(8081);
properties.setPort(ports.get().management);
return properties;
}
}
@Configuration
@Import(ServerPortConfig.class)
public static class RandomPortConfig {
@Bean
@ -255,6 +289,7 @@ public class EndpointWebMvcAutoConfigurationTests {
}
@Configuration
@Import(ServerPortConfig.class)
public static class DisableConfig {
@Bean

View File

@ -47,13 +47,13 @@ public class SpringApplicationHierarchyTests {
public void testParent() {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Child.class);
builder.parent(Parent.class);
this.context = builder.run();
this.context = builder.run("--server.port=0");
}
@Test
public void testChild() {
this.context = new SpringApplicationBuilder(Parent.class).child(Child.class)
.run();
this.context = new SpringApplicationBuilder(Parent.class).child(Child.class).run(
"--server.port=0");
}
@EnableAutoConfiguration

View File

@ -60,7 +60,8 @@ public class BasicErrorControllerSpecialIntegrationTests {
@Test
public void errorPageAvailableWithParentContext() throws Exception {
setup((ConfigurableWebApplicationContext) new SpringApplicationBuilder(
ParentConfiguration.class).child(ChildConfiguration.class).run());
ParentConfiguration.class).child(ChildConfiguration.class).run(
"--server.port=0"));
MvcResult response = this.mockMvc
.perform(get("/error").accept(MediaType.TEXT_HTML))
.andExpect(status().isOk()).andReturn();
@ -70,8 +71,8 @@ public class BasicErrorControllerSpecialIntegrationTests {
@Test
public void errorPageAvailableWithMvcIncluded() throws Exception {
setup((ConfigurableWebApplicationContext) SpringApplication
.run(WebMvcIncludedConfiguration.class));
setup((ConfigurableWebApplicationContext) new SpringApplication(
WebMvcIncludedConfiguration.class).run("--server.port=0"));
MvcResult response = this.mockMvc
.perform(get("/error").accept(MediaType.TEXT_HTML))
.andExpect(status().isOk()).andReturn();

View File

@ -20,6 +20,7 @@ import org.junit.After;
import org.junit.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
@ -48,8 +49,9 @@ public class AutoConfigurationReproTests {
public void doesNotEarlyInitializeFactoryBeans() throws Exception {
SpringApplication application = new SpringApplication(EarlyInitConfig.class,
PropertySourcesPlaceholderConfigurer.class,
EmbeddedServletContainerAutoConfiguration.class);
this.context = application.run();
EmbeddedServletContainerAutoConfiguration.class,
ServerPropertiesAutoConfiguration.class);
this.context = application.run("--server.port=0");
String bean = (String) this.context.getBean("earlyInit");
assertThat(bean, equalTo("bucket"));
}

View File

@ -131,7 +131,9 @@ public class MultipartAutoConfigurationTests {
public void containerWithAutomatedMultipartTomcatConfiguration() throws Exception {
this.context = new AnnotationConfigEmbeddedWebApplicationContext(
ContainerWithEverythingTomcat.class, BaseConfiguration.class);
new RestTemplate().getForObject("http://localhost:8080/", String.class);
new RestTemplate().getForObject("http://localhost:"
+ this.context.getEmbeddedServletContainer().getPort() + "/",
String.class);
this.context.getBean(MultipartConfigElement.class);
assertSame(this.context.getBean(DispatcherServlet.class).getMultipartResolver(),
this.context.getBean(StandardServletMultipartResolver.class));
@ -140,8 +142,9 @@ public class MultipartAutoConfigurationTests {
private void verifyServletWorks() {
RestTemplate restTemplate = new RestTemplate();
assertEquals(restTemplate.getForObject("http://localhost:8080/", String.class),
"Hello");
assertEquals(restTemplate.getForObject("http://localhost:"
+ this.context.getEmbeddedServletContainer().getPort() + "/",
String.class), "Hello");
}
@Configuration
@ -150,6 +153,13 @@ public class MultipartAutoConfigurationTests {
ServerPropertiesAutoConfiguration.class })
protected static class BaseConfiguration {
@Bean
public ServerProperties serverProperties() {
ServerProperties properties = new ServerProperties();
properties.setPort(0);
return properties;
}
}
@Configuration

View File

@ -39,6 +39,7 @@ import org.springframework.boot.cli.command.jar.JarCommand;
import org.springframework.boot.cli.command.run.RunCommand;
import org.springframework.boot.cli.command.test.TestCommand;
import org.springframework.boot.cli.util.OutputCapture;
import org.springframework.util.SocketUtils;
/**
* {@link TestRule} that can be used to invoke CLI commands.
@ -57,6 +58,8 @@ public class CliTester implements TestRule {
private final String prefix;
private final int port = SocketUtils.findAvailableTcpPort();
public CliTester(String prefix) {
this.prefix = prefix;
}
@ -96,11 +99,13 @@ public class CliTester implements TestRule {
@Override
public T call() throws Exception {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
System.setProperty("server.port", String.valueOf(CliTester.this.port));
try {
command.run(sources);
return command;
}
finally {
System.clearProperty("server.port");
Thread.currentThread().setContextClassLoader(loader);
}
}
@ -148,12 +153,13 @@ public class CliTester implements TestRule {
}
public String getHttpOutput() {
return getHttpOutput("http://localhost:8080");
return getHttpOutput("/");
}
public String getHttpOutput(String uri) {
try {
InputStream stream = URI.create(uri).toURL().openStream();
InputStream stream = URI.create("http://localhost:" + this.port + uri)
.toURL().openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
StringBuilder result = new StringBuilder();

View File

@ -99,7 +99,7 @@ public class SampleIntegrationTests {
this.cli.run("ui.groovy", "--classpath=.:src/test/resources");
String result = this.cli.getHttpOutput();
assertTrue("Wrong output: " + result, result.contains("Hello World"));
result = this.cli.getHttpOutput("http://localhost:8080/css/bootstrap.min.css");
result = this.cli.getHttpOutput("/css/bootstrap.min.css");
assertTrue("Wrong output: " + result, result.contains("container"));
}

View File

@ -1,8 +1,8 @@
logging.file: /tmp/logs/app.log
management.port: 8080
#server.port: 8080
#management.port: 8080
management.address: 127.0.0.1
endpoints.shutdown.enabled: true
server.port: 8080
server.tomcat.basedir: target/tomcat
server.tomcat.access_log_pattern: %h %t "%r" %s %b
security.require_ssl: false
@ -14,4 +14,4 @@ shell.ssh.port: 2222
shell.auth: spring
#shell.auth: key
#shell.auth.key.path: ${user.home}/test/id_rsa.pub.pem
#shell.auth: simple
#shell.auth: simple

View File

@ -31,6 +31,7 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.SocketUtils;
/**
* Sample Application to show Tomcat running 2 connectors
@ -42,6 +43,11 @@ import org.springframework.util.FileCopyUtils;
@ComponentScan
public class SampleTomcatTwoConnectorsApplication {
@Bean
public int port() {
return SocketUtils.findAvailableTcpPort();
}
@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
@ -57,7 +63,7 @@ public class SampleTomcatTwoConnectorsApplication {
File truststore = keystore;
connector.setScheme("https");
connector.setSecure(true);
connector.setPort(8443);
connector.setPort(port());
protocol.setSSLEnabled(true);
protocol.setKeystoreFile(keystore.getAbsolutePath());
protocol.setKeystorePass("changeit");

View File

@ -29,8 +29,11 @@ import javax.net.ssl.X509TrustManager;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
@ -49,10 +52,16 @@ import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleTomcatTwoConnectorsApplication.class)
@WebAppConfiguration
@IntegrationTest
@IntegrationTest("server.port=0")
@DirtiesContext
public class SampleTomcatTwoConnectorsApplicationTests {
@Value("${local.server.port}")
private String port;
@Autowired
private ApplicationContext context;
@BeforeClass
public static void setUp() {
@ -100,13 +109,13 @@ public class SampleTomcatTwoConnectorsApplicationTests {
});
template.setRequestFactory(factory);
ResponseEntity<String> entity = template.getForEntity(
"http://localhost:8080/hello", String.class);
ResponseEntity<String> entity = template.getForEntity("http://localhost:"
+ this.port + "/hello", String.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
assertEquals("hello", entity.getBody());
ResponseEntity<String> httpsEntity = template.getForEntity(
"https://localhost:8443/hello", String.class);
ResponseEntity<String> httpsEntity = template.getForEntity("https://localhost:"
+ this.context.getBean("port") + "/hello", String.class);
assertEquals(HttpStatus.OK, httpsEntity.getStatusCode());
assertEquals("hello", httpsEntity.getBody());