如何在使用pytest进行单元测试的“setup”方法中使用monkeypatch?

问题描述:

我试图在单元测试中嘲笑一个实用工具类(在这种情况下是python logger工具)。如何在使用pytest进行单元测试的“setup”方法中使用monkeypatch?

虽然我知道如何在每个测试级别上使用monkeypatch,但我希望能够以某种方式将它作为setup/global的一部分来完成。

以下是我希望我可以做(但我得到的错误):

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

请包括您收到的错误,它确实帮助我们了解发生了什么问题。 –

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你定义。

+0

您也可以执行'@ pytest.fixture(autouse = True)',因此它可以自动应用于所有测试,而无需使用'setup'参数。 –