Skip to content

Commit

Permalink
Added randomization on port to avoid the address already in use error
Browse files Browse the repository at this point in the history
  • Loading branch information
Raul committed Sep 4, 2024
1 parent a408a28 commit 48284cf
Showing 1 changed file with 7 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import javax.inject.Inject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
Expand Down Expand Up @@ -72,11 +72,6 @@ public void setup() throws IOException {
Guice.createInjector().injectMembers(this);
}

@After
public void tearDown() throws IOException {
ajpTestServer.stop();
}

@Test
public void detect_weakCredentialsExists_returnsWeakCredentials() throws Exception {
ajpTestServer.setResponseForCredential(
Expand All @@ -98,6 +93,7 @@ public void detect_weakCredentialsExists_returnsWeakCredentials() throws Excepti

assertThat(tester.testValidCredentials(targetNetworkService, ImmutableList.of(WEAK_CRED_1)))
.containsExactly(WEAK_CRED_1);
ajpTestServer.stop();
}

@Test
Expand Down Expand Up @@ -161,11 +157,14 @@ private static byte[] createAjpUnauthorizedResponse() {
private static class AjpTestServer {
private ServerSocket serverSocket;
private boolean running = false;
private final int port = 8009;
private int port;
private final String host = "localhost";
private final Map<String, byte[]> credentialResponses = new HashMap<>();

public void start() throws IOException {

this.port = ThreadLocalRandom.current().nextInt(8000, 10001);

serverSocket = new ServerSocket(port);
running = true;

Expand Down Expand Up @@ -202,17 +201,9 @@ public void start() throws IOException {

public void stop() throws IOException {
running = false;
if (serverSocket != null) {
if (serverSocket != null && !serverSocket.isClosed()) {
serverSocket.close();
}

while (!serverSocket.isClosed()) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}

public String getHost() {
Expand Down

0 comments on commit 48284cf

Please sign in to comment.