PageRenderTime 61ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/zmq/tests/test_asyncio.py

http://github.com/zeromq/pyzmq
Python | 498 lines | 410 code | 71 blank | 17 comment | 21 complexity | ac280e96950fa86c1d7e802510228e44 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0, Apache-2.0
  1. """Test asyncio support"""
  2. # Copyright (c) PyZMQ Developers
  3. # Distributed under the terms of the Modified BSD License.
  4. import asyncio
  5. import json
  6. import os
  7. import sys
  8. from concurrent.futures import CancelledError
  9. from multiprocessing import Process
  10. import pytest
  11. from pytest import mark
  12. import zmq
  13. import zmq.asyncio as zaio
  14. from zmq.auth.asyncio import AsyncioAuthenticator
  15. from zmq.tests import BaseZMQTestCase
  16. from zmq.tests.test_auth import TestThreadAuthentication
  17. class ProcessForTeardownTest(Process):
  18. def __init__(self, event_loop_policy_class):
  19. Process.__init__(self)
  20. self.event_loop_policy_class = event_loop_policy_class
  21. def run(self):
  22. """Leave context, socket and event loop upon implicit disposal"""
  23. asyncio.set_event_loop_policy(self.event_loop_policy_class())
  24. actx = zaio.Context.instance()
  25. socket = actx.socket(zmq.PAIR)
  26. socket.bind_to_random_port("tcp://127.0.0.1")
  27. async def never_ending_task(socket):
  28. await socket.recv() # never ever receive anything
  29. loop = asyncio.new_event_loop()
  30. coro = asyncio.wait_for(never_ending_task(socket), timeout=1)
  31. try:
  32. loop.run_until_complete(coro)
  33. except asyncio.TimeoutError:
  34. pass # expected timeout
  35. else:
  36. assert False, "never_ending_task was completed unexpectedly"
  37. finally:
  38. loop.close()
  39. class TestAsyncIOSocket(BaseZMQTestCase):
  40. Context = zaio.Context
  41. def setUp(self):
  42. self.loop = asyncio.new_event_loop()
  43. asyncio.set_event_loop(self.loop)
  44. super().setUp()
  45. def tearDown(self):
  46. super().tearDown()
  47. self.loop.close()
  48. # verify cleanup of references to selectors
  49. assert zaio._selectors == {}
  50. if 'zmq._asyncio_selector' in sys.modules:
  51. assert zmq._asyncio_selector._selector_loops == set()
  52. def test_socket_class(self):
  53. s = self.context.socket(zmq.PUSH)
  54. assert isinstance(s, zaio.Socket)
  55. s.close()
  56. def test_instance_subclass_first(self):
  57. actx = zmq.asyncio.Context.instance()
  58. ctx = zmq.Context.instance()
  59. ctx.term()
  60. actx.term()
  61. assert type(ctx) is zmq.Context
  62. assert type(actx) is zmq.asyncio.Context
  63. def test_instance_subclass_second(self):
  64. ctx = zmq.Context.instance()
  65. actx = zmq.asyncio.Context.instance()
  66. ctx.term()
  67. actx.term()
  68. assert type(ctx) is zmq.Context
  69. assert type(actx) is zmq.asyncio.Context
  70. def test_recv_multipart(self):
  71. async def test():
  72. a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  73. f = b.recv_multipart()
  74. assert not f.done()
  75. await a.send(b"hi")
  76. recvd = await f
  77. assert recvd == [b"hi"]
  78. self.loop.run_until_complete(test())
  79. def test_recv(self):
  80. async def test():
  81. a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  82. f1 = b.recv()
  83. f2 = b.recv()
  84. assert not f1.done()
  85. assert not f2.done()
  86. await a.send_multipart([b"hi", b"there"])
  87. recvd = await f2
  88. assert f1.done()
  89. assert f1.result() == b"hi"
  90. assert recvd == b"there"
  91. self.loop.run_until_complete(test())
  92. @mark.skipif(not hasattr(zmq, "RCVTIMEO"), reason="requires RCVTIMEO")
  93. def test_recv_timeout(self):
  94. async def test():
  95. a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  96. b.rcvtimeo = 100
  97. f1 = b.recv()
  98. b.rcvtimeo = 1000
  99. f2 = b.recv_multipart()
  100. with self.assertRaises(zmq.Again):
  101. await f1
  102. await a.send_multipart([b"hi", b"there"])
  103. recvd = await f2
  104. assert f2.done()
  105. assert recvd == [b"hi", b"there"]
  106. self.loop.run_until_complete(test())
  107. @mark.skipif(not hasattr(zmq, "SNDTIMEO"), reason="requires SNDTIMEO")
  108. def test_send_timeout(self):
  109. async def test():
  110. s = self.socket(zmq.PUSH)
  111. s.sndtimeo = 100
  112. with self.assertRaises(zmq.Again):
  113. await s.send(b"not going anywhere")
  114. self.loop.run_until_complete(test())
  115. def test_recv_string(self):
  116. async def test():
  117. a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  118. f = b.recv_string()
  119. assert not f.done()
  120. msg = "πøøπ"
  121. await a.send_string(msg)
  122. recvd = await f
  123. assert f.done()
  124. assert f.result() == msg
  125. assert recvd == msg
  126. self.loop.run_until_complete(test())
  127. def test_recv_json(self):
  128. async def test():
  129. a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  130. f = b.recv_json()
  131. assert not f.done()
  132. obj = dict(a=5)
  133. await a.send_json(obj)
  134. recvd = await f
  135. assert f.done()
  136. assert f.result() == obj
  137. assert recvd == obj
  138. self.loop.run_until_complete(test())
  139. def test_recv_json_cancelled(self):
  140. async def test():
  141. a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  142. f = b.recv_json()
  143. assert not f.done()
  144. f.cancel()
  145. # cycle eventloop to allow cancel events to fire
  146. await asyncio.sleep(0)
  147. obj = dict(a=5)
  148. await a.send_json(obj)
  149. # CancelledError change in 3.8 https://bugs.python.org/issue32528
  150. if sys.version_info < (3, 8):
  151. with pytest.raises(CancelledError):
  152. recvd = await f
  153. else:
  154. with pytest.raises(asyncio.exceptions.CancelledError):
  155. recvd = await f
  156. assert f.done()
  157. # give it a chance to incorrectly consume the event
  158. events = await b.poll(timeout=5)
  159. assert events
  160. await asyncio.sleep(0)
  161. # make sure cancelled recv didn't eat up event
  162. f = b.recv_json()
  163. recvd = await asyncio.wait_for(f, timeout=5)
  164. assert recvd == obj
  165. self.loop.run_until_complete(test())
  166. def test_recv_pyobj(self):
  167. async def test():
  168. a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  169. f = b.recv_pyobj()
  170. assert not f.done()
  171. obj = dict(a=5)
  172. await a.send_pyobj(obj)
  173. recvd = await f
  174. assert f.done()
  175. assert f.result() == obj
  176. assert recvd == obj
  177. self.loop.run_until_complete(test())
  178. def test_custom_serialize(self):
  179. def serialize(msg):
  180. frames = []
  181. frames.extend(msg.get("identities", []))
  182. content = json.dumps(msg["content"]).encode("utf8")
  183. frames.append(content)
  184. return frames
  185. def deserialize(frames):
  186. identities = frames[:-1]
  187. content = json.loads(frames[-1].decode("utf8"))
  188. return {
  189. "identities": identities,
  190. "content": content,
  191. }
  192. async def test():
  193. a, b = self.create_bound_pair(zmq.DEALER, zmq.ROUTER)
  194. msg = {
  195. "content": {
  196. "a": 5,
  197. "b": "bee",
  198. }
  199. }
  200. await a.send_serialized(msg, serialize)
  201. recvd = await b.recv_serialized(deserialize)
  202. assert recvd["content"] == msg["content"]
  203. assert recvd["identities"]
  204. # bounce back, tests identities
  205. await b.send_serialized(recvd, serialize)
  206. r2 = await a.recv_serialized(deserialize)
  207. assert r2["content"] == msg["content"]
  208. assert not r2["identities"]
  209. self.loop.run_until_complete(test())
  210. def test_custom_serialize_error(self):
  211. async def test():
  212. a, b = self.create_bound_pair(zmq.DEALER, zmq.ROUTER)
  213. msg = {
  214. "content": {
  215. "a": 5,
  216. "b": "bee",
  217. }
  218. }
  219. with pytest.raises(TypeError):
  220. await a.send_serialized(json, json.dumps)
  221. await a.send(b"not json")
  222. with pytest.raises(TypeError):
  223. await b.recv_serialized(json.loads)
  224. self.loop.run_until_complete(test())
  225. def test_recv_dontwait(self):
  226. async def test():
  227. push, pull = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  228. f = pull.recv(zmq.DONTWAIT)
  229. with self.assertRaises(zmq.Again):
  230. await f
  231. await push.send(b"ping")
  232. await pull.poll() # ensure message will be waiting
  233. f = pull.recv(zmq.DONTWAIT)
  234. assert f.done()
  235. msg = await f
  236. assert msg == b"ping"
  237. self.loop.run_until_complete(test())
  238. def test_recv_cancel(self):
  239. async def test():
  240. a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  241. f1 = b.recv()
  242. f2 = b.recv_multipart()
  243. assert f1.cancel()
  244. assert f1.done()
  245. assert not f2.done()
  246. await a.send_multipart([b"hi", b"there"])
  247. recvd = await f2
  248. assert f1.cancelled()
  249. assert f2.done()
  250. assert recvd == [b"hi", b"there"]
  251. self.loop.run_until_complete(test())
  252. def test_poll(self):
  253. async def test():
  254. a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  255. f = b.poll(timeout=0)
  256. await asyncio.sleep(0)
  257. assert f.result() == 0
  258. f = b.poll(timeout=1)
  259. assert not f.done()
  260. evt = await f
  261. assert evt == 0
  262. f = b.poll(timeout=1000)
  263. assert not f.done()
  264. await a.send_multipart([b"hi", b"there"])
  265. evt = await f
  266. assert evt == zmq.POLLIN
  267. recvd = await b.recv_multipart()
  268. assert recvd == [b"hi", b"there"]
  269. self.loop.run_until_complete(test())
  270. def test_poll_base_socket(self):
  271. async def test():
  272. ctx = zmq.Context()
  273. url = "inproc://test"
  274. a = ctx.socket(zmq.PUSH)
  275. b = ctx.socket(zmq.PULL)
  276. self.sockets.extend([a, b])
  277. a.bind(url)
  278. b.connect(url)
  279. poller = zaio.Poller()
  280. poller.register(b, zmq.POLLIN)
  281. f = poller.poll(timeout=1000)
  282. assert not f.done()
  283. a.send_multipart([b"hi", b"there"])
  284. evt = await f
  285. assert evt == [(b, zmq.POLLIN)]
  286. recvd = b.recv_multipart()
  287. assert recvd == [b"hi", b"there"]
  288. self.loop.run_until_complete(test())
  289. def test_poll_on_closed_socket(self):
  290. async def test():
  291. a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  292. f = b.poll(timeout=1)
  293. b.close()
  294. # The test might stall if we try to await f directly so instead just make a few
  295. # passes through the event loop to schedule and execute all callbacks
  296. for _ in range(5):
  297. await asyncio.sleep(0)
  298. if f.cancelled():
  299. break
  300. assert f.cancelled()
  301. self.loop.run_until_complete(test())
  302. @pytest.mark.skipif(
  303. sys.platform.startswith("win"),
  304. reason="Windows does not support polling on files",
  305. )
  306. def test_poll_raw(self):
  307. async def test():
  308. p = zaio.Poller()
  309. # make a pipe
  310. r, w = os.pipe()
  311. r = os.fdopen(r, "rb")
  312. w = os.fdopen(w, "wb")
  313. # POLLOUT
  314. p.register(r, zmq.POLLIN)
  315. p.register(w, zmq.POLLOUT)
  316. evts = await p.poll(timeout=1)
  317. evts = dict(evts)
  318. assert r.fileno() not in evts
  319. assert w.fileno() in evts
  320. assert evts[w.fileno()] == zmq.POLLOUT
  321. # POLLIN
  322. p.unregister(w)
  323. w.write(b"x")
  324. w.flush()
  325. evts = await p.poll(timeout=1000)
  326. evts = dict(evts)
  327. assert r.fileno() in evts
  328. assert evts[r.fileno()] == zmq.POLLIN
  329. assert r.read(1) == b"x"
  330. r.close()
  331. w.close()
  332. loop = asyncio.new_event_loop()
  333. loop.run_until_complete(test())
  334. def test_multiple_loops(self):
  335. a, b = self.create_bound_pair(zmq.PUSH, zmq.PULL)
  336. async def test():
  337. await a.send(b'buf')
  338. msg = await b.recv()
  339. assert msg == b'buf'
  340. for i in range(3):
  341. loop = asyncio.new_event_loop()
  342. asyncio.set_event_loop(loop)
  343. loop.run_until_complete(asyncio.wait_for(test(), timeout=10))
  344. loop.close()
  345. def test_shadow(self):
  346. async def test():
  347. ctx = zmq.Context()
  348. s = ctx.socket(zmq.PULL)
  349. async_s = zaio.Socket(s)
  350. assert isinstance(async_s, self.socket_class)
  351. def test_process_teardown(self):
  352. event_loop_policy_class = type(asyncio.get_event_loop_policy())
  353. proc = ProcessForTeardownTest(event_loop_policy_class)
  354. proc.start()
  355. try:
  356. proc.join(10) # starting new Python process may cost a lot
  357. self.assertEqual(
  358. proc.exitcode,
  359. 0,
  360. "Python process died with code %d" % proc.exitcode
  361. if proc.exitcode
  362. else "process teardown hangs",
  363. )
  364. finally:
  365. proc.terminate()
  366. class TestAsyncioAuthentication(TestThreadAuthentication):
  367. """Test authentication running in a asyncio task"""
  368. Context = zaio.Context
  369. def shortDescription(self):
  370. """Rewrite doc strings from TestThreadAuthentication from
  371. 'threaded' to 'asyncio'.
  372. """
  373. doc = self._testMethodDoc
  374. if doc:
  375. doc = doc.split("\n")[0].strip()
  376. if doc.startswith("threaded auth"):
  377. doc = doc.replace("threaded auth", "asyncio auth")
  378. return doc
  379. def setUp(self):
  380. self.loop = asyncio.new_event_loop()
  381. asyncio.set_event_loop(self.loop)
  382. super().setUp()
  383. def tearDown(self):
  384. super().tearDown()
  385. self.loop.close()
  386. def make_auth(self):
  387. return AsyncioAuthenticator(self.context)
  388. def can_connect(self, server, client):
  389. """Check if client can connect to server using tcp transport"""
  390. async def go():
  391. result = False
  392. iface = "tcp://127.0.0.1"
  393. port = server.bind_to_random_port(iface)
  394. client.connect("%s:%i" % (iface, port))
  395. msg = [b"Hello World"]
  396. # set timeouts
  397. server.SNDTIMEO = client.RCVTIMEO = 1000
  398. try:
  399. await server.send_multipart(msg)
  400. except zmq.Again:
  401. return False
  402. try:
  403. rcvd_msg = await client.recv_multipart()
  404. except zmq.Again:
  405. return False
  406. else:
  407. assert rcvd_msg == msg
  408. result = True
  409. return result
  410. return self.loop.run_until_complete(go())
  411. def _select_recv(self, multipart, socket, **kwargs):
  412. recv = socket.recv_multipart if multipart else socket.recv
  413. async def coro():
  414. if not await socket.poll(5000):
  415. raise TimeoutError("Should have received a message")
  416. return await recv(**kwargs)
  417. return self.loop.run_until_complete(coro())