【问题标题】:How to revert Mocking如何恢复模拟
【发布时间】:2021-07-29 13:21:00
【问题描述】:

当我弄清楚为什么我的测试文件运行顺利但如果使用 pytest 为整个包一起运行测试时会中断时,我几乎要发疯了。

我有一个父类和一个子类。子进程调用父进程的 init 如下:

class Child(Parent):
    __init__(...,**kwargs):
        ...
        super().__init__(**kwargs)

我想通过一个小测试来定义这种行为。

from unittest.mock import Mock

def test_init_calls_parent_init():
    Parent.__init__ = Mock()
    
    Child()

    assert Parent.__init__.called

问题是Parent.__init__ 一直是模拟,用于其他文件中的所有以下测试。

我的想法是把它放到一个函数作用域中使它只是一个临时的改变。当然,由于这些测试失败了,它们隐含地定义了对父级 init 的需求,但我也想确保使用一个显式测试。

我应该创建一些pytest setup/teardown 还是可以接受的防止这种情况的方法?

【问题讨论】:

    标签: python mocking pytest python-unittest


    【解决方案1】:

    当你执行Parent.__init__ = Mock()时,你基本上重新定义了模块本身的__init__,然后反映在后面的测试中。

    与其手动将Parent.__init__ 的实现更改为Mock,我的建议是使用unittest 和pytest-mock 中已有的修补功能。

    • 我们也可以按照@MattSom 的建议使用monkeypatch(参见cmets 部分)

    src.py

    class Parent:
        def __init__(self, **kwargs):
            print("Parent __init__ called")
    
    class Child(Parent):
        def __init__(self, **kwargs):
            super().__init__(**kwargs)
            print("Child __init__ called")
    

    未经修正:

    from unittest.mock import Mock, patch
    
    from src import Child, Parent
    
    
    def test_init_calls_real_parent_init():
        Child()
    
    
    def test_init_calls_updated_parent_init():
        Parent.__init__ = Mock()
    
        Child()
    
        assert Parent.__init__.called
    
    
    def test_init_calls_real_parent_init_2():
        Child()
    

    输出:

    $ pytest -q test_src.py -rP
    ...                                                                                                                                                                                                 [100%]
    ================================================================================================= PASSES ==================================================================================================
    ____________________________________________________________________________________ test_init_calls_real_parent_init _____________________________________________________________________________________
    ------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
    Parent __init__ called
    Child __init__ called
    ___________________________________________________________________________________ test_init_calls_updated_parent_init ___________________________________________________________________________________
    ------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
    Child __init__ called
    ___________________________________________________________________________________ test_init_calls_real_parent_init_2 ____________________________________________________________________________________
    ------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
    Child __init__ called
    3 passed in 0.01s
    

    调查结果:

    第一个测试称为真正的Parent.__init__。第二次测试称为模拟。然而在第三次测试中,它也意外地调用了第二次测试中的mock。

    有修正:

    from unittest.mock import Mock, patch
    
    from src import Child, Parent
    
    
    def test_init_calls_real_parent_init():
        Child()
    
    
    # Personally I wouldn't advise to do this. It just works :)
    def test_init_calls_updated_parent_init():
        # Setup
        orig_parent_init = Parent.__init__  # Store original init
    
        # Real test
        Parent.__init__ = Mock()
    
        Child()
    
        assert Parent.__init__.called
    
        # Teardown
        Parent.__init__ = orig_parent_init  # Bring back the original init
    
    
    @patch("src.Parent.__init__")  # Uses unittest
    def test_init_calls_mocked_parent_init(mock_parent_init):
        Child()
    
        assert mock_parent_init.called
    
    
    def test_init_calls_mocked_parent_init_2(mocker):  # Uses pytest-mock
        mock_parent_init = mocker.patch("src.Parent.__init__")
    
        Child()
    
        assert mock_parent_init.called
    
    
    def test_init_calls_real_parent_init_2():
        Child()
    

    输出:

    $ pytest -q test_src_2.py -rP
    .....                                                                                                                                                                                               [100%]
    ================================================================================================= PASSES ==================================================================================================
    ____________________________________________________________________________________ test_init_calls_real_parent_init _____________________________________________________________________________________
    ------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
    Parent __init__ called
    Child __init__ called
    ___________________________________________________________________________________ test_init_calls_updated_parent_init ___________________________________________________________________________________
    ------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
    Child __init__ called
    ___________________________________________________________________________________ test_init_calls_mocked_parent_init ____________________________________________________________________________________
    ------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
    Child __init__ called
    __________________________________________________________________________________ test_init_calls_mocked_parent_init_2 ___________________________________________________________________________________
    ------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
    Child __init__ called
    ___________________________________________________________________________________ test_init_calls_real_parent_init_2 ____________________________________________________________________________________
    ------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
    Parent __init__ called
    Child __init__ called
    5 passed in 0.03s
    

    调查结果:

    这里我使用了 2 个解决方案:

    1. 在手动重新分配为 mock 后将 Parent.__init__ 的原始实现改回(请参阅 test_init_calls_updated_parent_init)(不建议)
    2. 或使用 unittest 和 pytest-mock 的内置修补功能(请参阅 test_init_calls_mocked_parent_init 和 test_init_calls_mocked_parent_init_2)

    现在,第一个和最后一个测试都正确调用了实际的 Parent.__init__,即使在所有模拟完成之后也是如此。

    【讨论】:

    • 感谢您提供包括反模式在内的详尽答案!这很棒,因为起初我也已经完成了(通过创建origin_parent_init)。最终我做了一个猴子补丁,因为 pytest 有那个夹具。我认为您也可以宣传该选项:python def test_init_calls_parent_init(monkeypatch): monkeypatch.setattr(ModificationRequest, "__init__", Mock()) ProducerModificationRequest() assert ModificationRequest.__init__.called
    • 好建议 :) 我用monkeypatch 更新了答案作为替代方案。谢谢。
    【解决方案2】:

    您可以尝试将父级转换为fixture, which defaults to having a "function" scope,理论上应该在每次测试后拆除固定装置。

    记得yield your fixture,然后添加任何其他必要的拆卸说明。

    您的 Parent 不解构模拟的原因是因为不是固定装置的父类/函数被视为与任何其他父/子函数一样。

    【讨论】:

    • 嗨,克里斯,谢谢你的回答!一个问题:我怎样才能确保这个fixture会被孩子调用?
    • 在我链接的页面上是调用夹具的说明,特别是here或here
    • 我的意思是孩子继承自父类。它不能从固定装置继承。
    猜你喜欢
    • 1970-01-01
    • 2019-10-23
    • 1970-01-01
    • 2023-03-14
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2013-11-12
    相关资源
    最近更新 更多