Skip to content

Instantly share code, notes, and snippets.

@dpapp-hortonworks
Last active November 7, 2017 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpapp-hortonworks/6224068ffc11d18c500b75a861941dfb to your computer and use it in GitHub Desktop.
Save dpapp-hortonworks/6224068ffc11d18c500b75a861941dfb to your computer and use it in GitHub Desktop.
Automatic mock fixtures for pytest
import pytest
from _pytest.monkeypatch import MonkeyPatch
from mock import Mock
BUILTINS = set(dir(__builtins__))
def _mock(monkeypatch, name, module):
if name in BUILTINS:
module = __builtins__
ret = Mock()
monkeypatch.setattr(module, name, ret)
return ret
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_protocol(item, nextitem):
monkeypatch = MonkeyPatch()
for fname in item.fixturenames:
if fname.startswith("mock_") and fname not in item.funcargs:
item.funcargs[fname] = _mock(monkeypatch, fname[5:], item.module.MODULE)
yield
monkeypatch.undo()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment