CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
test_client.py
Go to the documentation of this file.
1"""Client tests: frame codec, UDP/TCP against small echo servers that behave like a service, and (with
2PSYCLONE_LIVE=<host>) every transport against a Psyclone running CMSDK/tools/client-test.xml."""
3import io
4import os
5import socket
6import struct
7import sys
8import threading
9import time
10import unittest
11
12sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
13from psyclone_client import DataMessage, Layout, PsycloneClient, PsycloneHttp # noqa: E402
14from psyclone_client.transports import WsFrames # noqa: E402
15
16LIVE = os.environ.get("PSYCLONE_LIVE", "")
17
18
19def is_packed(b):
20 return struct.unpack_from("<I", b, 4)[0] == Layout.PACKEDDATAMESSAGEID
21
22
23class UdpEcho:
24 """What the Echo service + Simple crank do: copy the message, name the trigger, answer in the same form."""
25 def __init__(self):
26 self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
27 self.s.bind(("127.0.0.1", 0))
28 self.port = self.s.getsockname()[1]
29 threading.Thread(target=self.run, daemon=True).start()
30
31 def run(self):
32 while True:
33 try:
34 d, a = self.s.recvfrom(65536)
35 except OSError:
36 return
37 m = DataMessage.from_bytes(d).set_string("PsyTrigger", "Pong")
38 self.s.sendto(m.to_packed_bytes() if is_packed(d) else m.to_bytes(), a)
39
40 def close(self):
41 self.s.close()
42
43
44class TcpEcho:
45 def __init__(self):
46 self.srv = socket.socket()
47 self.srv.bind(("127.0.0.1", 0))
48 self.srv.listen(5)
49 self.port = self.srv.getsockname()[1]
50 self.clients, self.accepted = [], 0
51 threading.Thread(target=self.run, daemon=True).start()
52
53 def run(self):
54 while True:
55 try:
56 c, _ = self.srv.accept()
57 except OSError:
58 return
59 self.clients.append(c)
60 self.accepted += 1
61 threading.Thread(target=self.serve, args=(c,), daemon=True).start()
62
63 def serve(self, c):
64 try:
65 while True:
66 h = b""
67 while len(h) < 8:
68 x = c.recv(8 - len(h))
69 if not x:
70 return
71 h += x
72 size = struct.unpack_from("<I", h)[0]
73 body = h
74 while len(body) < size:
75 body += c.recv(size - len(body))
76 c.sendall(DataMessage.from_bytes(body).set_string("PsyTrigger", "Pong").to_bytes())
77 except OSError:
78 pass
79
80 def drop_all(self):
81 for c in self.clients:
82 try:
83 c.shutdown(socket.SHUT_RDWR)
84 except OSError:
85 pass
86 c.close()
87 self.clients = []
88
89 def close(self):
90 self.srv.close()
91 self.drop_all()
92
93
94class Local(unittest.TestCase):
96 self.assertEqual("s3pPLMBiTxaQ9kYGzzhZRbK+xOo=", WsFrames.accept_for("dGhlIHNhbXBsZSBub25jZQ=="))
97
99 for n in (0, 1, 125, 126, 127, 65535, 65536, 200000):
100 payload = bytes((i * 31 + 7) & 0xFF for i in range(n))
101 for mask in (True, False):
102 b = io.BytesIO(WsFrames.encode(WsFrames.BINARY, payload, mask))
103 fin, op, p = WsFrames.read(b.read, 1 << 20)
104 self.assertTrue(fin)
105 self.assertEqual(WsFrames.BINARY, op)
106 self.assertEqual(payload, p, "length %d mask %s" % (n, mask))
107
109 for packed in (False, True):
110 srv = UdpEcho()
111 with PsycloneClient.udp("127.0.0.1", srv.port, "dev-1", packed=packed) as psy:
112 got, ev = [], threading.Event()
113 psy.on_trigger("Pong", lambda m: (got.append(m), len(got) == 3 and ev.set()))
114 for i in (1, 2, 3):
115 self.assertTrue(psy.post("Ping", DataMessage().set_int("N", i)))
116 self.assertTrue(ev.wait(3))
117 self.assertEqual({1, 2, 3}, {m.get_int("N") for m in got})
118 self.assertEqual("dev-1", got[0].get_string("PsyDevice"))
119 r = psy.request("Ping", DataMessage().set_string("Q", "hi"), timeout=3)
120 self.assertEqual("hi", r.get_string("Q"))
121 self.assertEqual(3, len(got), "a request reply does not go to the trigger handlers")
122 srv.close()
123
125 srv = TcpEcho()
126 states = []
127 with PsycloneClient.tcp("127.0.0.1", srv.port, "dev-2", reconnect_min=0.05, reconnect_max=0.2) as psy:
128 psy.on_state_changed(lambda up, err: states.append(up))
129 self.assertTrue(psy.wait_connected(3))
130 self.assertEqual(7, psy.request("Ping", DataMessage().set_int("N", 7), timeout=3).get_int("N"))
131 srv.drop_all()
132 end = time.time() + 5
133 while srv.accepted < 2 and time.time() < end:
134 time.sleep(0.02)
135 self.assertEqual(2, srv.accepted)
136 self.assertTrue(psy.wait_connected(3))
137 self.assertEqual(8, psy.request("Ping", DataMessage().set_int("N", 8), timeout=3).get_int("N"))
138 self.assertIn(False, states)
139 self.assertTrue(states[-1])
140 srv.close()
141
143 silent = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
144 silent.bind(("127.0.0.1", 0))
145 with PsycloneClient.udp("127.0.0.1", silent.getsockname()[1]) as psy:
146 t0 = time.time()
147 self.assertIsNone(psy.request("Ping", timeout=0.3))
148 self.assertTrue(0.25 < time.time() - t0 < 2)
149 silent.close()
150 with PsycloneClient.tcp("127.0.0.1", 1, reconnect=False, connect_timeout=0.5) as tcp:
151 self.assertFalse(tcp.post("Ping"))
152
153
154@unittest.skipUnless(LIVE, "PSYCLONE_LIVE=<host> runs these against CMSDK/tools/client-test.xml")
155class Live(unittest.TestCase):
156 def round_trip(self, psy, label):
157 with psy:
158 self.assertTrue(psy.wait_connected(5), label)
159 seen, ev = set(), threading.Event()
160 psy.on_trigger("Pong", lambda m: (seen.add(m.get_int("N")), len(seen) == 5 and ev.set()))
161 for i in range(1, 6):
162 self.assertTrue(psy.post("Ping", DataMessage().set_int("N", i).set_data("Bin", bytes(range(256)) * 2)))
163 self.assertTrue(ev.wait(5), "%s: got %s" % (label, seen))
164 t0 = time.perf_counter()
165 r = psy.request("Ping", DataMessage().set_string("Q", "hello " + label), timeout=5)
166 us = (time.perf_counter() - t0) * 1e6
167 self.assertIsNotNone(r, label)
168 self.assertEqual("hello " + label, r.get_string("Q"))
169 self.assertEqual("Pong", r.get_string("PsyTrigger"))
170 print("LIVE %s ok: 5 posts + request in %.0f us, sent %d received %d bad %d" % (label, us, psy.sent, psy.received, psy.bad))
171
172 def test_udp(self):
173 self.round_trip(PsycloneClient.udp(LIVE, 18710, "py-udp"), "udp")
174
176 self.round_trip(PsycloneClient.udp(LIVE, 18710, "py-udp-p", packed=True), "udp packed")
177
178 def test_tcp(self):
179 self.round_trip(PsycloneClient.tcp(LIVE, 18711, "py-tcp"), "tcp")
180
181 def test_websocket(self):
182 self.round_trip(PsycloneClient.websocket("ws://%s:18710/echo" % LIVE, "py-ws"), "ws")
183
185 self.round_trip(PsycloneClient.websocket("ws://%s:18710/echo" % LIVE, "py-ws-p", packed=True), "ws packed")
186
188 with PsycloneClient.websocket("ws://%s:18710/echo" % LIVE) as psy:
189 self.assertTrue(psy.wait_connected(5))
190 got, ev = [], threading.Event()
191 psy.on_text(lambda t: (got.append(t), ev.set()))
192 self.assertTrue(psy.send_text("plain text"))
193 self.assertTrue(ev.wait(5))
194 self.assertEqual(["plain text"], got)
195
196 def test_http(self):
197 r = PsycloneHttp("http://%s:18710" % LIVE).request("/echo", "Ping", {"Q": "via http"})
198 self.assertEqual(200, r.status)
199 self.assertIn("via http", r.text)
200
201
202if __name__ == "__main__":
203 unittest.main()
round_trip(self, psy, label)
test_websocket_text(self)
test_websocket_packed(self)
test_udp_post_trigger_and_request(self)
test_tcp_request_and_reconnect(self)
test_request_times_out_and_post_fails_when_down(self)
test_websocket_frames_round_trip_at_every_length_form(self)
test_websocket_accept_key_matches_rfc6455(self)