1. 前言
命令行參數(shù)是根據(jù)命令行選項(xiàng)將不同的值傳遞給測試函數(shù),比如平常在cmd執(zhí)行”pytest —html=report.html”,這里面的”—html=report.html“就是從命令行傳入的參數(shù)
對應(yīng)的參數(shù)名稱是html,參數(shù)值是report.html
2.contetest配置參數(shù)
1.首先需要在contetest.py添加命令行選項(xiàng),命令行傳入?yún)?shù)”—cmdopt“, 用例如果需要用到從命令行傳入的參數(shù),就調(diào)用cmdopt函數(shù):
# 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")
2.測試用例編寫案例
# content of test_sample.py
import pytest
def test_answer(cmdopt):
if cmdopt == "type1":
print("first")
elif cmdopt == "type2":
print("second")
assert 0 # to see what was printed
if __name__ == "__main__":
pytest.main(["-s", "test_case1.py"])
運(yùn)行結(jié)果:
>pytest -s
============================= test session starts =============================
test_sample.py first
F
================================== FAILURES ===================================
_________________________________ test_answer _________________________________
cmdopt = 'type1'
def test_answer(cmdopt):
if cmdopt == "type1":
print("first")
elif cmdopt == "type2":
print("second")
> assert 0 # to see what was printed
E assert 0
test_case1.py:8: AssertionError
========================== 1 failed in 0.05 seconds ===========================
3. 帶參數(shù)啟動
1.如果不帶參數(shù)執(zhí)行,那么傳默認(rèn)的default=”type1”,接下來在命令行帶上參數(shù)去執(zhí)行
$ pytest -s test_sample.py --cmdopt=type2
test_sample.py second
F
================================== FAILURES ===================================
_________________________________ test_answer _________________________________
cmdopt = 'type2'
def test_answer(cmdopt):
if cmdopt == "type1":
print("first")
elif cmdopt == "type2":
print("second")
> assert 0 # to see what was printed
E assert 0
test_case1.py:8: AssertionError
========================== 1 failed in 0.05 seconds ===========================