我什么时候应该使用 pytest --import-mode importlib

When should I use pytest --import-mode importlib

这是我的项目结构:

git_dir/
    root/
        __init__.py
        tests/
            __init__.piy
            test1.py
        foo_to_test/
            foo.py

我正在用pytest测试foo.py,test1.py如下:

from foo_to_test.foo import func_to_test

def test1():
    assert something about func_to_test

我想从终端运行

pytest tests

问题来了。 使用 --import-mode append 或 --import-mode prepend 时,它会将 'git_dir' 添加到 PYTHONPATH。 问题是 'git_dir' 不是项目根。

所以我的问题是:

这看起来很难,因为它不是它应该的工作方式。可能是时候学习包装了。

Python 模块系统旨在查找 sys.path 目录中的模块,如您所述。此变量 将由用户 以某种方式填充,最好不要被干预。

当开发人员想要使用您的软件包时,他们必须确保它安装在他们 运行 测试的系统上。

如果你想让他们更容易,提供例如一个 project.toml 文件;然后他们可以构建您的包,并使用 pip install /path/to/your/distribution-file.tgz.

安装它

这里有更多信息:https://setuptools.readthedocs.io/en/latest/userguide/quickstart.html#python-packaging-at-a-glance