我什么时候应该使用 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' 不是项目根。
我可以添加 sys.path.append('git_dir/root') 但是名称 'git_dir' 对于在其他计算机上工作的其他程序员来说是不同的。
我在pytest文档中看到使用--import-mode importlib可能会解决我的问题,但它似乎对我的PYTHONPATH没有任何影响,我无法理解它在做什么。
所以我的问题是:
- --import-mode importlib 在做什么?
- 我如何在测试时自动将我的根添加到路径中,以便每个拉动该项目的程序员都相同?
这看起来很难,因为它不是它应该的工作方式。可能是时候学习包装了。
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。
这是我的项目结构:
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' 不是项目根。
我可以添加 sys.path.append('git_dir/root') 但是名称 'git_dir' 对于在其他计算机上工作的其他程序员来说是不同的。
我在pytest文档中看到使用--import-mode importlib可能会解决我的问题,但它似乎对我的PYTHONPATH没有任何影响,我无法理解它在做什么。
所以我的问题是:
- --import-mode importlib 在做什么?
- 我如何在测试时自动将我的根添加到路径中,以便每个拉动该项目的程序员都相同?
这看起来很难,因为它不是它应该的工作方式。可能是时候学习包装了。
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。