conftest.py 9.9 KB

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