Last active
November 7, 2017 12:50
-
-
Save dpapp-hortonworks/6224068ffc11d18c500b75a861941dfb to your computer and use it in GitHub Desktop.
Automatic mock fixtures for pytest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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