test_threads.py 2.4 KB

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