如何通过命令行在pytest中传递参数

ash*_*kar 29 python pytest

我有一个代码,我需要传递像终端名称这样的参数.这是我的代码以及如何传递参数.我收到一个"文件未找到"的错误,我不明白.

我在终端尝试了这个命令:pytest <filename>.py -almonds 我应该把这个名字打印成"杏仁"

@pytest.mark.parametrize("name")
def print_name(name):
    print ("Displaying name: %s" % name)
Run Code Online (Sandbox Code Playgroud)

cla*_*lay 31

在你的pytest测试中,不要使用@pytest.mark.parametrize:

def test_print_name(name):
    print ("Displaying name: %s" % name)
Run Code Online (Sandbox Code Playgroud)

conftest.py:

def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")


def pytest_generate_tests(metafunc):
    # This is called for every test. Only get/set command line arguments
    # if the argument is specified in the list of test "fixturenames".
    option_value = metafunc.config.option.name
    if 'name' in metafunc.fixturenames and option_value is not None:
        metafunc.parametrize("name", [option_value])
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用命令行参数从命令行运行:

pytest -s tests/my_test_module.py --name abc
Run Code Online (Sandbox Code Playgroud)

  • 当您使用测试类时会发生什么?:) (4认同)
  • 不要使用它。我把它从答案中删除了。过去,它在旧版本的 pytest 中是支持甚至推荐的。在较新版本的 pytest 中,它已被删除且不受支持。 (3认同)

Gio*_*ous 14

所有你需要做的是使用pytest_addoption()conftest.py最后使用request夹具:

# conftest.py

from pytest import fixture


def pytest_addoption(parser):
    parser.addoption(
        "--name",
        action="store"
    )

@fixture()
def name(request):
    return request.config.getoption("--name")
Run Code Online (Sandbox Code Playgroud)

现在你可以运行你的测试

def my_test(name):
    assert name == 'myName'
Run Code Online (Sandbox Code Playgroud)

使用:

pytest --name myName
Run Code Online (Sandbox Code Playgroud)


Okk*_*ken 12

使用pytest_addoption挂钩函数conftest.py定义一个新选项。
然后pytestconfig在自己的灯具中使用灯具来获取名称。
您也可以pytestconfig从测试中使用它来避免编写自己的灯具,但是我认为选择使用自己的灯具会更干净。

# conftest.py

def pytest_addoption(parser):
    parser.addoption("--name", action="store", default="default name")
Run Code Online (Sandbox Code Playgroud)
# test_param.py 

import pytest

@pytest.fixture()
def name(pytestconfig):
    return pytestconfig.getoption("name")

def test_print_name(name):
        print(f"\ncommand line param (name): {name}")

def test_print_name_2(pytestconfig):
    print(f"test_print_name_2(name): {pytestconfig.getoption('name')}")
Run Code Online (Sandbox Code Playgroud)
# in action

$ pytest -q -s --name Brian test_param.py

test_print_name(name): Brian
.test_print_name_2(name): Brian
.
Run Code Online (Sandbox Code Playgroud)


ipe*_*rik 8

我在这里偶然发现了如何传递参数,但是我想避免参数化测试。上面的答案确实很好地解决了从命令行对测试进行参数化的确切问题,但是我想提供一种将命令行参数传递给特定测试的替代方法。如果指定了fixture,但未指定参数,则下面的方法使用fixture并跳过测试:

# test.py
def test_name(name):
    assert name == 'almond'


# conftest.py
def pytest_addoption(parser):
    parser.addoption("--name", action="store")

@pytest.fixture(scope='session')
def name(request):
    name_value = request.config.option.name
    if name_value is None:
        pytest.skip()
    return name_value
Run Code Online (Sandbox Code Playgroud)

例子:

$ py.test tests/test.py
=========================== test session starts ============================
platform linux -- Python 3.7.1, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
rootdir: /home/ipetrik/dev/pytest_test, inifile:
collected 1 item

tests/test.py s                                                      [100%]

======================== 1 skipped in 0.06 seconds =========================
Run Code Online (Sandbox Code Playgroud)
$ py.test tests/test.py --name notalmond
=========================== test session starts ============================
platform linux -- Python 3.7.1, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
rootdir: /home/ipetrik/dev/pytest_test, inifile:
collected 1 item

tests/test.py F                                                      [100%]

================================= FAILURES =================================
________________________________ test_name _________________________________

name = 'notalmond'

    def test_name(name):
>       assert name == 'almond'
E       AssertionError: assert 'notalmond' == 'almond'
E         - notalmond
E         ? ---
E         + almond

tests/test.py:5: AssertionError
========================= 1 failed in 0.28 seconds =========================
Run Code Online (Sandbox Code Playgroud)
$ py.test tests/test.py --name almond
=========================== test session starts ============================
platform linux -- Python 3.7.1, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
rootdir: /home/ipetrik/dev/pytest_test, inifile:
collected 1 item

tests/test.py .                                                      [100%]

========================= 1 passed in 0.03 seconds =========================
Run Code Online (Sandbox Code Playgroud)

  • ```python3 -m pytest test.py --name qwe``` 给出错误:```pytest.py: 错误:无法识别的参数:--name qwe```。我没有 py.test,在这种情况下我该怎么办,你能澄清一下吗? (2认同)
  • @ged - 按照你的称呼方式称呼它对我有用。请注意,您应该有两个文件 - conftest.py 和 test.py。我编辑了答案以使这一点更清楚。 (2认同)

小智 5

这是一种解决方法,但它会将参数带入测试中。根据要求,这可能就足够了。

def print_name():
    import os
    print(os.environ['FILENAME'])
    pass
Run Code Online (Sandbox Code Playgroud)

然后从命令行运行测试:

FILENAME=/home/username/decoded.txt python3 setup.py test --addopts "-svk print_name"
Run Code Online (Sandbox Code Playgroud)


Kir*_*hou 2

根据官方文档,标记装饰器应该如下所示。

@pytest.mark.parametrize("arg1", ["StackOverflow"])
def test_mark_arg1(arg1):
    assert arg1 == "StackOverflow" #Success
    assert arg1 == "ServerFault" #Failed
Run Code Online (Sandbox Code Playgroud)

跑步

python -m pytest <filename>.py
Run Code Online (Sandbox Code Playgroud)
  • 注意1:函数名必须以test_
  • 注意2:pytest会重定向stdout (print),因此直接运行stdout将无法在屏幕上显示任何结果。此外,无需在测试用例中的函数中打印结果。
  • 注3:pytest是python运行的模块,无法直接获取sys.argv

如果您确实想获取外部可配置参数,则应该在脚本内实现它。(例如加载文件内容)

with open("arguments.txt") as f:
    args = f.read().splitlines()
...
@pytest.mark.parametrize("arg1", args)
...
Run Code Online (Sandbox Code Playgroud)