在 Pytest 中使用本地导入 [英] Using local imports in Pytest
问题描述
我从来没有真正完全理解如何在 Python 中处理包,我现在遇到了问题.但是谷歌搜索似乎没有帮助,因为我觉得这个话题真的很混乱.
I have never really fully understood how packages are handled in Python and I'm having a problem with that right now. But googling doesn't seem to help as I find the topic really confusing.
我有一个采用这种结构的项目:
I have a project with this structure:
project_name/
src/
main.py
utils/
string_utils.py
tests/
test_string_utils.py
我正在使用 Pytest 进行单元测试,目前在test_string_utils.py"文件中我有以下内容:
I am using Pytest for running unit testing and currently inside the "test_string_utils.py" file I have the following:
from ..src.utils.string_utils import StringUtilsClass
但是我转到文件夹project_name"并尝试使用此命令中的任何一个运行测试时出现错误:
But I go to the folder "project_name" and try to run tests with any of this command I get errors:
$ pytest tests/
ValueError: 尝试在顶级包之外进行相对导入
ValueError: attempted relative import beyond top-level package
我知道 python 的 -m 参数,但似乎运行pytest -m"有完全不同的行为.
I know about the -m argument for python, but it seems that running "pytest -m" has a completely different behavior.
我该如何解决这个问题?我是否使用了错误的文件夹架构?我不认为我正在构建的应该是一个 pip 包(这将简化导入)
How can I solve this? Am I using the wrong folder architecture? I don't think what I'm building should be a pip package (which would simplify imports)
推荐答案
您是否尝试过:from src.utils.string_utils import StringUtilsClass
而 .. before src?或 from string_utils import StringUtilsClass
did you try : from src.utils.string_utils import StringUtilsClass
without .. before src?
or from string_utils import StringUtilsClass
这篇关于在 Pytest 中使用本地导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!