gpt4 book ai didi

python - 在运行测试之前更改 cwd

转载 作者:行者123 更新时间:2023-11-28 19:30:14 27 4
gpt4 key购买 nike

我在不同的目录中有一堆 unittest 测试用例。还有一个目录只包含测试的帮助脚本。所以我的文件树看起来像这样

test_dir1
test_dir2
test_dir3
helper_scripts

test_dir* 中的每个 python 文件都将包含这些行:

import sys
sys.path.append('../helper_scripts')
import helper_script

只要我从他们的目录中运行测试,这一切都很好。但是,我想在项目根目录下运行:

py.test

让它遍历所有目录并运行它找到的每个测试。问题是测试是从错误的目录运行的,所以 sys.path.append 没有附加 helper_scripts 目录,它附加了项目的父目录根。这会导致所有导入失败并出现 Import Error

有没有办法告诉 py.test 从它们的目录运行测试脚本? IE。在执行它们之前更改 cwd?如果没有,是否有另一个我可以使用的测试运行器?

最佳答案

我通常做的是像这样构建我的项目:

myproject/
setup.py
myproject/
__init__.py
mymodule.py
tests/
__init__.py
test_dir1/
test_mymodule.py
helper_scripts/
__init__.py
helper_script.py

为了运行测试,我在开发模式下使用安装了 myproject 的 virtualenv,在 myproject 根目录中使用以下命令之一:

pip install -e .
python setup.py develop

现在在 test_mymodule.py 我可以说

from myproject.tests.helper_scripts import helper_script

然后我可以运行 pytest 并且根本不需要更改测试中的工作目录。

参见 Pytest 的 Good Integration Practices以获得不同项目目录结构的优缺点的重要总结。

关于python - 在运行测试之前更改 cwd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26667490/

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