|
| 1 | +package io.kubernetes.client; |
| 2 | + |
| 3 | +import static org.junit.Assert.*; |
| 4 | + |
| 5 | +import com.squareup.okhttp.RequestBody; |
| 6 | +import com.squareup.okhttp.ws.WebSocket; |
| 7 | +import io.kubernetes.client.util.WebSocketStreamHandler; |
| 8 | +import java.io.*; |
| 9 | +import okio.Buffer; |
| 10 | +import okio.BufferedSink; |
| 11 | +import okio.Okio; |
| 12 | +import org.junit.Test; |
| 13 | + |
| 14 | +public class WebsocketStreamHandlerTest { |
| 15 | + |
| 16 | + private static String testProtocol = "test-protocol"; |
| 17 | + |
| 18 | + @Test |
| 19 | + public void testHandlerReceivingData() throws IOException { |
| 20 | + int testStreamId = 0; |
| 21 | + byte testData = 1; |
| 22 | + byte[] testDatas = |
| 23 | + new byte[] {(byte) testStreamId, testData, testData}; // first byte stands for stream id, |
| 24 | + ByteArrayInputStream testBytesInputStream = new ByteArrayInputStream(testDatas); |
| 25 | + |
| 26 | + WebSocketStreamHandler handler = new WebSocketStreamHandler(); |
| 27 | + MockWebSocket mockWebSocket = new MockWebSocket(); |
| 28 | + |
| 29 | + handler.open(testProtocol, mockWebSocket); |
| 30 | + |
| 31 | + InputStream inputStream = handler.getInputStream(testStreamId); |
| 32 | + |
| 33 | + // handler receiving |
| 34 | + handler.bytesMessage(testBytesInputStream); |
| 35 | + |
| 36 | + byte[] receivingData = new byte[16]; |
| 37 | + inputStream.read(receivingData); |
| 38 | + handler.close(); |
| 39 | + |
| 40 | + assertEquals(testData, receivingData[0]); |
| 41 | + assertEquals(testData, receivingData[1]); |
| 42 | + assertTrue(mockWebSocket.closed); |
| 43 | + } |
| 44 | + |
| 45 | + private class MockWebSocket implements WebSocket { |
| 46 | + private byte[] data; |
| 47 | + private boolean pinged = false; |
| 48 | + private boolean closed = false; |
| 49 | + |
| 50 | + @Override |
| 51 | + public void sendMessage(RequestBody message) throws IOException { |
| 52 | + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); |
| 53 | + BufferedSink sink = Okio.buffer(Okio.sink(outputStream)); |
| 54 | + message.writeTo(sink); |
| 55 | + this.data = outputStream.toByteArray(); |
| 56 | + } |
| 57 | + |
| 58 | + @Override |
| 59 | + public void sendPing(Buffer payload) throws IOException { |
| 60 | + this.pinged = true; |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public void close(int code, String reason) throws IOException { |
| 65 | + this.closed = true; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments