Assert a function/method was not called using Mock

后端 未结 6 1573
深忆病人
深忆病人 2020-12-12 19:50

I\'m using the Mock library to test my application, but I want to assert that some function was not called. Mock docs talk about methods like mock.assert_called_with

相关标签:
6条回答
  • 2020-12-12 20:21

    This should work for your case;

    assert not my_var.called, 'method should not have been called'
    

    Sample;

    >>> mock=Mock()
    >>> mock.a()
    <Mock name='mock.a()' id='4349129872'>
    >>> assert not mock.b.called, 'b was called and should not have been'
    >>> assert not mock.a.called, 'a was called and should not have been'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AssertionError: a was called and should not have been
    
    0 讨论(0)
  • 2020-12-12 20:26

    With python >= 3.5 you can use mock_object.assert_not_called().

    0 讨论(0)
  • 2020-12-12 20:33

    Judging from other answers, no one except @rob-kennedy talked about the call_args_list.

    It's a powerful tool for that you can implement the exact contrary of MagicMock.assert_called_with()

    call_args_list is a list of call objects. Each call object represents a call made on a mocked callable.

    >>> from unittest.mock import MagicMock
    >>> m = MagicMock()
    >>> m.call_args_list
    []
    >>> m(42)
    <MagicMock name='mock()' id='139675158423872'>
    >>> m.call_args_list
    [call(42)]
    >>> m(42, 30)
    <MagicMock name='mock()' id='139675158423872'>
    >>> m.call_args_list
    [call(42), call(42, 30)]
    

    Consuming a call object is easy, since you can compare it with a tuple of length 2 where the first component is a tuple containing all the positional arguments of the related call, while the second component is a dictionary of the keyword arguments.

    >>> ((42,),) in m.call_args_list
    True
    >>> m(42, foo='bar')
    <MagicMock name='mock()' id='139675158423872'>
    >>> ((42,), {'foo': 'bar'}) in m.call_args_list
    True
    >>> m(foo='bar')
    <MagicMock name='mock()' id='139675158423872'>
    >>> ((), {'foo': 'bar'}) in m.call_args_list
    True
    

    So, a way to address the specific problem of the OP is

    def test_something():
        with patch('something') as my_var:
            assert ((some, args),) not in my_var.call_args_list
    

    Note that this way, instead of just checking if a mocked callable has been called, via MagicMock.called, you can now check if it has been called with a specific set of arguments.

    That's useful. Say you want to test a function that takes a list and call another function, compute(), for each of the value of the list only if they satisfy a specific condition.

    You can now mock compute, and test if it has been called on some value but not on others.

    0 讨论(0)
  • 2020-12-12 20:36

    When you test using class inherits unittest.TestCase you can simply use methods like:

    • assertTrue
    • assertFalse
    • assertEqual

    and similar (in python documentation you find the rest).

    In your example we can simply assert if mock_method.called property is False, which means that method was not called.

    import unittest
    from unittest import mock
    
    import my_module
    
    class A(unittest.TestCase):
        def setUp(self):
            self.message = "Method should not be called. Called {times} times!"
    
        @mock.patch("my_module.method_to_mock")
        def test(self, mock_method):
            my_module.method_to_mock()
    
            self.assertFalse(mock_method.called,
                             self.message.format(times=mock_method.call_count))
    
    0 讨论(0)
  • 2020-12-12 20:38

    You can check the called attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest, you can check the contents of call_args_list instead:

    self.assertItemsEqual(my_var.call_args_list, [])
    

    When it fails, it gives a message like this:

    AssertionError: Element counts were not equal:
    First has 0, Second has 1:  call('first argument', 4)
    
    0 讨论(0)
  • 2020-12-12 20:43

    Though an old question, I would like to add that currently mock library (backport of unittest.mock) supports assert_not_called method.

    Just upgrade yours;

    pip install mock --upgrade

    0 讨论(0)
提交回复
热议问题