1、參數化parametrize
(1)測試用例參數化使用裝飾器 pytest.mark.parametrize
參數化
參數化執行結果
(2)參數組合:獲取多個參數化參數的所有組合
參數組合實例
參數的所有組合
2、命令行傳參
根據命令行選項將不同的值傳給測試函數
(1)conftest.py添加命令選項,命令行傳入參數'--cmdfun'(需要建立cmdfun函數后才能調用)
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)創建test_sample.py添加用例
import pytest
def test_answer(cmdopt):
? ? if cmdopt == 'type1':
? ? ? ? print('first')
? ? elif cmdopt == 'type2':
? ? ? ? print('second')
? ? assert 0
if __name__ == '__main__':
? ? pytest.main(['-s', 'test_sample.py'])
(3)啟動
pycharm中直接執行即可
不帶參數啟動:pytest -s test_sample.py 默認啟動第一個
帶參數啟動:pytest -s test_sample.py --cmdopt=type2?