前言
命令行參數是根據命令行選項將不同的值傳遞給測試函數,比如平常在cmd執行"pytest --html=report.html",這里面的”--html=report.html“就是從命令行傳入的參數
對應的參數名稱是html,參數值是report.html
conftest配置參數
1.首先需要在conftest.py添加命令行選項,命令行傳入參數”--cmdopt“, 用例如果需要用到從命令行傳入的參數,就調用cmdopt函數:
# 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"])
cmd打開,輸入指令啟動,也可以在pycharm里面右鍵執行上面代碼
$ pytest -s test_sample.py
運行結果:
>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 ===========================
帶參數啟動
1.如果不帶參數執行,那么傳默認的default="type1",接下來在命令行帶上參數去執行
$ 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 ===========================
2.命令行傳參數有兩種寫法,還有一種分成2個參數也可以的,參數和名稱用空格隔開
$ pytest -s test_case1.py --cmdopt type2