問題描述
我正在嘗試使用 pytest 和 pytest_mock 運行以下測試
I'm trying to run the following test using pytest and pytest_mock
def rm(filename):
helper(filename, 5)
def helper(filename):
pass
def test_unix_fs(mocker):
mocker.patch('module.helper')
rm('file')
helper.assert_called_once_with('file', 5)
但我得到異常 AttributeError: 'function' object has no attribute 'assert_called_once_with'
我做錯了什么?
推薦答案
你不能在 vanilla 函數上執行 .assert_call_once_with
函數:你首先需要包裝它與 mock.create_autospec代碼>
裝飾器.比如:
You can not perform a .assert_called_once_with
function on a vanilla function: you first need to wrap it with the mock.create_autospec
decorator. So for instance:
import unittest.mock as mock
def rm(filename):
helper(filename, 5)
def helper(filename):
pass
helper = mock.create_autospec(helper)
def test_unix_fs(mocker):
mocker.patch('module.helper')
rm('file')
helper.assert_called_once_with('file', 5)
或者更優雅:
import unittest.mock as mock
def rm(filename):
helper(filename, 5)
@mock.create_autospec
def helper(filename):
pass
def test_unix_fs(mocker):
mocker.patch('module.helper')
rm('file')
helper.assert_called_once_with('file', 5)
請注意,斷言將失敗,因為您僅使用 'file'
調用它.所以一個有效的測試是:
Note that the assertion will fail, since you call it only with 'file'
. So a valid test would be:
import unittest.mock as mock
def rm(filename):
helper(filename, 5)
@mock.create_autospec
def helper(filename):
pass
def test_unix_fs(mocker):
mocker.patch('module.helper')
rm('file')
helper.assert_called_once_with('file')
編輯:如果函數是在某個模塊中定義的,您可以將其包裝在本地的裝飾器中.例如:
EDIT: In case the function is defined in some module, you can wrap it in a decorator locally. For example:
import unittest.mock as mock
from some_module import some_function
some_function = mock.create_autospec(some_function)
def test_unix_fs(mocker):
some_function('file')
some_function.assert_called_once_with('file')
這篇關于'function' 對象沒有屬性 'assert_call_once_with'的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!