如何更改 pytest 的工作目录?

问题描述 投票:0回答:1

如果通过 Visual Studio Code 启动,我想在与使用

pytest tests
从命令行启动的同一目录中运行测试。

文件夹结构如下:

project-root
|- .vscode
   - settings.json
|-data-processing
| |-src
| |-tests

我从

data-processing
文件夹
pytest tests
运行 pytest,并
os.getcwd()
产生:

...project-root/data-processing

如果我从 VS Code 运行

os.getcwd()
产量:

...project-root

通过此设置 (

settings.json
):

{
    "python.testing.pytestArgs": [
        "data-processing/tests",
    ],
    "python.testing.unittestEnabled": false,
    "python.testing.pytestEnabled": true
}

我尝试使用

python.testing.cwd
选项来设置工作目录:

{
    "python.testing.pytestArgs": [
        "tests",
    ],
    "python.testing.cwd": "./data-processing/",
    "python.testing.unittestEnabled": false,
    "python.testing.pytestEnabled": true
}

问题是,一旦我设置

cwd
,测试发现就停止工作 - 根本没有发现任何测试。我尝试了带和不带“./”的不同路径。我还检查了microsoft/vscode-python#22504

那么如何在 VS Code 中获取相同的工作目录来进行测试运行呢?使用

os.chdir
更改目录不起作用,因为我的问题是由于 pyspark 内的模块解析造成的。

python visual-studio-code pytest
1个回答
0
投票

您可以在项目根目录中创建 conftest.py 文件,并在其中使用固定装置来处理您需要的内容,包括目录更改。

要更改目录,您可以简单地:

import pytest

@pytest.fixture(autouse=True)
def change_test_dir(request, monkeypatch):
    monkeypatch.chdir(request.fspath.dirname)

这样,您都需要在任何终端中输入 pytest,它将收集测试。

© www.soinside.com 2019 - 2024. All rights reserved.