如何通过命令行在pytest中传递参数 [英] How to pass arguments in pytest by command line
本文介绍了如何通过命令行在pytest中传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个代码,我需要从终端传递诸如name之类的参数.这是我的代码以及如何传递参数.我收到了我不理解的找不到文件"类错误.
I have a code and I need to pass the arguments like name from terminal. Here is my code and how to pass the arguments. I am getting a "File not found" kind error that I don't understand.
我已经在终端中尝试了以下命令: pytest< filename> .py-杏仁
我应该将名称打印为杏仁"
I have tried the command in the terminal: pytest <filename>.py -almonds
I should get the name printed as "almonds"
@pytest.mark.parametrize("name")
def print_name(name):
print ("Displaying name: %s" % name)
推荐答案
在pytest测试中,请勿使用 @ pytest.mark.parametrize
:
In your pytest test, don't use @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])
然后,您可以使用命令行参数从命令行运行:
Then you can run from the command line with a command line argument:
pytest -s tests/my_test_module.py --name abc
这篇关于如何通过命令行在pytest中传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文