如何将命令行参数传递给在vscode中运行的pytest测试

2024-10-02 18:27:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经编写了在vscode项目中由pytest运行的测试。配置文件.vscode/settings.json允许使用以下命令向pytest传递其他命令行参数:

    "python.testing.pytestArgs": [
        "test/",
        "--exitfirst",
        "--verbose"
    ],

如何将自定义脚本参数传递给测试脚本本身?类似于从命令行调用pytest,如下所示:

pytest --exitfirst --verbose test/ --test_arg1  --test_arg2

Tags: 项目命令行test命令脚本jsonverbose参数
2条回答

如果这只是针对调试器,那么您可以在launch.json文件的"args"中指定内容。有关更多详细信息,请参见https://code.visualstudio.com/docs/python/debugging#_args

经过多次试验,我终于找到了方法。我需要的是将用户名和密码传递给脚本,以便允许代码登录到测试服务器。我的测试是这样的:
my_module_test.py

import pytest
import my_module

def login_test(username, password):
    instance = my_module.Login(username, password)
    # ...more...

conftest.py

import pytest

def pytest_addoption(parser):
    parser.addoption(' username', action='store', help='Repository user')
    parser.addoption(' password', action='store', help='Repository password')

def pytest_generate_tests(metafunc):
    username = metafunc.config.option.username
    if 'username' in metafunc.fixturenames and username is not None:
        metafunc.parametrize('username', [username])

    password = metafunc.config.option.password
    if 'password' in metafunc.fixturenames and password is not None:
        metafunc.parametrize('password', [password])

然后在我的设置文件中,我可以使用:
.vscode/settings.json

{
    // ...more...
    "python.testing.autoTestDiscoverOnSaveEnabled": true,
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.testing.pytestEnabled": true,
    "python.testing.pytestArgs": [
        " exitfirst",
        " verbose",
        "test/",
        " username=myname",
        " password=secret",
    // ...more...
    ],
}

另一种方法是使用pytest.ini文件:
pytest.ini

[pytest]
junit_family=legacy
addopts =  username=myname  password=secret

相关问题 更多 >