【问题标题】:How to use monkeypatch in a "setup" method for unit tests using pytest?如何在使用 pytest 的单元测试的“设置”方法中使用monkeypatch?
【发布时间】: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


【解决方案1】:

monkeypatch 用作普通的 pytest 夹具。如果你想使用它,你需要把你的方法也做成一个fixture。

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

【讨论】:

  • 您也可以使用@pytest.fixture(autouse=True),这样它就会自动应用于所有测试,而无需使用setup 参数。
猜你喜欢
  • 2020-12-28
  • 2022-12-18
  • 2017-11-23
  • 2020-02-26
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多