我试图在单元测试中模拟一个实用程序类(在本例中为python logger实用程序)。
虽然我知道如何在每个测试级别上使用monkeypatch来做这件事,但我希望我可以在某种程度上将其作为设置/全局的一部分。
这是我希望我能做的(但我得到错误):
import logging
...
def setup(self, monkeypatch):
class fake_logger(level):
def __init__(self, val):
pass
def setLevel(self, level):
# Do something
def mock_logger(level):
return fake_logger(level)
monkeypatch.setattr(logging, 'getLogger', mock_logger)
这样做的正确方法是什么?
编辑:示例错误
name = 'setup'
def call_optional(obj, name):
method = getattr(obj, name, None)
isfixture = hasattr(method, "_pytestfixturefunction")
if method is not None and not isfixture and py.builtin.callable(method):
# If there's any problems allow the exception to raise rather than
# silently ignoring them
> method()
E TypeError: setup() missing 1 required positional argument: 'monkeypatch'
答案 0 :(得分:4)
monkeypatch
作为普通的pytest夹具。如果你想使用它,你需要将你的方法作为一个夹具。
import logging
import pytest
@pytest.fixture
def setup(monkeypatch):
class fake_logger(object):
def __init__(self, val):
pass
def setLevel(self, level):
# Do something
pass
def mock_logger(level):
return fake_logger(level)
monkeypatch.setattr(logging, 'getLogger', mock_logger)
def test_fake_logger(setup):
# test steps
如果您在测试中检查logging.getLogger('any level')
的类型,则会定义fake_logger
。