簡體   English   中英

Python - 我如何斷言模擬 object 沒有被特定的 arguments 調用?

[英]Python - How can I assert a mock object was not called with specific arguments?

我意識到unittest.mock對象現在有一個可用的assert_not_called方法,但我正在尋找的是一個assert_not_called_with 有沒有這樣的東西? 我查看了 Google 並沒有看到任何東西,當我嘗試僅使用mock_function.assert_not_called_with(...)它引發了一個AttributeError ,這意味着 function 不存在該名稱。

我目前的解決方案

with self.assertRaises(AssertionError):
    mock_function.assert_called_with(arguments_I_want_to_test)

這行得通,但如果我想進行多個此類調用,則會使代碼混亂。

有關的

斷言未使用 Mock 調用函數/方法

您可以自己將assert_not_called_with方法添加到unittest.mock.Mock

from unittest.mock import Mock

def assert_not_called_with(self, *args, **kwargs):
    try:
        self.assert_called_with(*args, **kwargs)
    except AssertionError:
        return
    raise AssertionError('Expected %s to not have been called.' % self._format_mock_call_signature(args, kwargs))

Mock.assert_not_called_with = assert_not_called_with

以便:

m = Mock()
m.assert_not_called_with(1, 2, a=3)
m(3, 4, b=5)
m.assert_not_called_with(3, 4, b=5)

輸出:

AssertionError: Expected mock(3, 4, b=5) to not have been called.

另一種使用模擬調用歷史記錄的解決方案:

from unittest.mock import call

assert call(arguments_I_want_to_test) not in mock_function.mock_calls

使用 Pytest,我斷言調用了“AssertionError”:

import pytest
from unittest.mock import Mock


def test_something():
    something.foo = Mock()
    
    # Test that something.foo(bar) is not called.
    with pytest.raises(AssertionError):
        something.foo.assert_called_with(bar)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM