conftest.py 9.4 KB

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