Skip to content

Commit

Permalink
test: Add close-during-accept test to AcceptTimeoutTest
Browse files Browse the repository at this point in the history
This test verifies that closing ServerSocket while accept is active
terminates and throws a SocketException.
  • Loading branch information
kohlschuetter committed Feb 12, 2024
1 parent 6421559 commit f0759d2
Showing 1 changed file with 43 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import java.net.SocketTimeoutException;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

import org.junit.jupiter.api.Test;
Expand All @@ -39,6 +40,8 @@
import com.kohlschutter.annotations.compiletime.SuppressFBWarnings;
import com.kohlschutter.testutil.TestAbortedWithImportantMessageException;
import com.kohlschutter.testutil.TestAbortedWithImportantMessageException.MessageType;
import com.kohlschutter.testutil.TestAsyncUtil;
import com.kohlschutter.testutil.TestStackTraceUtil;

/**
* Verifies that accept properly times out when an soTimeout was specified.
Expand Down Expand Up @@ -223,4 +226,44 @@ public void testAcceptWithoutBindToService() throws Exception {
}
});
}

@Test
public void testPendingAcceptCloseServerSocketImmediately() throws Exception {
testPendingAcceptCloseServerSocket(false);
}

@Test
public void testPendingAcceptCloseServerSocketDelayed() throws Exception {
testPendingAcceptCloseServerSocket(true);
}

private void testPendingAcceptCloseServerSocket(boolean delayed) throws Exception {
SocketAddress addr = newTempAddress();
ServerSocket ss = newServerSocketBindOn(addr);

Runnable doClose = () -> {
try {
ss.close();
} catch (IOException e) {
TestStackTraceUtil.printStackTrace(e);
}
};

if (delayed) {
TestAsyncUtil.runAsyncDelayed(1, TimeUnit.SECONDS, doClose);
} else {
doClose.run();
}

assertTimeoutPreemptively(Duration.ofSeconds(5), () -> {
// Should be SocketClosedException or InvalidArgumentSocketException, but no guarantee
assertThrows(SocketException.class, () -> {
try (Socket unused = ss.accept()) {
fail("Should not be reached");
} catch (SocketException e) {
throw e;
}
});
});
}
}

0 comments on commit f0759d2

Please sign in to comment.