Pytest:如何解决在tests文件夹中缺少__init__.py的问题?

时间:2018-06-11 11:09:00

标签: python pytest

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

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

test_a.py中的测试类继承自base.py。现在,问题是因为缺少__init__.py IDE工具不起作用并且无法解析导入。在__init__.py下添加tests会解决IDE中的所有导入错误,但测试不再使用pytest test_a.py运行,因为py.test无法导入conftest.py。< / p>

在我的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导入的工作原理了。

1 个答案:

答案 0 :(得分:2)

添加__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