我有一段代码,需要从终端传递参数,比如姓名。 以下是我的代码以及传递参数的方法。但是我遇到了一个“文件未找到”的错误,不明白原因。
我在终端尝试了以下命令:pytest <filename>.py -almonds
应该会打印出姓名为“almonds”。
@pytest.mark.parametrize("name")
def print_name(name):
print ("Displaying name: %s" % name)
我有一段代码,需要从终端传递参数,比如姓名。 以下是我的代码以及传递参数的方法。但是我遇到了一个“文件未找到”的错误,不明白原因。
我在终端尝试了以下命令:pytest <filename>.py -almonds
应该会打印出姓名为“almonds”。
@pytest.mark.parametrize("name")
def print_name(name):
print ("Displaying name: %s" % name)
在你的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
ERROR: file or directory not found: abc
- Gulzar使用 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.mark.model_diagnostics
来区分那些需要输入的测试,例如pytest -m model_diagnostics --fp-model=./model.h5
。这还需要在您的pytest.ini
中“注册”您的标记。 - ryanjdillontest.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 =========================
python3 -m pytest test.py --name qwe
报错:pytest.py: error: unrecognized arguments: --name qwe
。我没有 py.test,这种情况下我该怎么办?请您解释一下。 - ged您只需要在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
这有点像是一个变通方法,但它可以将参数传递到测试中。根据要求,这可能足够了。
def print_name():
import os
print(os.environ['FILENAME'])
pass
然后从命令行运行测试:
FILENAME=/home/username/decoded.txt python3 setup.py test --addopts "-svk print_name"
根据命令行选项向测试函数传递不同的值
假设我们想编写一个依赖于命令行选项的测试。以下是一个基本的模式:
# 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")
然后您可以使用以下方式调用它:
pytest --cmdopt type1
通过这里的答案和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
@pytest.mark.parametrize("arg1", ["StackOverflow"])
def test_mark_arg1(arg1):
assert arg1 == "StackOverflow" #Success
assert arg1 == "ServerFault" #Failed
Run
python -m pytest <filename>.py
test_
开头。stdout(print)
,因此直接运行stdout将无法在屏幕上显示任何结果。另外,在测试用例中不需要在您的函数中打印结果。with open("arguments.txt") as f:
args = f.read().splitlines()
...
@pytest.mark.parametrize("arg1", args)
...
我读了很多关于这个的内容,感到非常困惑。最终我弄明白了,以下是我的做法:
首先创建一个名为: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)
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.