我有以下 pytest 目录结构:
system_tests/
├── conftest
├── pytest.ini
│
├── suite_1/
│ └── test_A.py
│
└── suite_2/
└── sub_suite_2a/
└── test_B.py
当每个测试方法运行时,许多第三方库/进程会在当前工作目录中生成工件。sub_suite
执行时文件夹(使用 CLI 或 IDE“播放”按钮),文件在 sub_suite
中生成文件夹,我希望它们在哪里。 system_tests
运行 pytest 时运行所有测试的文件夹,所有工件都在 system_tests
中创建文件夹,这不是我想要的。 有没有一种简单的方法可以强制 pytest 始终使用测试类文件夹作为工作目录,这样无论我如何或从哪里运行测试,我都会得到相同的结果?
最佳答案
以下函数级 fixture 将更改为测试用例目录,运行测试(yield),然后更改回调用目录以避免副作用,正如@hi2meuk 所建议的那样:
@pytest.fixture
def change_test_dir(request):
os.chdir(request.fspath.dirname)
yield
os.chdir(request.config.invocation_dir)
request
是一个内置的 pytest fixture fspath
是 LocalPath
到正在执行的测试模块dirname
是测试模块的目录request.config.invocationdir
- 执行 pytest 的文件夹 request.config.rootdir
- pytest root,不会根据您运行 pytest 的位置而改变。此处未使用,但可能有用。 任何由测试启动的进程都将使用测试用例文件夹作为它们的工作目录,并将它们的日志、输出等复制到那里,而不管测试套件在哪里执行。
编辑:改进的解决方案
使用 monkeypatch正如@Kound 建议的那样,删除样板代码以恢复 cwd。您也可以启用autouse自动将此 fixture 应用于所有测试功能。将以下 fixture 添加到 conftest.py更改所有测试的 cwd:
@pytest.fixture(autouse=True)
def change_test_dir(request, monkeypatch):
monkeypatch.chdir(request.fspath.dirname)
关于python - 将 pytest 工作目录更改为测试用例目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62044541/