如何在VS Code中使用pytest输入命令行参数
我设置了pytest测试,想用可选的命令行参数来运行这些测试。我希望在VS Code中运行和调试这些测试,但我发现命令行参数在VS Code中无法正常工作。
根据VS Code的调试Python测试说明,我在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 Code的说明不同的地方在于,我添加了args
来传递我的命令行参数。我在launch.json中还有另一个配置,但它的目的不是"debug-test"
(而且当我在这个配置中添加args时,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)
结果是request.config.option.skip
和request.config.option.csvfile
总是为None(默认值)。当我导入sys
并查看sys.argv
时,发现它没有包含来自launch.json
的参数。
我使用的是Python 3.12和VS Code版本1.87.1。
1 个回答
0
我有一个类似的例子,我把 launch.json
设置成用 python 来运行,而不是根据文件内容使用 debugpy
。
{
"name": "Python: Debug Tests",
"type": "python",
"request": "launch",
"module": "pytest",
"args": [
"${workspaceFolder}/path/to/your/test_file.py",
"--csvfile=../example.csv",
"--skip=1"
],
"console": "integratedTerminal",
"justMyCode": false
}