conftest.py 9.7 KB

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