blob: 74695c9a7135b56755656fe5201aeb4faa46993b (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
package tools.refinery.language.web.tests;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.fail;
public abstract class WebSocketIntegrationTestClient {
private static final long TIMEOUT_MILLIS = Duration.ofSeconds(1).toMillis();
private boolean finished = false;
private final Object lock = new Object();
private Throwable error;
private int closeStatusCode;
private final List<String> responses = new ArrayList<>();
public int getCloseStatusCode() {
return closeStatusCode;
}
public List<String> getResponses() {
return responses;
}
@OnWebSocketConnect
public void onConnect(Session session) {
arrangeAndCatchErrors(session);
}
private void arrangeAndCatchErrors(Session session) {
try {
arrange(session, responses.size());
} catch (Exception e) {
finishedWithError(e);
}
}
protected abstract void arrange(Session session, int responsesReceived) throws IOException;
@OnWebSocketClose
public void onClose(int statusCode, String reason) {
closeStatusCode = statusCode;
testFinished();
}
@OnWebSocketError
public void onError(Throwable error) {
finishedWithError(error);
}
@OnWebSocketMessage
public void onMessage(Session session, String message) {
responses.add(message);
arrangeAndCatchErrors(session);
}
private void finishedWithError(Throwable t) {
error = t;
testFinished();
}
private void testFinished() {
synchronized (lock) {
finished = true;
lock.notify();
}
}
public void waitForTestResult() {
synchronized (lock) {
if (!finished) {
try {
lock.wait(TIMEOUT_MILLIS);
} catch (InterruptedException e) {
fail("Unexpected InterruptedException", e);
}
}
}
if (!finished) {
fail("Test still not finished after timeout");
}
if (error != null) {
fail("Unexpected exception in websocket thread", error);
}
}
}
|