gpt4 book ai didi

python - Pytest:如何解决测试文件夹中缺少 __init__.py 的问题?

转载 作者:太空宇宙 更新时间:2023-11-03 11:16:27 25 4
gpt4 key购买 nike

我将所有 pytest 文件存储在项目根目录下的 tests 子目录中。该目录或更高目录中没有 __init__.py 并且 pytest tests/test_a.py 按预期工作。我还可以直接从 tests 文件夹中运行 pytest test_a.py

|--<project_root>
+---[tests]
test_a.py
base.py
config.py
conftest.py

test_a.py中的测试类继承自base.py。现在,问题是由于缺少 __init__.py,IDE 工具无法正常工作,无法解析导入。在 tests 下添加 __init__.py 解决了 IDE 中的所有导入错误,但是测试将不再使用 pytest test_a.py 运行,因为 py .test 无法导入 conftest.py

在我的 conftest.py 中,我有以下导入:

from config import HOST_URL_DEFAULT, USER, PASSWORD

结果是:

ModuleNotFoundError: No module named 'config'
ERROR: could not load /project_root/tests/conftest.py

有没有办法解决这个问题,让 IDE 工具 pytest 继续工作?如果可能,我想避免使用点导入。

更新:阅读后this answer我想我终于开始更多地了解 python 导入的工作原理。

最佳答案

添加 __init__.py 并在 conftest.py 中使用相对或绝对导入:

# relative
from .config import HOST_URL_DEFAULT, USER, PASSWORD
# absolute
from tests.config import HOST_URL_DEFAULT, USER, PASSWORD

在包中(由 __init__.py 标识),您需要明确的导入路径。使用非限定导入(from config import ...)取决于 PYTHONPATHsys.modules,包括您的包根目录 - 这通常不稳健且应该避免,因为它绕过了包基础设施。

你这里的(其他模块使用的config.py)一个包。把它当作一个。


pytest 不鼓励使用带有 __init__.py 的测试包!这有真实的用例 - 例如您的。

什么pytest does discourage在同一个源根目录中有一个源包 测试包。但是,这意味着您应该移动您的源包,而不是您的测试包!

mysource/  # root directory for both mypackage and mytests
+- mypackage/ # should be src/mypackage instead!
+- __init__.py
+- abcd.py
+- mytests
+- __init__.py
+- tests_abcd.py # ``from mypackage import abcd`` imports from source

问题是运行 mytests 意味着 mypackage 也可以从源代码导入。也就是说,您的测试是在您的源包 上进行的,而不是您安装的包。如果您的安装过程中有任何错误,测试将不会发现它。 See the blog linked in the pytest docs for details .

关于python - Pytest:如何解决测试文件夹中缺少 __init__.py 的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50796370/

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