|
| 1 | +package jsc.jServer; |
| 2 | + |
| 3 | +import jsc.jConnection.JConnection; |
| 4 | +import org.junit.jupiter.api.AfterEach; |
| 5 | +import org.junit.jupiter.api.BeforeEach; |
| 6 | +import org.junit.jupiter.api.Test; |
| 7 | + |
| 8 | +import java.util.concurrent.BlockingQueue; |
| 9 | +import java.util.concurrent.LinkedBlockingQueue; |
| 10 | +import java.util.concurrent.TimeUnit; |
| 11 | + |
| 12 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 13 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 14 | + |
| 15 | +/** End-to-end: real JServer on an ephemeral port, real JConnection client, messages echoed back in order. */ |
| 16 | +class EchoRoundTripTest { |
| 17 | + |
| 18 | + public static class Echo extends JRequestManager { |
| 19 | + @Override |
| 20 | + public void accept(String req) { write(req); } |
| 21 | + } |
| 22 | + |
| 23 | + private JServer server; |
| 24 | + private JConnection client; |
| 25 | + private final BlockingQueue<String> received = new LinkedBlockingQueue<>(); |
| 26 | + |
| 27 | + @BeforeEach |
| 28 | + void setUp() throws Exception { |
| 29 | + server = new JServer(0, Echo.class); // port 0 = OS picks a free port |
| 30 | + Thread t = new Thread(server::start, "jserver"); |
| 31 | + t.setDaemon(true); |
| 32 | + t.start(); |
| 33 | + client = new JConnection("127.0.0.1", server.getServerSocket().getLocalPort(), received::add); |
| 34 | + client.run(); |
| 35 | + } |
| 36 | + |
| 37 | + @AfterEach |
| 38 | + void tearDown() { |
| 39 | + client.close(); |
| 40 | + server.setRunning(false); |
| 41 | + server.close(); |
| 42 | + } |
| 43 | + |
| 44 | + @Test |
| 45 | + void echoesMessagesInOrder() throws Exception { |
| 46 | + String[] msgs = {"hello", "1/2~3>4;5,6", "unicode ✓"}; |
| 47 | + for (String m : msgs) client.write(m); |
| 48 | + for (String m : msgs) assertEquals(m, received.poll(5, TimeUnit.SECONDS)); |
| 49 | + } |
| 50 | + |
| 51 | + @Test |
| 52 | + void pausedReadHoldsMessagesUntilResume() throws Exception { |
| 53 | + client.write("before"); |
| 54 | + assertEquals("before", received.poll(5, TimeUnit.SECONDS)); |
| 55 | + client.setReadInterrupt(true); |
| 56 | + client.write("m1"); |
| 57 | + client.write("m2"); |
| 58 | + client.write("m3"); |
| 59 | + Thread.sleep(500); |
| 60 | + // The pause is checked before each blocking readUTF(), so a read already in flight |
| 61 | + // can still deliver one message (documented limitation); the rest must be held. |
| 62 | + int leaked = received.size(); |
| 63 | + assertTrue(leaked <= 1, "at most one in-flight message may arrive while paused, got " + leaked); |
| 64 | + client.setReadInterrupt(false); |
| 65 | + for (String m : new String[]{"m1", "m2", "m3"}) assertEquals(m, received.poll(5, TimeUnit.SECONDS)); |
| 66 | + } |
| 67 | +} |
0 commit comments