conftest.py 9.4 KB

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