test_threads.py 2.4 KB

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