conftest.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. from __future__ import absolute_import, unicode_literals
  2. import logging
  3. import os
  4. import pytest
  5. import sys
  6. import threading
  7. import warnings
  8. from importlib import import_module
  9. from case import Mock
  10. from celery.utils.pytest import (
  11. CELERY_TEST_CONFIG, Trap, TestApp,
  12. assert_signal_called, TaskMessage, TaskMessage1, task_message_from_sig,
  13. )
  14. from celery.utils.pytest import app # noqa
  15. from celery.utils.pytest import reset_cache_backend_state # noqa
  16. from celery.utils.pytest import depends_on_current_app # noqa
  17. __all__ = ['app', 'reset_cache_backend_state', 'depends_on_current_app']
  18. try:
  19. WindowsError = WindowsError # noqa
  20. except NameError:
  21. class WindowsError(Exception):
  22. pass
  23. PYPY3 = getattr(sys, 'pypy_version_info', None) and sys.version_info[0] > 3
  24. CASE_LOG_REDIRECT_EFFECT = 'Test {0} didn\'t disable LoggingProxy for {1}'
  25. CASE_LOG_LEVEL_EFFECT = 'Test {0} modified the level of the root logger'
  26. CASE_LOG_HANDLER_EFFECT = 'Test {0} modified handlers for the root logger'
  27. @pytest.fixture(autouse=True, scope='session')
  28. def AAA_disable_multiprocessing():
  29. # pytest-cov breaks if a multiprocessing.Process is started,
  30. # so disable them completely to make sure it doesn't happen.
  31. from case import patch
  32. stuff = [
  33. 'multiprocessing.Process',
  34. 'billiard.Process',
  35. 'billiard.context.Process',
  36. 'billiard.process.Process',
  37. 'billiard.process.BaseProcess',
  38. 'multiprocessing.Process',
  39. ]
  40. ctxs = [patch(s) for s in stuff]
  41. [ctx.__enter__() for ctx in ctxs]
  42. yield
  43. [ctx.__exit__(*sys.exc_info()) for ctx in ctxs]
  44. def alive_threads():
  45. return [thread for thread in threading.enumerate() if thread.is_alive()]
  46. @pytest.fixture(autouse=True)
  47. def task_join_will_not_block():
  48. from celery import _state
  49. from celery import result
  50. prev_res_join_block = result.task_join_will_block
  51. _state.orig_task_join_will_block = _state.task_join_will_block
  52. prev_state_join_block = _state.task_join_will_block
  53. result.task_join_will_block = \
  54. _state.task_join_will_block = lambda: False
  55. _state._set_task_join_will_block(False)
  56. yield
  57. result.task_join_will_block = prev_res_join_block
  58. _state.task_join_will_block = prev_state_join_block
  59. _state._set_task_join_will_block(False)
  60. @pytest.fixture(scope='session', autouse=True)
  61. def record_threads_at_startup(request):
  62. try:
  63. request.session._threads_at_startup
  64. except AttributeError:
  65. request.session._threads_at_startup = alive_threads()
  66. @pytest.fixture(autouse=True)
  67. def threads_not_lingering(request):
  68. yield
  69. assert request.session._threads_at_startup == alive_threads()
  70. @pytest.fixture(autouse=True)
  71. def test_cases_shortcuts(request, app, patching):
  72. if request.instance:
  73. @app.task
  74. def add(x, y):
  75. return x + y
  76. # IMPORTANT: We set an .app attribute for every test case class.
  77. request.instance.app = app
  78. request.instance.Celery = TestApp
  79. request.instance.assert_signal_called = assert_signal_called
  80. request.instance.task_message_from_sig = task_message_from_sig
  81. request.instance.TaskMessage = TaskMessage
  82. request.instance.TaskMessage1 = TaskMessage1
  83. request.instance.CELERY_TEST_CONFIG = dict(CELERY_TEST_CONFIG)
  84. request.instance.add = add
  85. request.instance.patching = patching
  86. yield
  87. if request.instance:
  88. request.instance.app = None
  89. @pytest.fixture(autouse=True)
  90. def zzzz_test_cases_calls_setup_teardown(request):
  91. if request.instance:
  92. # we set the .patching attribute for every test class.
  93. setup = getattr(request.instance, 'setup', None)
  94. # we also call .setup() and .teardown() after every test method.
  95. setup and setup()
  96. yield
  97. if request.instance:
  98. teardown = getattr(request.instance, 'teardown', None)
  99. teardown and teardown()
  100. @pytest.fixture(autouse=True)
  101. def sanity_no_shutdown_flags_set():
  102. yield
  103. # Make sure no test left the shutdown flags enabled.
  104. from celery.worker import state as worker_state
  105. # check for EX_OK
  106. assert worker_state.should_stop is not False
  107. assert worker_state.should_terminate is not False
  108. # check for other true values
  109. assert not worker_state.should_stop
  110. assert not worker_state.should_terminate
  111. @pytest.fixture(autouse=True)
  112. def sanity_stdouts(request):
  113. yield
  114. from celery.utils.log import LoggingProxy
  115. assert sys.stdout
  116. assert sys.stderr
  117. assert sys.__stdout__
  118. assert sys.__stderr__
  119. this = request.node.name
  120. if isinstance(sys.stdout, (LoggingProxy, Mock)) or \
  121. isinstance(sys.__stdout__, (LoggingProxy, Mock)):
  122. raise RuntimeError(CASE_LOG_REDIRECT_EFFECT.format(this, 'stdout'))
  123. if isinstance(sys.stderr, (LoggingProxy, Mock)) or \
  124. isinstance(sys.__stderr__, (LoggingProxy, Mock)):
  125. raise RuntimeError(CASE_LOG_REDIRECT_EFFECT.format(this, 'stderr'))
  126. @pytest.fixture(autouse=True)
  127. def sanity_logging_side_effects(request):
  128. root = logging.getLogger()
  129. rootlevel = root.level
  130. roothandlers = root.handlers
  131. yield
  132. this = request.node.name
  133. root_now = logging.getLogger()
  134. if root_now.level != rootlevel:
  135. raise RuntimeError(CASE_LOG_LEVEL_EFFECT.format(this))
  136. if root_now.handlers != roothandlers:
  137. raise RuntimeError(CASE_LOG_HANDLER_EFFECT.format(this))
  138. def setup_session(scope='session'):
  139. using_coverage = (
  140. os.environ.get('COVER_ALL_MODULES') or '--with-coverage' in sys.argv
  141. )
  142. os.environ.update(
  143. # warn if config module not found
  144. C_WNOCONF='yes',
  145. KOMBU_DISABLE_LIMIT_PROTECTION='yes',
  146. )
  147. if using_coverage and not PYPY3:
  148. from warnings import catch_warnings
  149. with catch_warnings(record=True):
  150. import_all_modules()
  151. warnings.resetwarnings()
  152. from celery._state import set_default_app
  153. set_default_app(Trap())
  154. def teardown():
  155. # Don't want SUBDEBUG log messages at finalization.
  156. try:
  157. from multiprocessing.util import get_logger
  158. except ImportError:
  159. pass
  160. else:
  161. get_logger().setLevel(logging.WARNING)
  162. # Make sure test database is removed.
  163. import os
  164. if os.path.exists('test.db'):
  165. try:
  166. os.remove('test.db')
  167. except WindowsError:
  168. pass
  169. # Make sure there are no remaining threads at shutdown.
  170. import threading
  171. remaining_threads = [thread for thread in threading.enumerate()
  172. if thread.getName() != 'MainThread']
  173. if remaining_threads:
  174. sys.stderr.write(
  175. '\n\n**WARNING**: Remaining threads at teardown: %r...\n' % (
  176. remaining_threads))
  177. def find_distribution_modules(name=__name__, file=__file__):
  178. current_dist_depth = len(name.split('.')) - 1
  179. current_dist = os.path.join(os.path.dirname(file),
  180. *([os.pardir] * current_dist_depth))
  181. abs = os.path.abspath(current_dist)
  182. dist_name = os.path.basename(abs)
  183. for dirpath, dirnames, filenames in os.walk(abs):
  184. package = (dist_name + dirpath[len(abs):]).replace('/', '.')
  185. if '__init__.py' in filenames:
  186. yield package
  187. for filename in filenames:
  188. if filename.endswith('.py') and filename != '__init__.py':
  189. yield '.'.join([package, filename])[:-3]
  190. def import_all_modules(name=__name__, file=__file__,
  191. skip=('celery.decorators',
  192. 'celery.task')):
  193. for module in find_distribution_modules(name, file):
  194. if not module.startswith(skip):
  195. try:
  196. import_module(module)
  197. except ImportError:
  198. pass
  199. except OSError as exc:
  200. warnings.warn(UserWarning(
  201. 'Ignored error importing module {0}: {1!r}'.format(
  202. module, exc,
  203. )))