| 1 |
import builtins |
| 2 |
import inspect |
| 3 |
import io |
| 4 |
import logging |
| 5 |
import os |
| 6 |
import platform |
| 7 |
import sys |
| 8 |
import threading |
| 9 |
import types |
| 10 |
import warnings |
| 11 |
from contextlib import contextmanager |
| 12 |
from functools import wraps |
| 13 |
from importlib import import_module, reload |
| 14 |
from unittest.mock import MagicMock, Mock, patch |
| 15 |
|
| 16 |
import pytest |
| 17 |
from kombu import Queue |
| 18 |
|
| 19 |
from celery.backends.cache import CacheBackend, DummyClient |
| 20 |
# we have to import the pytest plugin fixtures here, |
| 21 |
# in case user did not do the `python setup.py develop` yet, |
| 22 |
# that installs the pytest plugin into the setuptools registry. |
| 23 |
from celery.contrib.pytest import celery_app, celery_enable_logging, celery_parameters, depends_on_current_app |
| 24 |
from celery.contrib.testing.app import TestApp, Trap |
| 25 |
from celery.contrib.testing.mocks import TaskMessage, TaskMessage1, task_message_from_sig |
| 26 |
|
| 27 |
# Tricks flake8 into silencing redefining fixtures warnings. |
| 28 |
__all__ = ( |
| 29 |
'celery_app', 'celery_enable_logging', 'depends_on_current_app', |
| 30 |
'celery_parameters' |
| 31 |
) |
| 32 |
|
| 33 |
|
| 34 |
PYPY3 = getattr(sys, 'pypy_version_info', None) and sys.version_info[0] > 3 |
| 35 |
|
| 36 |
CASE_LOG_REDIRECT_EFFECT = 'Test {0} didn\'t disable LoggingProxy for {1}' |
| 37 |
CASE_LOG_LEVEL_EFFECT = 'Test {0} modified the level of the root logger' |
| 38 |
CASE_LOG_HANDLER_EFFECT = 'Test {0} modified handlers for the root logger' |
| 39 |
|
| 40 |
_SIO_write = io.StringIO.write |
| 41 |
_SIO_init = io.StringIO.__init__ |
| 42 |
|
| 43 |
SENTINEL = object() |
| 44 |
|
| 45 |
|
| 46 |
def noop(*args, **kwargs): |
| 47 |
pass |
| 48 |
|
| 49 |
|
| 50 |
class WhateverIO(io.StringIO): |
| 51 |
|
| 52 |
def __init__(self, v=None, *a, **kw): |
| 53 |
_SIO_init(self, v.decode() if isinstance(v, bytes) else v, *a, **kw) |
| 54 |
|
| 55 |
def write(self, data): |
| 56 |
_SIO_write(self, data.decode() if isinstance(data, bytes) else data) |
| 57 |
|
| 58 |
|
| 59 |
@pytest.fixture(scope='session') |
| 60 |
def celery_config(): |
| 61 |
return { |
| 62 |
'broker_url': 'memory://', |
| 63 |
'broker_transport_options': { |
| 64 |
'polling_interval': 0.1 |
| 65 |
}, |
| 66 |
'result_backend': 'cache+memory://', |
| 67 |
'task_default_queue': 'testcelery', |
| 68 |
'task_default_exchange': 'testcelery', |
| 69 |
'task_default_routing_key': 'testcelery', |
| 70 |
'task_queues': ( |
| 71 |
Queue('testcelery', routing_key='testcelery'), |
| 72 |
), |
| 73 |
'accept_content': ('json', 'pickle'), |
| 74 |
|
| 75 |
# Mongo results tests (only executed if installed and running) |
| 76 |
'mongodb_backend_settings': { |
| 77 |
'host': os.environ.get('MONGO_HOST') or 'localhost', |
| 78 |
'port': os.environ.get('MONGO_PORT') or 27017, |
| 79 |
'database': os.environ.get('MONGO_DB') or 'celery_unittests', |
| 80 |
'taskmeta_collection': ( |
| 81 |
os.environ.get('MONGO_TASKMETA_COLLECTION') or |
| 82 |
'taskmeta_collection' |
| 83 |
), |
| 84 |
'user': os.environ.get('MONGO_USER'), |
| 85 |
'password': os.environ.get('MONGO_PASSWORD'), |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
|
| 90 |
@pytest.fixture(scope='session') |
| 91 |
def use_celery_app_trap(): |
| 92 |
return True |
| 93 |
|
| 94 |
|
| 95 |
@pytest.fixture(autouse=True) |
| 96 |
def reset_cache_backend_state(celery_app): |
| 97 |
"""Fixture that resets the internal state of the cache result backend.""" |
| 98 |
yield |
| 99 |
backend = celery_app.__dict__.get('backend') |
| 100 |
if backend is not None: |
| 101 |
if isinstance(backend, CacheBackend): |
| 102 |
if isinstance(backend.client, DummyClient): |
| 103 |
backend.client.cache.clear() |
| 104 |
backend._cache.clear() |
| 105 |
|
| 106 |
|
| 107 |
@contextmanager |
| 108 |
def assert_signal_called(signal, **expected): |
| 109 |
"""Context that verifies signal is called before exiting.""" |
| 110 |
handler = Mock() |
| 111 |
|
| 112 |
def on_call(**kwargs): |
| 113 |
return handler(**kwargs) |
| 114 |
|
| 115 |
signal.connect(on_call) |
| 116 |
try: |
| 117 |
yield handler |
| 118 |
finally: |
| 119 |
signal.disconnect(on_call) |
| 120 |
handler.assert_called_with(signal=signal, **expected) |
| 121 |
|
| 122 |
|
| 123 |
@pytest.fixture |
| 124 |
def app(celery_app): |
| 125 |
yield celery_app |
| 126 |
|
| 127 |
|
| 128 |
@pytest.fixture(autouse=True, scope='session') |
| 129 |
def AAA_disable_multiprocessing(): |
| 130 |
# pytest-cov breaks if a multiprocessing.Process is started, |
| 131 |
# so disable them completely to make sure it doesn't happen. |
| 132 |
stuff = [ |
| 133 |
'multiprocessing.Process', |
| 134 |
'billiard.Process', |
| 135 |
'billiard.context.Process', |
| 136 |
'billiard.process.Process', |
| 137 |
'billiard.process.BaseProcess', |
| 138 |
'multiprocessing.Process', |
| 139 |
] |
| 140 |
ctxs = [patch(s) for s in stuff] |
| 141 |
[ctx.__enter__() for ctx in ctxs] |
| 142 |
|
| 143 |
yield |
| 144 |
|
| 145 |
[ctx.__exit__(*sys.exc_info()) for ctx in ctxs] |
| 146 |
|
| 147 |
|
| 148 |
def alive_threads(): |
| 149 |
return [ |
| 150 |
thread |
| 151 |
for thread in threading.enumerate() |
| 152 |
if not thread.name.startswith("pytest_timeout ") and thread.is_alive() |
| 153 |
] |
| 154 |
|
| 155 |
|
| 156 |
@pytest.fixture(autouse=True) |
| 157 |
def task_join_will_not_block(): |
| 158 |
from celery import _state, result |
| 159 |
prev_res_join_block = result.task_join_will_block |
| 160 |
_state.orig_task_join_will_block = _state.task_join_will_block |
| 161 |
prev_state_join_block = _state.task_join_will_block |
| 162 |
result.task_join_will_block = \ |
| 163 |
_state.task_join_will_block = lambda: False |
| 164 |
_state._set_task_join_will_block(False) |
| 165 |
|
| 166 |
yield |
| 167 |
|
| 168 |
result.task_join_will_block = prev_res_join_block |
| 169 |
_state.task_join_will_block = prev_state_join_block |
| 170 |
_state._set_task_join_will_block(False) |
| 171 |
|
| 172 |
|
| 173 |
@pytest.fixture(scope='session', autouse=True) |
| 174 |
def record_threads_at_startup(request): |
| 175 |
try: |
| 176 |
request.session._threads_at_startup |
| 177 |
except AttributeError: |
| 178 |
request.session._threads_at_startup = alive_threads() |
| 179 |
|
| 180 |
|
| 181 |
@pytest.fixture(autouse=True) |
| 182 |
def threads_not_lingering(request): |
| 183 |
yield |
| 184 |
assert request.session._threads_at_startup == alive_threads() |
| 185 |
|
| 186 |
|
| 187 |
@pytest.fixture(autouse=True) |
| 188 |
def AAA_reset_CELERY_LOADER_env(): |
| 189 |
yield |
| 190 |
assert not os.environ.get('CELERY_LOADER') |
| 191 |
|
| 192 |
|
| 193 |
@pytest.fixture(autouse=True) |
| 194 |
def test_cases_shortcuts(request, app, patching, celery_config): |
| 195 |
if request.instance: |
| 196 |
@app.task |
| 197 |
def add(x, y): |
| 198 |
return x + y |
| 199 |
|
| 200 |
# IMPORTANT: We set an .app attribute for every test case class. |
| 201 |
request.instance.app = app |
| 202 |
request.instance.Celery = TestApp |
| 203 |
request.instance.assert_signal_called = assert_signal_called |
| 204 |
request.instance.task_message_from_sig = task_message_from_sig |
| 205 |
request.instance.TaskMessage = TaskMessage |
| 206 |
request.instance.TaskMessage1 = TaskMessage1 |
| 207 |
request.instance.CELERY_TEST_CONFIG = celery_config |
| 208 |
request.instance.add = add |
| 209 |
request.instance.patching = patching |
| 210 |
yield |
| 211 |
if request.instance: |
| 212 |
request.instance.app = None |
| 213 |
|
| 214 |
|
| 215 |
@pytest.fixture(autouse=True) |
| 216 |
def sanity_no_shutdown_flags_set(): |
| 217 |
yield |
| 218 |
|
| 219 |
# Make sure no test left the shutdown flags enabled. |
| 220 |
from celery.worker import state as worker_state |
| 221 |
|
| 222 |
# check for EX_OK |
| 223 |
assert worker_state.should_stop is not False |
| 224 |
assert worker_state.should_terminate is not False |
| 225 |
# check for other true values |
| 226 |
assert not worker_state.should_stop |
| 227 |
assert not worker_state.should_terminate |
| 228 |
|
| 229 |
|
| 230 |
@pytest.fixture(autouse=True) |
| 231 |
def sanity_stdouts(request): |
| 232 |
yield |
| 233 |
|
| 234 |
from celery.utils.log import LoggingProxy |
| 235 |
assert sys.stdout |
| 236 |
assert sys.stderr |
| 237 |
assert sys.__stdout__ |
| 238 |
assert sys.__stderr__ |
| 239 |
this = request.node.name |
| 240 |
if isinstance(sys.stdout, (LoggingProxy, Mock)) or \ |
| 241 |
isinstance(sys.__stdout__, (LoggingProxy, Mock)): |
| 242 |
raise RuntimeError(CASE_LOG_REDIRECT_EFFECT.format(this, 'stdout')) |
| 243 |
if isinstance(sys.stderr, (LoggingProxy, Mock)) or \ |
| 244 |
isinstance(sys.__stderr__, (LoggingProxy, Mock)): |
| 245 |
raise RuntimeError(CASE_LOG_REDIRECT_EFFECT.format(this, 'stderr')) |
| 246 |
|
| 247 |
|
| 248 |
@pytest.fixture(autouse=True) |
| 249 |
def sanity_logging_side_effects(request): |
| 250 |
from _pytest.logging import LogCaptureHandler |
| 251 |
root = logging.getLogger() |
| 252 |
rootlevel = root.level |
| 253 |
roothandlers = [ |
| 254 |
x for x in root.handlers if not isinstance(x, LogCaptureHandler)] |
| 255 |
|
| 256 |
yield |
| 257 |
|
| 258 |
this = request.node.name |
| 259 |
root_now = logging.getLogger() |
| 260 |
if root_now.level != rootlevel: |
| 261 |
raise RuntimeError(CASE_LOG_LEVEL_EFFECT.format(this)) |
| 262 |
newhandlers = [x for x in root_now.handlers if not isinstance( |
| 263 |
x, LogCaptureHandler)] |
| 264 |
if newhandlers != roothandlers: |
| 265 |
raise RuntimeError(CASE_LOG_HANDLER_EFFECT.format(this)) |
| 266 |
|
| 267 |
|
| 268 |
def setup_session(scope='session'): |
| 269 |
using_coverage = ( |
| 270 |
os.environ.get('COVER_ALL_MODULES') or '--with-coverage' in sys.argv |
| 271 |
) |
| 272 |
os.environ.update( |
| 273 |
# warn if config module not found |
| 274 |
C_WNOCONF='yes', |
| 275 |
KOMBU_DISABLE_LIMIT_PROTECTION='yes', |
| 276 |
) |
| 277 |
|
| 278 |
if using_coverage and not PYPY3: |
| 279 |
from warnings import catch_warnings |
| 280 |
with catch_warnings(record=True): |
| 281 |
import_all_modules() |
| 282 |
warnings.resetwarnings() |
| 283 |
from celery._state import set_default_app |
| 284 |
set_default_app(Trap()) |
| 285 |
|
| 286 |
|
| 287 |
def teardown(): |
| 288 |
# Don't want SUBDEBUG log messages at finalization. |
| 289 |
try: |
| 290 |
from multiprocessing.util import get_logger |
| 291 |
except ImportError: |
| 292 |
pass |
| 293 |
else: |
| 294 |
get_logger().setLevel(logging.WARNING) |
| 295 |
|
| 296 |
# Make sure test database is removed. |
| 297 |
import os |
| 298 |
if os.path.exists('test.db'): |
| 299 |
try: |
| 300 |
os.remove('test.db') |
| 301 |
except OSError: |
| 302 |
pass |
| 303 |
|
| 304 |
# Make sure there are no remaining threads at shutdown. |
| 305 |
import threading |
| 306 |
remaining_threads = [thread for thread in threading.enumerate() |
| 307 |
if thread.getName() != 'MainThread'] |
| 308 |
if remaining_threads: |
| 309 |
sys.stderr.write( |
| 310 |
'\n\n**WARNING**: Remaining threads at teardown: %r...\n' % ( |
| 311 |
remaining_threads)) |
| 312 |
|
| 313 |
|
| 314 |
def find_distribution_modules(name=__name__, file=__file__): |
| 315 |
current_dist_depth = len(name.split('.')) - 1 |
| 316 |
current_dist = os.path.join(os.path.dirname(file), |
| 317 |
*([os.pardir] * current_dist_depth)) |
| 318 |
abs = os.path.abspath(current_dist) |
| 319 |
dist_name = os.path.basename(abs) |
| 320 |
|
| 321 |
for dirpath, dirnames, filenames in os.walk(abs): |
| 322 |
package = (dist_name + dirpath[len(abs):]).replace('/', '.') |
| 323 |
if '__init__.py' in filenames: |
| 324 |
yield package |
| 325 |
for filename in filenames: |
| 326 |
if filename.endswith('.py') and filename != '__init__.py': |
| 327 |
yield '.'.join([package, filename])[:-3] |
| 328 |
|
| 329 |
|
| 330 |
def import_all_modules(name=__name__, file=__file__, |
| 331 |
skip=('celery.decorators', |
| 332 |
'celery.task')): |
| 333 |
for module in find_distribution_modules(name, file): |
| 334 |
if not module.startswith(skip): |
| 335 |
try: |
| 336 |
import_module(module) |
| 337 |
except ImportError: |
| 338 |
pass |
| 339 |
except OSError as exc: |
| 340 |
warnings.warn(UserWarning( |
| 341 |
'Ignored error importing module {}: {!r}'.format( |
| 342 |
module, exc, |
| 343 |
))) |
| 344 |
|
| 345 |
|
| 346 |
@pytest.fixture |
| 347 |
def sleepdeprived(request): |
| 348 |
"""Mock sleep method in patched module to do nothing. |
| 349 |
|
| 350 |
Example: |
| 351 |
>>> import time |
| 352 |
>>> @pytest.mark.sleepdeprived_patched_module(time) |
| 353 |
>>> def test_foo(self, sleepdeprived): |
| 354 |
>>> pass |
| 355 |
""" |
| 356 |
module = request.node.get_closest_marker( |
| 357 |
"sleepdeprived_patched_module").args[0] |
| 358 |
old_sleep, module.sleep = module.sleep, noop |
| 359 |
try: |
| 360 |
yield |
| 361 |
finally: |
| 362 |
module.sleep = old_sleep |
| 363 |
|
| 364 |
|
| 365 |
# Taken from |
| 366 |
# http://bitbucket.org/runeh/snippets/src/tip/missing_modules.py |
| 367 |
@pytest.fixture |
| 368 |
def mask_modules(request): |
| 369 |
"""Ban some modules from being importable inside the context |
| 370 |
For example:: |
| 371 |
>>> @pytest.mark.masked_modules('gevent.monkey') |
| 372 |
>>> def test_foo(self, mask_modules): |
| 373 |
... try: |
| 374 |
... import sys |
| 375 |
... except ImportError: |
| 376 |
... print('sys not found') |
| 377 |
sys not found |
| 378 |
""" |
| 379 |
realimport = builtins.__import__ |
| 380 |
modnames = request.node.get_closest_marker("masked_modules").args |
| 381 |
|
| 382 |
def myimp(name, *args, **kwargs): |
| 383 |
if name in modnames: |
| 384 |
raise ImportError('No module named %s' % name) |
| 385 |
else: |
| 386 |
return realimport(name, *args, **kwargs) |
| 387 |
|
| 388 |
builtins.__import__ = myimp |
| 389 |
try: |
| 390 |
yield |
| 391 |
finally: |
| 392 |
builtins.__import__ = realimport |
| 393 |
|
| 394 |
|
| 395 |
@pytest.fixture |
| 396 |
def environ(request): |
| 397 |
"""Mock environment variable value. |
| 398 |
Example:: |
| 399 |
>>> @pytest.mark.patched_environ('DJANGO_SETTINGS_MODULE', 'proj.settings') |
| 400 |
>>> def test_other_settings(self, environ): |
| 401 |
... ... |
| 402 |
""" |
| 403 |
env_name, env_value = request.node.get_closest_marker("patched_environ").args |
| 404 |
prev_val = os.environ.get(env_name, SENTINEL) |
| 405 |
os.environ[env_name] = env_value |
| 406 |
try: |
| 407 |
yield |
| 408 |
finally: |
| 409 |
if prev_val is SENTINEL: |
| 410 |
os.environ.pop(env_name, None) |
| 411 |
else: |
| 412 |
os.environ[env_name] = prev_val |
| 413 |
|
| 414 |
|
| 415 |
def replace_module_value(module, name, value=None): |
| 416 |
"""Mock module value, given a module, attribute name and value. |
| 417 |
|
| 418 |
Example:: |
| 419 |
|
| 420 |
>>> replace_module_value(module, 'CONSTANT', 3.03) |
| 421 |
""" |
| 422 |
has_prev = hasattr(module, name) |
| 423 |
prev = getattr(module, name, None) |
| 424 |
if value: |
| 425 |
setattr(module, name, value) |
| 426 |
else: |
| 427 |
try: |
| 428 |
delattr(module, name) |
| 429 |
except AttributeError: |
| 430 |
pass |
| 431 |
try: |
| 432 |
yield |
| 433 |
finally: |
| 434 |
if prev is not None: |
| 435 |
setattr(module, name, prev) |
| 436 |
if not has_prev: |
| 437 |
try: |
| 438 |
delattr(module, name) |
| 439 |
except AttributeError: |
| 440 |
pass |
| 441 |
|
| 442 |
|
| 443 |
@contextmanager |
| 444 |
def platform_pyimp(value=None): |
| 445 |
"""Mock :data:`platform.python_implementation` |
| 446 |
Example:: |
| 447 |
>>> with platform_pyimp('PyPy'): |
| 448 |
... ... |
| 449 |
""" |
| 450 |
yield from replace_module_value(platform, 'python_implementation', value) |
| 451 |
|
| 452 |
|
| 453 |
@contextmanager |
| 454 |
def sys_platform(value=None): |
| 455 |
"""Mock :data:`sys.platform` |
| 456 |
|
| 457 |
Example:: |
| 458 |
>>> mock.sys_platform('darwin'): |
| 459 |
... ... |
| 460 |
""" |
| 461 |
prev, sys.platform = sys.platform, value |
| 462 |
try: |
| 463 |
yield |
| 464 |
finally: |
| 465 |
sys.platform = prev |
| 466 |
|
| 467 |
|
| 468 |
@contextmanager |
| 469 |
def pypy_version(value=None): |
| 470 |
"""Mock :data:`sys.pypy_version_info` |
| 471 |
|
| 472 |
Example:: |
| 473 |
>>> with pypy_version((3, 6, 1)): |
| 474 |
... ... |
| 475 |
""" |
| 476 |
yield from replace_module_value(sys, 'pypy_version_info', value) |
| 477 |
|
| 478 |
|
| 479 |
def _restore_logging(): |
| 480 |
outs = sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__ |
| 481 |
root = logging.getLogger() |
| 482 |
level = root.level |
| 483 |
handlers = root.handlers |
| 484 |
|
| 485 |
try: |
| 486 |
yield |
| 487 |
finally: |
| 488 |
sys.stdout, sys.stderr, sys.__stdout__, sys.__stderr__ = outs |
| 489 |
root.level = level |
| 490 |
root.handlers[:] = handlers |
| 491 |
|
| 492 |
|
| 493 |
@contextmanager |
| 494 |
def restore_logging_context_manager(): |
| 495 |
"""Restore root logger handlers after test returns. |
| 496 |
Example:: |
| 497 |
>>> with restore_logging_context_manager(): |
| 498 |
... setup_logging() |
| 499 |
""" |
| 500 |
yield from _restore_logging() |
| 501 |
|
| 502 |
|
| 503 |
@pytest.fixture |
| 504 |
def restore_logging(request): |
| 505 |
"""Restore root logger handlers after test returns. |
| 506 |
Example:: |
| 507 |
>>> def test_foo(self, restore_logging): |
| 508 |
... setup_logging() |
| 509 |
""" |
| 510 |
yield from _restore_logging() |
| 511 |
|
| 512 |
|
| 513 |
@pytest.fixture |
| 514 |
def module(request): |
| 515 |
"""Mock one or modules such that every attribute is a :class:`Mock`.""" |
| 516 |
yield from _module(*request.node.get_closest_marker("patched_module").args) |
| 517 |
|
| 518 |
|
| 519 |
@contextmanager |
| 520 |
def module_context_manager(*names): |
| 521 |
"""Mock one or modules such that every attribute is a :class:`Mock`.""" |
| 522 |
yield from _module(*names) |
| 523 |
|
| 524 |
|
| 525 |
def _module(*names): |
| 526 |
prev = {} |
| 527 |
|
| 528 |
class MockModule(types.ModuleType): |
| 529 |
|
| 530 |
def __getattr__(self, attr): |
| 531 |
setattr(self, attr, Mock()) |
| 532 |
return types.ModuleType.__getattribute__(self, attr) |
| 533 |
|
| 534 |
mods = [] |
| 535 |
for name in names: |
| 536 |
try: |
| 537 |
prev[name] = sys.modules[name] |
| 538 |
except KeyError: |
| 539 |
pass |
| 540 |
mod = sys.modules[name] = MockModule(name) |
| 541 |
mods.append(mod) |
| 542 |
try: |
| 543 |
yield mods |
| 544 |
finally: |
| 545 |
for name in names: |
| 546 |
try: |
| 547 |
sys.modules[name] = prev[name] |
| 548 |
except KeyError: |
| 549 |
try: |
| 550 |
del (sys.modules[name]) |
| 551 |
except KeyError: |
| 552 |
pass |
| 553 |
|
| 554 |
|
| 555 |
class _patching: |
| 556 |
|
| 557 |
def __init__(self, monkeypatch, request): |
| 558 |
self.monkeypatch = monkeypatch |
| 559 |
self.request = request |
| 560 |
|
| 561 |
def __getattr__(self, name): |
| 562 |
return getattr(self.monkeypatch, name) |
| 563 |
|
| 564 |
def __call__(self, path, value=SENTINEL, name=None, |
| 565 |
new=MagicMock, **kwargs): |
| 566 |
value = self._value_or_mock(value, new, name, path, **kwargs) |
| 567 |
self.monkeypatch.setattr(path, value) |
| 568 |
return value |
| 569 |
|
| 570 |
def object(self, target, attribute, *args, **kwargs): |
| 571 |
return _wrap_context( |
| 572 |
patch.object(target, attribute, *args, **kwargs), |
| 573 |
self.request) |
| 574 |
|
| 575 |
def _value_or_mock(self, value, new, name, path, **kwargs): |
| 576 |
if value is SENTINEL: |
| 577 |
value = new(name=name or path.rpartition('.')[2]) |
| 578 |
for k, v in kwargs.items(): |
| 579 |
setattr(value, k, v) |
| 580 |
return value |
| 581 |
|
| 582 |
def setattr(self, target, name=SENTINEL, value=SENTINEL, **kwargs): |
| 583 |
# alias to __call__ with the interface of pytest.monkeypatch.setattr |
| 584 |
if value is SENTINEL: |
| 585 |
value, name = name, None |
| 586 |
return self(target, value, name=name) |
| 587 |
|
| 588 |
def setitem(self, dic, name, value=SENTINEL, new=MagicMock, **kwargs): |
| 589 |
# same as pytest.monkeypatch.setattr but default value is MagicMock |
| 590 |
value = self._value_or_mock(value, new, name, dic, **kwargs) |
| 591 |
self.monkeypatch.setitem(dic, name, value) |
| 592 |
return value |
| 593 |
|
| 594 |
def modules(self, *mods): |
| 595 |
modules = [] |
| 596 |
for mod in mods: |
| 597 |
mod = mod.split('.') |
| 598 |
modules.extend(reversed([ |
| 599 |
'.'.join(mod[:-i] if i else mod) for i in range(len(mod)) |
| 600 |
])) |
| 601 |
modules = sorted(set(modules)) |
| 602 |
return _wrap_context(module_context_manager(*modules), self.request) |
| 603 |
|
| 604 |
|
| 605 |
def _wrap_context(context, request): |
| 606 |
ret = context.__enter__() |
| 607 |
|
| 608 |
def fin(): |
| 609 |
context.__exit__(*sys.exc_info()) |
| 610 |
request.addfinalizer(fin) |
| 611 |
return ret |
| 612 |
|
| 613 |
|
| 614 |
@pytest.fixture() |
| 615 |
def patching(monkeypatch, request): |
| 616 |
"""Monkeypath.setattr shortcut. |
| 617 |
Example: |
| 618 |
.. code-block:: python |
| 619 |
>>> def test_foo(patching): |
| 620 |
>>> # execv value here will be mock.MagicMock by default. |
| 621 |
>>> execv = patching('os.execv') |
| 622 |
>>> patching('sys.platform', 'darwin') # set concrete value |
| 623 |
>>> patching.setenv('DJANGO_SETTINGS_MODULE', 'x.settings') |
| 624 |
>>> # val will be of type mock.MagicMock by default |
| 625 |
>>> val = patching.setitem('path.to.dict', 'KEY') |
| 626 |
""" |
| 627 |
return _patching(monkeypatch, request) |
| 628 |
|
| 629 |
|
| 630 |
@contextmanager |
| 631 |
def stdouts(): |
| 632 |
"""Override `sys.stdout` and `sys.stderr` with `StringIO` |
| 633 |
instances. |
| 634 |
>>> with conftest.stdouts() as (stdout, stderr): |
| 635 |
... something() |
| 636 |
... self.assertIn('foo', stdout.getvalue()) |
| 637 |
""" |
| 638 |
prev_out, prev_err = sys.stdout, sys.stderr |
| 639 |
prev_rout, prev_rerr = sys.__stdout__, sys.__stderr__ |
| 640 |
mystdout, mystderr = WhateverIO(), WhateverIO() |
| 641 |
sys.stdout = sys.__stdout__ = mystdout |
| 642 |
sys.stderr = sys.__stderr__ = mystderr |
| 643 |
|
| 644 |
try: |
| 645 |
yield mystdout, mystderr |
| 646 |
finally: |
| 647 |
sys.stdout = prev_out |
| 648 |
sys.stderr = prev_err |
| 649 |
sys.__stdout__ = prev_rout |
| 650 |
sys.__stderr__ = prev_rerr |
| 651 |
|
| 652 |
|
| 653 |
@contextmanager |
| 654 |
def reset_modules(*modules): |
| 655 |
"""Remove modules from :data:`sys.modules` by name, |
| 656 |
and reset back again when the test/context returns. |
| 657 |
Example:: |
| 658 |
>>> with conftest.reset_modules('celery.result', 'celery.app.base'): |
| 659 |
... pass |
| 660 |
""" |
| 661 |
prev = { |
| 662 |
k: sys.modules.pop(k) for k in modules if k in sys.modules |
| 663 |
} |
| 664 |
|
| 665 |
try: |
| 666 |
for k in modules: |
| 667 |
reload(import_module(k)) |
| 668 |
yield |
| 669 |
finally: |
| 670 |
sys.modules.update(prev) |
| 671 |
|
| 672 |
|
| 673 |
def get_logger_handlers(logger): |
| 674 |
return [ |
| 675 |
h for h in logger.handlers |
| 676 |
if not isinstance(h, logging.NullHandler) |
| 677 |
] |
| 678 |
|
| 679 |
|
| 680 |
@contextmanager |
| 681 |
def wrap_logger(logger, loglevel=logging.ERROR): |
| 682 |
"""Wrap :class:`logging.Logger` with a StringIO() handler. |
| 683 |
yields a StringIO handle. |
| 684 |
Example:: |
| 685 |
>>> with conftest.wrap_logger(logger, loglevel=logging.DEBUG) as sio: |
| 686 |
... ... |
| 687 |
... sio.getvalue() |
| 688 |
""" |
| 689 |
old_handlers = get_logger_handlers(logger) |
| 690 |
sio = WhateverIO() |
| 691 |
siohandler = logging.StreamHandler(sio) |
| 692 |
logger.handlers = [siohandler] |
| 693 |
|
| 694 |
try: |
| 695 |
yield sio |
| 696 |
finally: |
| 697 |
logger.handlers = old_handlers |
| 698 |
|
| 699 |
|
| 700 |
@contextmanager |
| 701 |
def _mock_context(mock): |
| 702 |
context = mock.return_value = Mock() |
| 703 |
context.__enter__ = Mock() |
| 704 |
context.__exit__ = Mock() |
| 705 |
|
| 706 |
def on_exit(*x): |
| 707 |
if x[0]: |
| 708 |
raise x[0] from x[1] |
| 709 |
context.__exit__.side_effect = on_exit |
| 710 |
context.__enter__.return_value = context |
| 711 |
try: |
| 712 |
yield context |
| 713 |
finally: |
| 714 |
context.reset() |
| 715 |
|
| 716 |
|
| 717 |
@contextmanager |
| 718 |
def open(side_effect=None): |
| 719 |
"""Patch builtins.open so that it returns StringIO object. |
| 720 |
:param side_effect: Additional side effect for when the open context |
| 721 |
is entered. |
| 722 |
Example:: |
| 723 |
>>> with mock.open(io.BytesIO) as open_fh: |
| 724 |
... something_opening_and_writing_bytes_to_a_file() |
| 725 |
... self.assertIn(b'foo', open_fh.getvalue()) |
| 726 |
""" |
| 727 |
with patch('builtins.open') as open_: |
| 728 |
with _mock_context(open_) as context: |
| 729 |
if side_effect is not None: |
| 730 |
context.__enter__.side_effect = side_effect |
| 731 |
val = context.__enter__.return_value = WhateverIO() |
| 732 |
val.__exit__ = Mock() |
| 733 |
yield val |
| 734 |
|
| 735 |
|
| 736 |
@contextmanager |
| 737 |
def module_exists(*modules): |
| 738 |
"""Patch one or more modules to ensure they exist. |
| 739 |
A module name with multiple paths (e.g. gevent.monkey) will |
| 740 |
ensure all parent modules are also patched (``gevent`` + |
| 741 |
``gevent.monkey``). |
| 742 |
Example:: |
| 743 |
>>> with conftest.module_exists('gevent.monkey'): |
| 744 |
... gevent.monkey.patch_all = Mock(name='patch_all') |
| 745 |
... ... |
| 746 |
""" |
| 747 |
gen = [] |
| 748 |
old_modules = [] |
| 749 |
for module in modules: |
| 750 |
if isinstance(module, str): |
| 751 |
module = types.ModuleType(module) |
| 752 |
gen.append(module) |
| 753 |
if module.__name__ in sys.modules: |
| 754 |
old_modules.append(sys.modules[module.__name__]) |
| 755 |
sys.modules[module.__name__] = module |
| 756 |
name = module.__name__ |
| 757 |
if '.' in name: |
| 758 |
parent, _, attr = name.rpartition('.') |
| 759 |
setattr(sys.modules[parent], attr, module) |
| 760 |
try: |
| 761 |
yield |
| 762 |
finally: |
| 763 |
for module in gen: |
| 764 |
sys.modules.pop(module.__name__, None) |
| 765 |
for module in old_modules: |
| 766 |
sys.modules[module.__name__] = module |
| 767 |
|
| 768 |
|
| 769 |
def _bind(f, o): |
| 770 |
@wraps(f) |
| 771 |
def bound_meth(*fargs, **fkwargs): |
| 772 |
return f(o, *fargs, **fkwargs) |
| 773 |
return bound_meth |
| 774 |
|
| 775 |
|
| 776 |
class MockCallbacks: |
| 777 |
|
| 778 |
def __new__(cls, *args, **kwargs): |
| 779 |
r = Mock(name=cls.__name__) |
| 780 |
cls.__init__(r, *args, **kwargs) |
| 781 |
for key, value in vars(cls).items(): |
| 782 |
if key not in ('__dict__', '__weakref__', '__new__', '__init__'): |
| 783 |
if inspect.ismethod(value) or inspect.isfunction(value): |
| 784 |
r.__getattr__(key).side_effect = _bind(value, r) |
| 785 |
else: |
| 786 |
r.__setattr__(key, value) |
| 787 |
return r |