conftest.py 9.7 KB

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