conftest.py 9.8 KB

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