我已将 pytest 测试设置为使用可选的命令行参数。我想在 VS Code 中运行和调试这些测试。但是,我无法获取与 VS Code 一起使用的命令行参数。
根据调试Python测试的VS Code说明,我在launch.json中添加了以下配置:
{
"name": "Python: Debug Tests",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"purpose": ["debug-test"],
"console": "integratedTerminal",
"args": ["--csvfile='..\\example.csv'","--skip", "1"],
"justMyCode": false
}
这与 VS 代码指令的不同之处仅在于我添加了
args
来传递命令行参数。我在 launch.json 中有另一个配置,但其目的不是"debug-test"
(当我向其中添加参数时,pytest 仍然没有收到我的参数)。
我的 conftest.py 包含以下内容,这些内容在 VS Code 外部使用 pytest 时有效:
def pytest_addoption(parser):
parser.addoption(
"--csvfile", action="store", default=None)
parser.addoption("--skip", action="store", default=None)
@pytest.fixture(scope='session')
def skip(request):
return request.config.option.skip
@pytest.fixture(scope='session')
def data(request):
return pd.read_csv(request.config.option.csvfile)
我使用的是 Python 3.12 和 VS Code 版本 1.87.1。
我有一个类似的示例,我将
launch.json
设置为与 python 一起运行,而不是 debugpy
跟随文件内容。
{
"version": "0.2.0",
"configurations": [
{
"name": "Python: XXXXX Tests",
"type": "python",
"request": "launch",
"program": "${workspaceFolder}/path/to/your/test_file.py",
"args": [
"--csvfile", "../example.csv",
"--skip", "1"
],
"console": "integratedTerminal",
"justMyCode": false
}
]
}