python - 在文件顶部导入的模拟函数
问题描述
我正在尝试在一个项目中进行测试,但我遇到了一个奇怪的错误。
我用下面的玩具示例重现了非常相似的情况:
这是文件结构:
.
├── some_package
│ ├── __init__.py
│ └── some_file.py
└── test_mock_patch.py
"""some_package/some_file.py"""
# when I import here, the test fails
from math import floor
def some_func(a, b):
# if I import here, the test passes
# from math import floor
return floor(a + b)
"""test_mock_patch.py"""
import pytest
from unittest import mock
from some_package.some_file import some_func
@pytest.fixture
def mock_floor():
with mock.patch('math.floor', autospec=True) as m:
yield m
def test_some_func(mock_floor):
some_func(1.1, 1)
assert mock_floor.call_count == 1
使用的命令:pytest -v -s test_mock_patch.py
错误:
为什么当我在函数内部导入test_some_func
时通过,而当我在顶部导入时测试失败?
预先感谢您提供任何帮助来解释这种行为mock.patch
版本:
- Python 3.7.3
- pytest 4.4.1
解决方案
这是一个最小的示例,如何通过更改test_mock_patch.py
文件来实现所需的结果。
import pytest
from some_package.some_file import some_func
def test_some_func(monkeypatch):
with monkeypatch.context() as mc:
mc.setattr('some_package.some_file.floor', lambda x: 'foo')
res = some_func(1.1, 1)
assert res == 'foo'
就像我在评论中提到的那样,您需要修补正在导入的功能。
推荐阅读
- ruby-on-rails - 使表名仅对用户唯一,而不是在整个数据库中唯一
- angular8 - 如何在 ag 网格单元格渲染模板中调整 datepicker 视图?
- python - ModuleNotFoundError:没有名为“tensorflow.contrib”的模块,tensorflow=2.0.0
- c# - 使用 Serilog 时如何覆盖 appsettings.json 中指定的应用程序名称?
- json - 我应该如何制作结构以在 SwiftUI 中获取此 JSON 数据?
- qt - 在索引 0 处插入列时 QTreeView 的行为
- javascript - 如何在不更改使用 angularjs 的输入类型复选框的 ng-if 条件的情况下禁用按钮?
- java - 如何修复在类 com.example.chatappfirebase.Model.User 上找不到 id 的设置器/字段?
- typescript - “只读”类型上不存在属性“商店”
我正在学习 Next.js、TypeScript、Redux。
要在接下来应用 redux,在谷歌搜索之后,我这样编写代码。但我不知道错误的含义是什么以及我必须做什么。
import App from "next/app"; import Head from 'next/head'; /*redux*/ import withRedux fro
- r - 在多个特定条件下过滤