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; ...@@ -18,15 +18,39 @@ package org.onosproject.rest.resources;
18 import org.glassfish.jersey.server.ResourceConfig; 18 import org.glassfish.jersey.server.ResourceConfig;
19 import org.glassfish.jersey.test.JerseyTest; 19 import org.glassfish.jersey.test.JerseyTest;
20 20
21 +import java.io.IOException;
22 +import java.net.ServerSocket;
23 +
21 /** 24 /**
22 * Base class for REST API tests. Performs common configuration operations. 25 * Base class for REST API tests. Performs common configuration operations.
23 */ 26 */
24 public class ResourceTest extends JerseyTest { 27 public class ResourceTest extends JerseyTest {
28 + private static final int DEFAULT_PORT = 9998;
25 29
26 /** 30 /**
27 * Creates a new web-resource test. 31 * Creates a new web-resource test.
28 */ 32 */
29 public ResourceTest() { 33 public ResourceTest() {
30 super(ResourceConfig.forApplicationClass(CoreWebApplication.class)); 34 super(ResourceConfig.forApplicationClass(CoreWebApplication.class));
35 + this.set("jersey.config.test.container.port", getRandomPort(DEFAULT_PORT));
36 + }
37 +
38 + /**
39 + * Returns an unused port number to make sure that each unit test runs in
40 + * different port number.
41 + *
42 + * @param defaultPort default port number
43 + * @return a randomized unique port number
44 + */
45 + private int getRandomPort(int defaultPort) {
46 + try {
47 + ServerSocket socket = new ServerSocket(0);
48 + socket.setReuseAddress(true);
49 + int port = socket.getLocalPort();
50 + socket.close();
51 + return port;
52 + } catch (IOException ioe) {
53 + return defaultPort;
54 + }
31 } 55 }
32 } 56 }
......