Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用pytest测试函数的正确参数?_Python_Unit Testing_Pytest - Fatal编程技术网

Python 如何使用pytest测试函数的正确参数?

Python 如何使用pytest测试函数的正确参数?,python,unit-testing,pytest,Python,Unit Testing,Pytest,我正在学习如何在Python中使用py.test进行测试。我试图测试一种在使用其他库(如mock)时非常常见的特定情况。具体来说,测试一个函数或方法是否调用另一个具有正确参数的可调用函数。不需要返回值,只需确认被测方法正确调用即可 下面是一个直接来自以下方面的示例: 是否可以使用py.test中的monkeypatch或fixtures执行此操作,而无需有效地编写自己的模拟类?我已经搜索了这个特定的用例,但是找不到一个例子。py.test是否鼓励使用类似这样的代码替代方法?很好。我想出了一些似乎

我正在学习如何在Python中使用
py.test
进行测试。我试图测试一种在使用其他库(如
mock
)时非常常见的特定情况。具体来说,测试一个函数或方法是否调用另一个具有正确参数的可调用函数。不需要返回值,只需确认被测方法正确调用即可

下面是一个直接来自以下方面的示例:


是否可以使用
py.test
中的
monkeypatch
fixtures
执行此操作,而无需有效地编写自己的模拟类?我已经搜索了这个特定的用例,但是找不到一个例子。
py.test
是否鼓励使用类似这样的代码替代方法?

很好。我想出了一些似乎有效的方法,但我想它与mock类似:

@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]

您可以使用它,这样就可以很容易地将包用作pytest夹具。

奇怪的是,这种单元测试的基本功能不是现成的。我们如何将这种方法与模拟返回值结合起来?
@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]