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

Uri*_*Uri 7 python unit-testing pytest visual-studio-code

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

    "python.testing.pytestArgs": [
        "test/",
        "--exitfirst",
        "--verbose"
    ],
Run Code Online (Sandbox Code Playgroud)

我怎样才能将自定义脚本参数传递给测试脚本本身?就像从命令行调用 pytest 一样:

pytest --exitfirst --verbose test/ --test_arg1  --test_arg2
Run Code Online (Sandbox Code Playgroud)

Uri*_*Uri 5

经过大量实验,我终于找到了如何做到这一点。我需要的是将用户名和密码传递给我的脚本,以允许代码登录到测试服务器。我的测试是这样的:
my_module_test.py

import pytest
import my_module

def login_test(username, password):
    instance = my_module.Login(username, password)
    # ...more...
Run Code Online (Sandbox Code Playgroud)

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])
Run Code Online (Sandbox Code Playgroud)

然后在我的设置文件中我可以使用:
.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...
    ],
}

Run Code Online (Sandbox Code Playgroud)

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

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

Run Code Online (Sandbox Code Playgroud)