gpt4 book ai didi

python - 在 Python whl 文件中模拟一个函数

转载 作者:行者123 更新时间:2023-12-04 16:45:25 31 4
gpt4 key购买 nike

我正在尝试为在 .whl 中调用函数的函数编写测试。文件,但我正在努力模拟车轮中的功能。我在我的虚拟环境中安装了轮子 - 我用 pip install my_wheel.whl 安装了轮子而在环境中。车轮中的包裹名为 my_package .

我要测试的功能 看起来像这样:

from my_package import wheel_function

def my_func():
x = wheel_function()
return x + 5

我要 mock wheel_function所以测试只看 my_func .

我的 测试脚本 :
import pytest

def mock_wheel_function():
return 5

def test_my_func(mocker):
my_mock = mocker.patch("src.wheels.my_wheel.path.to.wheel_function",
side_effect=mock_wheel_function)
# (Do stuff)

我收到以下错误: AttributeError: module 'src.wheels' has no attribute 'my_wheel' .

我的目录结构是这样的。

源文件
|轮子
|........ my_wheel.whl
|模块
|........ my_module

测试
| - 测试模块
|........ test_my_module

如果我尝试在虚拟环境中传递模块的路径(即 /Users/me/venv/lib/python3.7/site-packages/.... ),我得到 ModuleNotFoundError: module '/Users/me/venv/lib/python3' not found .

有任何想法吗?谢谢

最佳答案

使用时mocker.patch ,您必须提供要模拟的对象的 Python 导入路径,而不是相对文件系统路径。

wheel_function包含在模块 my_package 中,你会想要将你的 mock 者设置为

my_mock = mocker.patch(
"my_package.wheel_function",
side_effect=mock_wheel_function
)

关于python - 在 Python whl 文件中模拟一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60516628/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com