Jian Li
Committed by Gerrit Code Review

Randomize the port number to avoid race condition in REST unit test

Change-Id: Ib1b3bd5f16c7642af47b01d7a7930cae238fa71b
......@@ -18,15 +18,39 @@ package org.onosproject.rest.resources;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import java.io.IOException;
import java.net.ServerSocket;
/**
* Base class for REST API tests. Performs common configuration operations.
*/
public class ResourceTest extends JerseyTest {
private static final int DEFAULT_PORT = 9998;
/**
* Creates a new web-resource test.
*/
public ResourceTest() {
super(ResourceConfig.forApplicationClass(CoreWebApplication.class));
this.set("jersey.config.test.container.port", getRandomPort(DEFAULT_PORT));
}
/**
* Returns an unused port number to make sure that each unit test runs in
* different port number.
*
* @param defaultPort default port number
* @return a randomized unique port number
*/
private int getRandomPort(int defaultPort) {
try {
ServerSocket socket = new ServerSocket(0);
socket.setReuseAddress(true);
int port = socket.getLocalPort();
socket.close();
return port;
} catch (IOException ioe) {
return defaultPort;
}
}
}
......