【问题标题】:How to pass command line arguments to pytest tests running in vscode如何将命令行参数传递给在 vscode 中运行的 pytest 测试
【发布时间】:2020-07-02 06:41:55
【问题描述】:

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

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

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

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

【问题讨论】:

  • 这能回答你的问题吗? How to pass arguments in pytest by command line
  • 这篇文章回答了如何将参数传递给测试脚本的问题。 不是这篇文章的主题。我对如何在 vscode 中做同样的事情感兴趣
  • 很抱歉,我看不出有什么不同。您在问题中引用了一个 pytest 命令行,并且链接中的答案中有带有参数的示例命令行。
  • 从命令行运行 pytest 不允许调试 vscode 中的测试。从命令行调用允许进入 pdb 以单步执行代码。使用 vscode 交互式调试器的能力要优越得多。

标签: python unit-testing visual-studio-code pytest


【解决方案1】:

经过多次试验,我终于找到了方法。我需要将用户名和密码传递给我的脚本,以允许代码登录到测试服务器。我的测试如下所示:
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

【讨论】:

  • vscode 是否提供了一些方法来轻松地在 UI 中更改它?例如,如果您想有时向它传递不同的“用户名”和“密码”怎么办。是在运行测试之前修改 settings.json 的唯一方法,还是有 UI 功能可以使用不同的 args 设置测试运行?
  • @red888 我假设您询问的是在运行测试时提示输入用户名和密码。 AFAIK,没有互动的方式。您必须在执行前更改设置文件。
  • 其实看起来是可以交互完成的。我还没有尝试过,所以我不确定它是否适用于单元测试。查看更多信息here
【解决方案2】:

如果这只是用于调试器,那么您可以在launch.json 文件中的"args" 中指定内容。详情请见https://code.visualstudio.com/docs/python/debugging#_args

【讨论】:

  • 问题不在于简单的调试。我正在尝试使用单元测试扩展,它在每个单元测试上公开一个按钮,从而可以调试单个测试用例。我知道使用参数调用这些测试用例的唯一方法是以上述方式提供参数。
猜你喜欢
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多