#39;function#39; object has no attribute #39;assert_called_once_with#39;(function 对象没有属性 assert_call_once_with)
问题描述
我正在尝试使用 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'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:'function' 对象没有属性 'assert_call_once_w
基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
