test_rdb.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import errno
  2. import io
  3. import socket
  4. import pytest
  5. from case import Mock, patch, skip
  6. from celery.contrib.rdb import (
  7. Rdb,
  8. debugger,
  9. set_trace,
  10. )
  11. class SockErr(socket.error):
  12. errno = None
  13. class test_Rdb:
  14. @patch('celery.contrib.rdb.Rdb')
  15. def test_debugger(self, Rdb):
  16. x = debugger()
  17. assert x
  18. assert x is debugger()
  19. @patch('celery.contrib.rdb.debugger')
  20. @patch('celery.contrib.rdb._frame')
  21. def test_set_trace(self, _frame, debugger):
  22. assert set_trace(Mock())
  23. assert set_trace()
  24. debugger.return_value.set_trace.assert_called()
  25. @patch('celery.contrib.rdb.Rdb.get_avail_port')
  26. @skip.if_pypy()
  27. def test_rdb(self, get_avail_port):
  28. sock = Mock()
  29. get_avail_port.return_value = (sock, 8000)
  30. sock.accept.return_value = (Mock(), ['helu'])
  31. out = io.StringIO()
  32. with Rdb(out=out) as rdb:
  33. get_avail_port.assert_called()
  34. assert 'helu' in out.getvalue()
  35. # set_quit
  36. with patch('sys.settrace') as settrace:
  37. rdb.set_quit()
  38. settrace.assert_called_with(None)
  39. # set_trace
  40. with patch('celery.contrib.rdb.Pdb.set_trace') as pset:
  41. with patch('celery.contrib.rdb._frame'):
  42. rdb.set_trace()
  43. rdb.set_trace(Mock())
  44. pset.side_effect = SockErr
  45. pset.side_effect.errno = errno.ENOENT
  46. with pytest.raises(SockErr):
  47. rdb.set_trace()
  48. # _close_session
  49. rdb._close_session()
  50. rdb.active = True
  51. rdb._handle = None
  52. rdb._client = None
  53. rdb._sock = None
  54. rdb._close_session()
  55. # do_continue
  56. rdb.set_continue = Mock()
  57. rdb.do_continue(Mock())
  58. rdb.set_continue.assert_called_with()
  59. # do_quit
  60. rdb.set_quit = Mock()
  61. rdb.do_quit(Mock())
  62. rdb.set_quit.assert_called_with()
  63. @patch('socket.socket')
  64. @skip.if_pypy()
  65. def test_get_avail_port(self, sock):
  66. out = io.StringIO()
  67. sock.return_value.accept.return_value = (Mock(), ['helu'])
  68. with Rdb(out=out):
  69. pass
  70. with patch('celery.contrib.rdb.current_process') as curproc:
  71. curproc.return_value.name = 'PoolWorker-10'
  72. with Rdb(out=out):
  73. pass
  74. err = sock.return_value.bind.side_effect = SockErr()
  75. err.errno = errno.ENOENT
  76. with pytest.raises(SockErr):
  77. with Rdb(out=out):
  78. pass
  79. err.errno = errno.EADDRINUSE
  80. with pytest.raises(Exception):
  81. with Rdb(out=out):
  82. pass
  83. called = [0]
  84. def effect(*a, **kw):
  85. try:
  86. if called[0] > 50:
  87. return True
  88. raise err
  89. finally:
  90. called[0] += 1
  91. sock.return_value.bind.side_effect = effect
  92. with Rdb(out=out):
  93. pass