我有一個代碼,我需要從終端傳遞名稱這樣的參數。 這是我的代碼和如何傳遞參數。我收到錯誤。沒有找到文件類的東西。我無法理解。如何通過命令行在pytest中傳遞參數
我已經在終端嘗試了命令:pytest <filename>.py -almonds
我應該得到的名字印爲「杏仁」
@pytest.mark.parametrize("name")
def print_name(name):
print ("Displaying name: %s" % name)
我有一個代碼,我需要從終端傳遞名稱這樣的參數。 這是我的代碼和如何傳遞參數。我收到錯誤。沒有找到文件類的東西。我無法理解。如何通過命令行在pytest中傳遞參數
我已經在終端嘗試了命令:pytest <filename>.py -almonds
我應該得到的名字印爲「杏仁」
@pytest.mark.parametrize("name")
def print_name(name):
print ("Displaying name: %s" % name)
按照official document,標誌裝飾應如下。
@pytest.mark.parametrize("arg1", ["StackOverflow"])
def test_mark_arg1(arg1):
assert arg1 == "StackOverflow" #Success
assert arg1 == "ServerFault" #Failed
運行
python -m pytest <filename>.py
test_
stdout (print)
,從而直接運行標準輸出將不能夠顯示出對任何結果屏幕。另外,在測試用例中不需要在你的函數中打印結果。如果你真的想要得到外面配置參數,你應該怎麼實現你的腳本里面。 (例如,加載文件的內容)
with open("arguments.txt") as f:
args = f.read().splitlines()
...
@pytest.mark.parametrize("arg1", args)
...
在你pytest測試,不要使用@pytest.mark.parametrize
:
@pytest.mark.unit
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