Skip to content

When pytest-mock installed "assert_not_called" has an exception when assertion fails #252

Closed

Description

@ecs-jnguyen

Description

Hi,

I am trying to use MagicMock's assert_not_called_with method. When I have pytest-mock installed and the assertion is failing, I see this message: During handling of the above exception, another exception occurred:

This might be undesired because there is too much output while trying to find why my test has failed.

Example Code

# Contents of tests/test_something.py

from unittest.mock import MagicMock

def test_assert_not_called_with_pytest():
    magic_mock = MagicMock()
    magic_mock.hello(1)
    magic_mock.hello.assert_not_called()

Example run without pytest-mock installed

============================= test session starts ==============================
platform darwin -- Python 3.9.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /private/var/folders/6g/63d9pqp17ksf50rrs6qw65br0000gp/T/tmp.KtOTIK0R
collected 1 item

tests/test_something.py F                                                [100%]

=================================== FAILURES ===================================
______________________ test_assert_not_called_with_pytest ______________________

    def test_assert_not_called_with_pytest():
        magic_mock = MagicMock()
        magic_mock.hello(1)
>       magic_mock.hello.assert_not_called()

tests/test_something.py:6: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <MagicMock name='mock.hello' id='4355535152'>

    def assert_not_called(self):
        """assert that the mock was never called.
        """
        if self.call_count != 0:
            msg = ("Expected '%s' to not have been called. Called %s times.%s"
                   % (self._mock_name or 'mock',
                      self.call_count,
                      self._calls_repr()))
>           raise AssertionError(msg)
E           AssertionError: Expected 'hello' to not have been called. Called 1 times.
E           Calls: [call(1)].

/Users/jnguyen/.pyenv/versions/3.9.5/lib/python3.9/unittest/mock.py:868: AssertionError
=========================== short test summary info ============================
FAILED tests/test_something.py::test_assert_not_called_with_pytest - Assertio...
============================== 1 failed in 0.10s ===============================

Example run with pytest-mock installed

➜ python -m pytest tests
============================= test session starts ==============================
platform darwin -- Python 3.9.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /private/var/folders/6g/63d9pqp17ksf50rrs6qw65br0000gp/T/tmp.KtOTIK0R
plugins: mock-3.6.1
collected 1 item

tests/test_something.py F                                                [100%]

=================================== FAILURES ===================================
______________________ test_assert_not_called_with_pytest ______________________

__wrapped_mock_method__ = <function NonCallableMock.assert_not_called at 0x10421da60>
args = (<MagicMock name='mock.hello' id='4365369984'>,), kwargs = {}
__tracebackhide__ = True
msg = "Expected 'hello' to not have been called. Called 1 times.\nCalls: [call(1)].\n\npytest introspection follows:\n\nArgs:\nassert (1,) == ()\n  Left contains one more item: 1\n  Use -v to get the full diff"
__mock_self = <MagicMock name='mock.hello' id='4365369984'>, actual_args = (1,)
actual_kwargs = {}
introspection = '\nArgs:\nassert (1,) == ()\n  Left contains one more item: 1\n  Use -v to get the full diff'
@py_assert2 = (), @py_assert1 = None
@py_format4 = '(1,) == ()\n~Left contains one more item: 1\n~Use -v to get the full diff'

    def assert_wrapper(
        __wrapped_mock_method__: Callable[..., Any], *args: Any, **kwargs: Any
    ) -> None:
        __tracebackhide__ = True
        try:
>           __wrapped_mock_method__(*args, **kwargs)

venv/lib/python3.9/site-packages/pytest_mock/plugin.py:414: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <MagicMock name='mock.hello' id='4365369984'>

    def assert_not_called(self):
        """assert that the mock was never called.
        """
        if self.call_count != 0:
            msg = ("Expected '%s' to not have been called. Called %s times.%s"
                   % (self._mock_name or 'mock',
                      self.call_count,
                      self._calls_repr()))
>           raise AssertionError(msg)
E           AssertionError: Expected 'hello' to not have been called. Called 1 times.
E           Calls: [call(1)].

/Users/jnguyen/.pyenv/versions/3.9.5/lib/python3.9/unittest/mock.py:868: AssertionError

During handling of the above exception, another exception occurred:

    def test_assert_not_called_with_pytest():
        magic_mock = MagicMock()
        magic_mock.hello(1)
>       magic_mock.hello.assert_not_called()
E       AssertionError: Expected 'hello' to not have been called. Called 1 times.
E       Calls: [call(1)].
E       
E       pytest introspection follows:
E       
E       Args:
E       assert (1,) == ()
E         Left contains one more item: 1
E         Use -v to get the full diff

tests/test_something.py:6: AssertionError
=========================== short test summary info ============================
FAILED tests/test_something.py::test_assert_not_called_with_pytest - Assertio...
============================== 1 failed in 0.09s ===============================

Activity

  1. nicoddemus commented on Aug 17, 2021

    @nicoddemus
    Member

    Hi @ecs-jnguyen,

    Thanks for the report and sorry for the delay.

    I think we are missing installing a "wrapper" for assert_not_called_with. Here's a wrapper which we install for assert_not_called:

    def wrap_assert_not_called(*args: Any, **kwargs: Any) -> None:
    __tracebackhide__ = True
    assert_wrapper(_mock_module_originals["assert_not_called"], *args, **kwargs)

    Probably we just need to do the same for assert_not_called_with.

  2. changed the title [-]When pytest-mock installed "assert_not_called_with" has an exception when assertion fails[/-] [+]When pytest-mock installed "assert_not_called" has an exception when assertion fails[/+] on Aug 17, 2021
  3. ecs-jnguyen commented on Aug 17, 2021

    @ecs-jnguyen
    Author

    @nicoddemus

    Sorry my title was incorrect I just modified it. Before it said assert_not_called_with had the issue but it is actually assert_not_called that has the issue. I don't believe that the mock library has an assert_not_called_with method.

  4. nicoddemus commented on Aug 17, 2021

    @nicoddemus
    Member

    I see, thanks.

    If you disable the feature, does it look better to you?

    [pytest]
    mock_traceback_monkeypatch = false
  5. ecs-jnguyen commented on Aug 17, 2021

    @ecs-jnguyen
    Author

    @nicoddemus

    yes that works great. Thank you!

    Is this a workaround or is there still an issue?

    I found the documentation that talks about mock_traceback_monkeypatch and the output of the example test looked different for me. The following test has a long error message when the test fails.

    from pytest_mock import MockFixture
    
    def test_something(mocker):
        m = mocker.Mock()
        m('fo')
        m.assert_called_once_with('', bar=4)
  6. nicoddemus commented on Aug 18, 2021

    @nicoddemus
    Member

    I found the documentation that talks about mock_traceback_monkeypatch and the output of the example test looked different for me. The following test has a long error message when the test fails.

    The test documentation might indeed be outdated, as it is not generated automatically. Can you show the output please?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions