|
3 | 3 | import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
|
4 | 4 |
|
5 | 5 | import java.io.IOException;
|
| 6 | +import java.nio.channels.ServerSocketChannel; |
6 | 7 | import java.nio.file.Files;
|
7 | 8 | import java.nio.file.Path;
|
8 | 9 | import java.time.Duration;
|
| 10 | +import java.util.concurrent.atomic.AtomicBoolean; |
| 11 | +import jnr.unixsocket.UnixSocketAddress; |
9 | 12 | import org.junit.jupiter.api.Assertions;
|
10 | 13 | import org.junit.jupiter.api.Test;
|
11 | 14 |
|
12 | 15 | public class TunnelingJdkSocketTest {
|
13 | 16 |
|
| 17 | + private final AtomicBoolean running = new AtomicBoolean(false); |
| 18 | + |
14 | 19 | @Test
|
15 | 20 | public void testTimeout() throws Exception {
|
16 | 21 | Assertions.assertEquals(1 + 1, 3); // should fail
|
17 | 22 |
|
18 | 23 | // create test path
|
19 | 24 | Path socketPath = Files.createTempFile("testSocket", null);
|
| 25 | + // start server |
| 26 | + startServer(socketPath); |
20 | 27 | // create client socket
|
21 | 28 | TunnelingJdkSocket clientSocket = createClient(socketPath);
|
22 | 29 |
|
23 | 30 | // attempt to read from empty socket (read should block indefinitely)
|
24 | 31 | assertTimeoutPreemptively(Duration.ofSeconds(5), () -> clientSocket.getInputStream().read());
|
25 | 32 |
|
26 |
| - // clean up |
| 33 | + // clean up client, server, and path |
27 | 34 | clientSocket.close();
|
| 35 | + running.set(false); |
28 | 36 | Files.deleteIfExists(socketPath);
|
29 | 37 | }
|
30 | 38 |
|
| 39 | + private void startServer(Path socketPath) { |
| 40 | + Thread serverThread = |
| 41 | + new Thread( |
| 42 | + () -> { |
| 43 | + // open and bind server to socketPath |
| 44 | + try (ServerSocketChannel serverChannel = ServerSocketChannel.open()) { |
| 45 | + serverChannel.socket().bind(new UnixSocketAddress(socketPath.toFile())); |
| 46 | + // accept connections made to the server |
| 47 | + running.set(true); |
| 48 | + while (running.get()) { |
| 49 | + serverChannel.accept(); |
| 50 | + } |
| 51 | + } catch (IOException e) { |
| 52 | + throw new RuntimeException(e); |
| 53 | + } |
| 54 | + }); |
| 55 | + |
| 56 | + // start server in separate thread |
| 57 | + serverThread.start(); |
| 58 | + } |
| 59 | + |
31 | 60 | private TunnelingJdkSocket createClient(Path socketPath) throws IOException {
|
32 | 61 | // create client socket
|
33 | 62 | TunnelingJdkSocket clientSocket = new TunnelingJdkSocket(socketPath);
|
|
0 commit comments