如何通过命令行在 pytest 中传递参数
- 2025-02-13 08:35:00
- admin 原创
- 42
问题描述:
我有一个代码,我需要从终端传递参数,例如名称。这是我的代码以及如何传递参数。我收到一个我不明白的“文件未找到”错误。
我已经在终端中尝试了该命令:pytest <filename>.py -almonds
我应该将名称打印为“杏仁”
@pytest.mark.parametrize("name")
def print_name(name):
print ("Displaying name: %s" % name)
解决方案 1:
在您的 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
解决方案 2:
使用pytest_addoption
钩子函数conftest.py
来定义一个新选项。
然后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"
command 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
.
解决方案 3:
我偶然发现了如何传递参数,但我想避免参数化测试。@clay 的最佳答案确实很好地解决了从命令行参数化测试的确切问题,但我想提供一种将命令行参数传递给特定测试的替代方法。下面的方法使用一个装置,如果指定了装置但未指定参数,则跳过测试:
测试.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 =========================
解决方案 4:
您所要做的就是使用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")
现在你可以运行测试了
def my_test(name):
assert name == 'myName'
使用:
pytest --name myName
解决方案 5:
这有点像变通方法,但它会将参数纳入测试。根据要求,这可能就足够了。
def print_name():
import os
print(os.environ['FILENAME'])
pass
然后从命令行运行测试:
FILENAME=/home/username/decoded.txt python3 setup.py test --addopts "-svk print_name"
解决方案 6:
根据命令行选项将不同的值传递给测试函数
假设我们要编写一个依赖于命令行选项的测试。以下是实现此目的的基本模式:
# 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
解决方案 7:
按照官方文档的说法,标记装饰器应该如下所示。
@pytest.mark.parametrize("arg1", ["StackOverflow"])
def test_mark_arg1(arg1):
assert arg1 == "StackOverflow" #Success
assert arg1 == "ServerFault" #Failed
跑步
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)
...
解决方案 8:
设法使它与unittest.TestCase
使用此处和https://docs.pytest.org/en/6.2.x/unittest.html的答案类一起工作
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}"))
测试参数
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
解决方案 9:
我读了很多关于这个的内容,但真的很困惑。我终于搞明白了,以下是我所做的:
首先建立文件名:conftest.py
Second 在里面添加如下代码:
# 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
新 param 装置将被使用的位置:将使用 param 的示例 Python 测试:
Test_MyFucntion(myParam)
解决方案 10:
如果你习惯使用 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.