【发布时间】:2016-06-21 15:17:17
【问题描述】:
我正在尝试在单元测试中模拟一个实用程序类(在本例中为 python 记录器实用程序)。
虽然我知道如何在每个测试级别上使用 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'
【问题讨论】:
-
请包括您遇到的错误,这确实有助于我们了解问题所在。
标签: python unit-testing pytest monkeypatching