test_context.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. # Copyright (C) PyZMQ Developers
  2. # Distributed under the terms of the Modified BSD License.
  3. import copy
  4. import gc
  5. import os
  6. import sys
  7. import time
  8. from threading import Thread, Event
  9. try:
  10. from queue import Queue
  11. except ImportError:
  12. from Queue import Queue
  13. try:
  14. from unittest import mock
  15. except ImportError:
  16. mock = None
  17. from pytest import mark
  18. import zmq
  19. from zmq.tests import (
  20. BaseZMQTestCase, have_gevent, GreenTest, skip_green, PYPY, SkipTest,
  21. )
  22. class KwargTestSocket(zmq.Socket):
  23. test_kwarg_value = None
  24. def __init__(self, *args, **kwargs):
  25. self.test_kwarg_value = kwargs.pop('test_kwarg', None)
  26. super(KwargTestSocket, self).__init__(*args, **kwargs)
  27. class KwargTestContext(zmq.Context):
  28. _socket_class = KwargTestSocket
  29. class TestContext(BaseZMQTestCase):
  30. def test_init(self):
  31. c1 = self.Context()
  32. self.assert_(isinstance(c1, self.Context))
  33. del c1
  34. c2 = self.Context()
  35. self.assert_(isinstance(c2, self.Context))
  36. del c2
  37. c3 = self.Context()
  38. self.assert_(isinstance(c3, self.Context))
  39. del c3
  40. def test_dir(self):
  41. ctx = self.Context()
  42. self.assertTrue('socket' in dir(ctx))
  43. if zmq.zmq_version_info() > (3,):
  44. self.assertTrue('IO_THREADS' in dir(ctx))
  45. ctx.term()
  46. @mark.skipif(mock is None, reason="requires unittest.mock")
  47. def test_mockable(self):
  48. m = mock.Mock(spec=self.context)
  49. def test_term(self):
  50. c = self.Context()
  51. c.term()
  52. self.assert_(c.closed)
  53. def test_context_manager(self):
  54. with self.Context() as c:
  55. pass
  56. self.assert_(c.closed)
  57. def test_fail_init(self):
  58. self.assertRaisesErrno(zmq.EINVAL, self.Context, -1)
  59. def test_term_hang(self):
  60. rep,req = self.create_bound_pair(zmq.ROUTER, zmq.DEALER)
  61. req.setsockopt(zmq.LINGER, 0)
  62. req.send(b'hello', copy=False)
  63. req.close()
  64. rep.close()
  65. self.context.term()
  66. def test_instance(self):
  67. ctx = self.Context.instance()
  68. c2 = self.Context.instance(io_threads=2)
  69. self.assertTrue(c2 is ctx)
  70. c2.term()
  71. c3 = self.Context.instance()
  72. c4 = self.Context.instance()
  73. self.assertFalse(c3 is c2)
  74. self.assertFalse(c3.closed)
  75. self.assertTrue(c3 is c4)
  76. def test_instance_subclass_first(self):
  77. self.context.term()
  78. class SubContext(zmq.Context):
  79. pass
  80. sctx = SubContext.instance()
  81. ctx = zmq.Context.instance()
  82. ctx.term()
  83. sctx.term()
  84. assert type(ctx) is zmq.Context
  85. assert type(sctx) is SubContext
  86. def test_instance_subclass_second(self):
  87. self.context.term()
  88. class SubContextInherit(zmq.Context):
  89. pass
  90. class SubContextNoInherit(zmq.Context):
  91. _instance = None
  92. pass
  93. ctx = zmq.Context.instance()
  94. sctx = SubContextInherit.instance()
  95. sctx2 = SubContextNoInherit.instance()
  96. ctx.term()
  97. sctx.term()
  98. sctx2.term()
  99. assert type(ctx) is zmq.Context
  100. assert type(sctx) is zmq.Context
  101. assert type(sctx2) is SubContextNoInherit
  102. def test_instance_threadsafe(self):
  103. self.context.term() # clear default context
  104. q = Queue()
  105. # slow context initialization,
  106. # to ensure that we are both trying to create one at the same time
  107. class SlowContext(self.Context):
  108. def __init__(self, *a, **kw):
  109. time.sleep(1)
  110. super(SlowContext, self).__init__(*a, **kw)
  111. def f():
  112. q.put(SlowContext.instance())
  113. # call ctx.instance() in several threads at once
  114. N = 16
  115. threads = [ Thread(target=f) for i in range(N) ]
  116. [ t.start() for t in threads ]
  117. # also call it in the main thread (not first)
  118. ctx = SlowContext.instance()
  119. assert isinstance(ctx, SlowContext)
  120. # check that all the threads got the same context
  121. for i in range(N):
  122. thread_ctx = q.get(timeout=5)
  123. assert thread_ctx is ctx
  124. # cleanup
  125. ctx.term()
  126. [ t.join(timeout=5) for t in threads ]
  127. def test_socket_passes_kwargs(self):
  128. test_kwarg_value = 'testing one two three'
  129. with KwargTestContext() as ctx:
  130. with ctx.socket(zmq.DEALER, test_kwarg=test_kwarg_value) as socket:
  131. self.assertTrue(socket.test_kwarg_value is test_kwarg_value)
  132. def test_many_sockets(self):
  133. """opening and closing many sockets shouldn't cause problems"""
  134. ctx = self.Context()
  135. for i in range(16):
  136. sockets = [ ctx.socket(zmq.REP) for i in range(65) ]
  137. [ s.close() for s in sockets ]
  138. # give the reaper a chance
  139. time.sleep(1e-2)
  140. ctx.term()
  141. def test_sockopts(self):
  142. """setting socket options with ctx attributes"""
  143. ctx = self.Context()
  144. ctx.linger = 5
  145. self.assertEqual(ctx.linger, 5)
  146. s = ctx.socket(zmq.REQ)
  147. self.assertEqual(s.linger, 5)
  148. self.assertEqual(s.getsockopt(zmq.LINGER), 5)
  149. s.close()
  150. # check that subscribe doesn't get set on sockets that don't subscribe:
  151. ctx.subscribe = b''
  152. s = ctx.socket(zmq.REQ)
  153. s.close()
  154. ctx.term()
  155. @mark.skipif(
  156. sys.platform.startswith('win'),
  157. reason='Segfaults on Windows')
  158. def test_destroy(self):
  159. """Context.destroy should close sockets"""
  160. ctx = self.Context()
  161. sockets = [ ctx.socket(zmq.REP) for i in range(65) ]
  162. # close half of the sockets
  163. [ s.close() for s in sockets[::2] ]
  164. ctx.destroy()
  165. # reaper is not instantaneous
  166. time.sleep(1e-2)
  167. for s in sockets:
  168. self.assertTrue(s.closed)
  169. def test_destroy_linger(self):
  170. """Context.destroy should set linger on closing sockets"""
  171. req,rep = self.create_bound_pair(zmq.REQ, zmq.REP)
  172. req.send(b'hi')
  173. time.sleep(1e-2)
  174. self.context.destroy(linger=0)
  175. # reaper is not instantaneous
  176. time.sleep(1e-2)
  177. for s in (req,rep):
  178. self.assertTrue(s.closed)
  179. def test_term_noclose(self):
  180. """Context.term won't close sockets"""
  181. ctx = self.Context()
  182. s = ctx.socket(zmq.REQ)
  183. self.assertFalse(s.closed)
  184. t = Thread(target=ctx.term)
  185. t.start()
  186. t.join(timeout=0.1)
  187. self.assertTrue(t.is_alive(), "Context should be waiting")
  188. s.close()
  189. t.join(timeout=0.1)
  190. self.assertFalse(t.is_alive(), "Context should have closed")
  191. def test_gc(self):
  192. """test close&term by garbage collection alone"""
  193. if PYPY:
  194. raise SkipTest("GC doesn't work ")
  195. # test credit @dln (GH #137):
  196. def gcf():
  197. def inner():
  198. ctx = self.Context()
  199. s = ctx.socket(zmq.PUSH)
  200. inner()
  201. gc.collect()
  202. t = Thread(target=gcf)
  203. t.start()
  204. t.join(timeout=1)
  205. self.assertFalse(t.is_alive(), "Garbage collection should have cleaned up context")
  206. def test_cyclic_destroy(self):
  207. """ctx.destroy should succeed when cyclic ref prevents gc"""
  208. # test credit @dln (GH #137):
  209. class CyclicReference(object):
  210. def __init__(self, parent=None):
  211. self.parent = parent
  212. def crash(self, sock):
  213. self.sock = sock
  214. self.child = CyclicReference(self)
  215. def crash_zmq():
  216. ctx = self.Context()
  217. sock = ctx.socket(zmq.PULL)
  218. c = CyclicReference()
  219. c.crash(sock)
  220. ctx.destroy()
  221. crash_zmq()
  222. def test_term_thread(self):
  223. """ctx.term should not crash active threads (#139)"""
  224. ctx = self.Context()
  225. evt = Event()
  226. evt.clear()
  227. def block():
  228. s = ctx.socket(zmq.REP)
  229. s.bind_to_random_port('tcp://127.0.0.1')
  230. evt.set()
  231. try:
  232. s.recv()
  233. except zmq.ZMQError as e:
  234. self.assertEqual(e.errno, zmq.ETERM)
  235. return
  236. finally:
  237. s.close()
  238. self.fail("recv should have been interrupted with ETERM")
  239. t = Thread(target=block)
  240. t.start()
  241. evt.wait(1)
  242. self.assertTrue(evt.is_set(), "sync event never fired")
  243. time.sleep(0.01)
  244. ctx.term()
  245. t.join(timeout=1)
  246. self.assertFalse(t.is_alive(), "term should have interrupted s.recv()")
  247. def test_destroy_no_sockets(self):
  248. ctx = self.Context()
  249. s = ctx.socket(zmq.PUB)
  250. s.bind_to_random_port('tcp://127.0.0.1')
  251. s.close()
  252. ctx.destroy()
  253. assert s.closed
  254. assert ctx.closed
  255. def test_ctx_opts(self):
  256. if zmq.zmq_version_info() < (3,):
  257. raise SkipTest("context options require libzmq 3")
  258. ctx = self.Context()
  259. ctx.set(zmq.MAX_SOCKETS, 2)
  260. self.assertEqual(ctx.get(zmq.MAX_SOCKETS), 2)
  261. ctx.max_sockets = 100
  262. self.assertEqual(ctx.max_sockets, 100)
  263. self.assertEqual(ctx.get(zmq.MAX_SOCKETS), 100)
  264. def test_copy(self):
  265. c1 = self.Context()
  266. c2 = copy.copy(c1)
  267. c2b = copy.deepcopy(c1)
  268. c3 = copy.deepcopy(c2)
  269. self.assert_(c2._shadow)
  270. self.assert_(c3._shadow)
  271. self.assertEqual(c1.underlying, c2.underlying)
  272. self.assertEqual(c1.underlying, c3.underlying)
  273. self.assertEqual(c1.underlying, c2b.underlying)
  274. s = c3.socket(zmq.PUB)
  275. s.close()
  276. c1.term()
  277. def test_shadow(self):
  278. ctx = self.Context()
  279. ctx2 = self.Context.shadow(ctx.underlying)
  280. self.assertEqual(ctx.underlying, ctx2.underlying)
  281. s = ctx.socket(zmq.PUB)
  282. s.close()
  283. del ctx2
  284. self.assertFalse(ctx.closed)
  285. s = ctx.socket(zmq.PUB)
  286. ctx2 = self.Context.shadow(ctx.underlying)
  287. s2 = ctx2.socket(zmq.PUB)
  288. s.close()
  289. s2.close()
  290. ctx.term()
  291. self.assertRaisesErrno(zmq.EFAULT, ctx2.socket, zmq.PUB)
  292. del ctx2
  293. def test_shadow_pyczmq(self):
  294. try:
  295. from pyczmq import zctx, zsocket, zstr
  296. except Exception:
  297. raise SkipTest("Requires pyczmq")
  298. ctx = zctx.new()
  299. a = zsocket.new(ctx, zmq.PUSH)
  300. zsocket.bind(a, "inproc://a")
  301. ctx2 = self.Context.shadow_pyczmq(ctx)
  302. b = ctx2.socket(zmq.PULL)
  303. b.connect("inproc://a")
  304. zstr.send(a, b'hi')
  305. rcvd = self.recv(b)
  306. self.assertEqual(rcvd, b'hi')
  307. b.close()
  308. @mark.skipif(
  309. sys.platform.startswith('win'),
  310. reason='No fork on Windows')
  311. def test_fork_instance(self):
  312. ctx = self.Context.instance()
  313. parent_ctx_id = id(ctx)
  314. r_fd, w_fd = os.pipe()
  315. reader = os.fdopen(r_fd, 'r')
  316. child_pid = os.fork()
  317. if child_pid == 0:
  318. ctx = self.Context.instance()
  319. writer = os.fdopen(w_fd, 'w')
  320. child_ctx_id = id(ctx)
  321. ctx.term()
  322. writer.write(str(child_ctx_id) + "\n")
  323. writer.flush()
  324. writer.close()
  325. os._exit(0)
  326. else:
  327. os.close(w_fd)
  328. child_id_s = reader.readline()
  329. reader.close()
  330. assert child_id_s
  331. assert int(child_id_s) != parent_ctx_id
  332. ctx.term()
  333. if False: # disable green context tests
  334. class TestContextGreen(GreenTest, TestContext):
  335. """gevent subclass of context tests"""
  336. # skip tests that use real threads:
  337. test_gc = GreenTest.skip_green
  338. test_term_thread = GreenTest.skip_green
  339. test_destroy_linger = GreenTest.skip_green