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

135

我有一段代码,需要从终端传递参数,比如姓名。 以下是我的代码以及传递参数的方法。但是我遇到了一个“文件未找到”的错误,不明白原因。

我在终端尝试了以下命令:pytest <filename>.py -almonds 应该会打印出姓名为“almonds”。

@pytest.mark.parametrize("name")
def print_name(name):
    print ("Displaying name: %s" % name)

1
需要考虑的一件事是,pytest真的希望您能够在命令行上指定多个测试文件。在这种情况下,命令行参数会发生什么?每个人都使用-almonds吗?如果两个不同的测试需要不同的参数怎么办? - James Moore
10个回答

105

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

def test_print_name(name):
    print ("Displaying name: %s" % name)

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])

然后你可以在命令行中使用命令行参数运行:

pytest -s tests/my_test_module.py --name abc

3
不要使用它。我已经从答案中删除了它。在过去,它得到了支持,甚至在较旧的pytest版本中被推荐使用。在较新的pytest版本中,它已被删除并不再受支持。 - clay
4
当您使用测试类时会发生什么? :) - Roelant
你能否指出如何将参数添加到测试“fixturenames”列表中,就像你在答案中所说的那样。 - dor00012
1
可以在pytest文档中查看pytest_generate_tests的解释。 - dor00012
ERROR: file or directory not found: abc - Gulzar
显示剩余2条评论

94

使用 conftest.py 中的 pytest_addoption 钩子函数来定义一个新选项。
然后在自己的夹具中使用 pytestconfig 夹具来获取名称。
您还可以从测试中使用 pytestconfig,以避免编写自己的夹具,但我认为让选项拥有它自己的名称更加清晰。

# conftest.py

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

import pytest

@pytest.fixture(scope="session")
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')}")
# in action

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

test_print_name(name): Brian
.test_print_name_2(name): Brian
.

我遵循了这个模式,并在我的情况下还添加了一个pytest标记@pytest.mark.model_diagnostics来区分那些需要输入的测试,例如pytest -m model_diagnostics --fp-model=./model.h5。这还需要在您的pytest.ini中“注册”您的标记。 - ryanjdillon

53
我在这里搜索如何传递参数,但我想避免将测试参数化。@clay's top answer回答完美地解决了从命令行参数化测试的确切问题,但我想提供一种替代方法来将命令行参数传递给特定的测试。下面的方法使用一个fixture,如果指定了fixture但没有指定参数,则跳过测试:

test.py:

def test_name(name):
    assert name == 'almond'

conftest.py:

import pytest

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

例子:

$ 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 =========================

$ 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 =========================

$ 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 =========================

2
python3 -m pytest test.py --name qwe 报错:pytest.py: error: unrecognized arguments: --name qwe。我没有 py.test,这种情况下我该怎么办?请您解释一下。 - ged
2
@ged - 按照您所说的方式进行调用对我有效。请注意,您应该有两个文件 - conftest.py 和 test.py。我已经编辑了答案,使其更加清晰明了。 - ipetrik
还没有被接受的答案带有绿色勾选标记,所以您指的是哪一个? - thewhiteambit
说得好 - 我不知道为什么我写这篇文章时认为@clay的答案被接受了,但我想这只是最受欢迎的答案。我更新了我的回答。 - ipetrik

25

您只需要在conftest.py中使用pytest_addoption(),最后使用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")

现在,您可以运行您的测试。


def my_test(name):
    assert name == 'myName'

使用:

pytest --name myName

我收到了这个错误信息:pytest: error: unrecognized arguments: --name - aksyuma

5

这有点像是一个变通方法,但它可以将参数传递到测试中。根据要求,这可能足够了。

def print_name():
    import os
    print(os.environ['FILENAME'])
    pass

然后从命令行运行测试:

FILENAME=/home/username/decoded.txt python3 setup.py test --addopts "-svk print_name"

3

根据命令行选项向测试函数传递不同的值
假设我们想编写一个依赖于命令行选项的测试。以下是一个基本的模式:

# content of test_sample.py
def test_answer(cmdopt):
    if cmdopt == "type1":
        print("first")
    elif cmdopt == "type2":
        print("second")
    assert 0  # to see what was printed

For this to work we need to add a command line option and provide the cmdopt through a fixture function:

# content of conftest.py
import pytest


def pytest_addoption(parser):
    parser.addoption(
        "--cmdopt", action="store", default="type1", help="my option: type1 or type2"
    )


@pytest.fixture
def cmdopt(request):
    return request.config.getoption("--cmdopt")

参考链接: https://docs.pytest.org/en/latest/example/simple.html#pass-different-values-to-a-test-function-depending-on-command-line-options

然后您可以使用以下方式调用它:

pytest --cmdopt type1

2

通过这里的答案和https://docs.pytest.org/en/6.2.x/unittest.html,成功使用unittest.TestCase类使其工作。

conftest.py:

import pytest

my_params = {
    "name": "MyName",
    "foo": "Bar",
}


def pytest_addoption(parser):
    for my_param_name, my_param_default in my_params.items():
        parser.addoption(f"--{my_param_name}", action="store", default=my_param_default)


@pytest.fixture()
def pass_parameters(request):
    for my_param in my_params:
        setattr(request.cls, my_param, request.config.getoption(f"--{my_param}"))

test_param.py

import unittest
import pytest


@pytest.mark.usefixtures("pass_parameters")
class TestParam(unittest.TestCase):
    def test_it(self):
        self.assertEqual(self.name, "MyName")

使用:
pytest --name MyName

2
根据官方文件,标记修饰符应该如下所示。
@pytest.mark.parametrize("arg1", ["StackOverflow"])
def test_mark_arg1(arg1):
    assert arg1 == "StackOverflow" #Success
    assert arg1 == "ServerFault" #Failed

Run

python -m pytest <filename>.py
  • 注意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)
...

0

我读了很多关于这个的内容,感到非常困惑。最终我弄明白了,以下是我的做法:

首先创建一个名为:conftest.py 的文件。 其次,在其中添加以下代码:

# this is a function to add new parameters to pytest
def pytest_addoption(parser):
    parser.addoption(
        "--MyParamName", action="store", default="defaultParam", help="This is a help section for the new param you are creating"
    )
# this method here makes your configuration global
option = None
def pytest_configure(config):
    global option
    option = config.option

最后,您将使用夹具访问新创建的参数,以公开所需代码中的参数:
@pytest.fixture
def myParam(request):
    return request.config.getoption('--MyParamName')

以下是如何在pytest执行中使用新创建的参数

# command to run pytest with newly created param
$ pytest --MyParamName=myParamValue

新参数 fixture 将被使用的位置: 使用 param 的示例 python 测试:

Test_MyFucntion(myParam)

-4
如果您习惯于使用 argparse,您可以按照通常的方式在 arparse 中准备它。
import argparse
import sys

DEFAULT_HOST = test99
#### for --host parameter ###
def pytest_addoption(parser):
    parser.addoption("--host")   # needed otherwhise --host will fail pytest

parser = argparse.ArgumentParser(description="run test on --host")
parser.add_argument('--host', help='host to run tests on (default: %(default)s)', default=DEFAULT_HOST)
args, notknownargs = parser.parse_known_args()
if notknownargs:
    print("pytest arguments? : {}".format(notknownargs))
sys.argv[1:] = notknownargs

#
then args.hosts holds you variable, while sys.args is parsed further with pytest.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接