[Python] Unexpected failed assert when changing order of python mocks when mocking function...

Discussão em 'Python' iniciado por Stack, Maio 1, 2025.

  1. Stack

    Stack Membro Participativo

    I am implementing a test for a function func1a() in module1.py using mocks.

    The function func1a() calls:

    • one function from module2.py: func2a()
    • one function from module1.py: func1b()

    It appears that the order in which mocks are applied, introduces unexpected effects in my test.

    module2.py contains:

    def func2a()->None:
    return None



    module1.py contains:


    from module2 import func2a


    def func1a()->None:
    func2a()
    func1b()
    return None

    def func1b()->None:
    return None


    The test is implemented this way:


    from unittest.mock import MagicMock, Mock, call, patch
    import pytest


    @patch("module1.func1b")
    @patch("module2.func2a")
    def test_func1a(
    mock_func2a:MagicMock,
    mock_func1b:MagicMock,
    )->None:
    from module1 import func1a
    mocks = ( mock_func2a,
    mock_func1b,
    )
    mock_manager = Mock()
    for mock in mocks:
    mock_manager.attach_mock(mock, "mock_" + mock._extract_mock_name())

    expected_calls = [
    call.mock_func2a(),
    call.mock_func1b(),
    ]
    # When
    func1a()

    # Then
    assert mock_manager.mock_calls == expected_calls


    and works perfectly.

    However, if I invert the order of the patches and keep the rest of the code identical:

    @patch("module2.func2a")
    @patch("module1.func1b")
    def test_func1a(
    mock_func1b:MagicMock,
    mock_func2a:MagicMock,
    )->None:



    I encounter the following assertion error

    assert [call.mock_func1b()] == [call.mock_fu...mock_func1b()]

    At index 0 diff: call.mock_func1b() != call.mock_func2a()
    Right contains 2 more items, first extra item: call.mock_func2b()


    I suspect it may be due to the order in which the mocks are applied. In particular, I think this is due to the fact that I am mocking a function that import another function, while also mocking this function simultaneously.

    Has anyone run into this issue before and can explain why this might be happening?

    Thanks!

    Continue reading...

Compartilhe esta Página