pytest:如何获取从模拟 class 返回的(模拟)实例?

pytest: how do I get the (mock) instances returned from a mocked class?

我一定很累,因为肯定有一种简单的方法可以做到这一点。 但是我已经阅读了 pytest 文档并且无法弄清楚这个简单的用例。

我有一个小包要测试:

class MyClass:
    def __init__(self):
        pass
    def my_method(self, arg):
        pass

def the_main_method():
    m = MyClass()
    m.my_method(123)

我想确保 (1) 创建 MyClass 的实例,并且 (2) 使用正确的参数调用 my_method

所以这是我的测试:

from unittest.mock import patch

@patch('mypkg.MyClass', autospec=True)
def test_all(mocked_class):

    # Call the real production code, with the class mocked.
    import mypkg
    mypkg.the_main_method()

    # Ensure an instance of MyClass was created.
    mocked_class.assert_called_once_with()

    # But how do I ensure that "my_method" was called?
    # I want something like mocked_class.get_returned_values() ...

我知道每次生产代码调用 MyClass() 时,unittest 框架都会生成一个新的模拟实例。

但是我如何获得这些实例呢?

我想写这样的东西:

the_instance.assert_called_once_with(123)

但是我从哪里得到 the_instance

好吧,令我惊讶的是,无论您调用构造函数多少次,都只创建了一个 模拟实例 (:

我能写的是:

mocked_class.return_value.my_method.assert_called_once_with(123)

return_value 不代表一个 return 值,但是 — 它为 所有 个创建的实例积累信息。

在我看来,这是一种相当深奥的方法。我假设它是从一些疯狂的 Java 模拟库 (:

如果你想捕捉单个returned对象,你可以使用.side_effect到return任何你想要的,并记录在你自己的列表中等