test_threads.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. from __future__ import absolute_import, unicode_literals
  2. import pytest
  3. from case import mock, patch
  4. from celery.utils.threads import (Local, LocalManager, _FastLocalStack,
  5. _LocalStack, bgThread)
  6. class test_bgThread:
  7. def test_crash(self):
  8. class T(bgThread):
  9. def body(self):
  10. raise KeyError()
  11. with patch('os._exit') as _exit:
  12. with mock.stdouts():
  13. _exit.side_effect = ValueError()
  14. t = T()
  15. with pytest.raises(ValueError):
  16. t.run()
  17. _exit.assert_called_with(1)
  18. def test_interface(self):
  19. x = bgThread()
  20. with pytest.raises(NotImplementedError):
  21. x.body()
  22. class test_Local:
  23. def test_iter(self):
  24. x = Local()
  25. x.foo = 'bar'
  26. ident = x.__ident_func__()
  27. assert (ident, {'foo': 'bar'}) in list(iter(x))
  28. delattr(x, 'foo')
  29. assert (ident, {'foo': 'bar'}) not in list(iter(x))
  30. with pytest.raises(AttributeError):
  31. delattr(x, 'foo')
  32. assert x(lambda: 'foo') is not None
  33. class test_LocalStack:
  34. def test_stack(self):
  35. x = _LocalStack()
  36. assert x.pop() is None
  37. x.__release_local__()
  38. ident = x.__ident_func__
  39. x.__ident_func__ = ident
  40. with pytest.raises(RuntimeError):
  41. x()[0]
  42. x.push(['foo'])
  43. assert x()[0] == 'foo'
  44. x.pop()
  45. with pytest.raises(RuntimeError):
  46. x()[0]
  47. class test_FastLocalStack:
  48. def test_stack(self):
  49. x = _FastLocalStack()
  50. x.push(['foo'])
  51. x.push(['bar'])
  52. assert x.top == ['bar']
  53. assert len(x) == 2
  54. x.pop()
  55. assert x.top == ['foo']
  56. x.pop()
  57. assert x.top is None
  58. class test_LocalManager:
  59. def test_init(self):
  60. x = LocalManager()
  61. assert x.locals == []
  62. assert x.ident_func
  63. def ident():
  64. return 1
  65. loc = Local()
  66. x = LocalManager([loc], ident_func=ident)
  67. assert x.locals == [loc]
  68. x = LocalManager(loc, ident_func=ident)
  69. assert x.locals == [loc]
  70. assert x.ident_func is ident
  71. assert x.locals[0].__ident_func__ is ident
  72. assert x.get_ident() == 1
  73. with patch('celery.utils.threads.release_local') as release:
  74. x.cleanup()
  75. release.assert_called_with(loc)
  76. assert repr(x)