如何使用pytest使用正确的参数调用函数?

don*_*pj2 8 python unit-testing pytest

我正在学习如何使用Python完成测试py.test.我正在尝试测试在使用其他库时非常常见的特定情况mock.具体来说,测试函数或方法是否使用正确的参数调用另一个callable.不需要返回值,只需确认被测方法正确调用.

以下是直接来自文档的示例:

>>> class ProductionClass:
...     def method(self):
...         self.something(1, 2, 3)
...     def something(self, a, b, c):
...         pass
...
>>> real = ProductionClass()
>>> real.something = MagicMock()
>>> real.method()
>>> real.something.assert_called_once_with(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)

是否可以使用monkeypatchfixtures从中进行此操作py.test,而无需有效地编写自己的模拟类?我搜索了这个特定的用例,但找不到一个例子.是否py.test鼓励采用另类方式来执行此类代码?

don*_*pj2 7

出色地。我想出了一些似乎有效的方法,但我认为它与模拟类似:

@pytest.fixture
def argtest():
    class TestArgs(object):
        def __call__(self, *args): 
            self.args = list(args)
    return TestArgs()

class ProductionClass:
    def method(self):
        self.something(1,2,3)
    def something(self, a, b, c):
        pass

def test_example(monkeypatch, argtest):
    monkeypatch.setattr("test_module.ProductionClass.something", argtest)
    real = ProductionClass()
    real.method()
    assert argtest.args == [1,2,3]
Run Code Online (Sandbox Code Playgroud)