我们可以在命令行中使用pytest传递自定义参数excelpath,然后在测试脚本中获取excelpath的路径,然后解析成数据集批量执行。
一、代码实现
import pytest def pytest_addoption(parser): parser.addoption("--excelpath", action="store", default=None, help="The Excel path that stores test datas.") @pytest.fixture def excelpath(request): return request.config.getoption("--excelpath") def test_get_cases(excelpath): print(f'excelpath: {excelpath}') # values = parse_excel(excelpath) # return values return [1, 2, 3] # demo for values @pytest.mark.parametrize('case', test_get_cases(excelpath)) def test_runner(case): print(case)
二、Demo验证
命令行中运行:
python -m pytest tests/test_cases.py --excelpath=path/to/excel -s
运行结果:
=========================================================================================================================================================== test session starts =========================================================================================================================================================== platform win32 -- Python 3.9.18, pytest-7.4.0, pluggy-1.0.0 rootdir: D:\BaiduSyncdisk\xyouwen-workspace\ddautotest plugins: dependency-0.5.1 collecting ... excelpath: <function excelpath at 0x0000011F8261E940> collected 4 items tests\test_cases.py excelpath: path/to/excel .1 .2 .3 . ============================================================================================================================================================ warnings summary ============================================================================================================================================================= tests/test_cases.py::test_get_cases D:\ProgramFiles\anaconda3\envs\ddautotest\lib\site-packages\_pytest\python.py:198: PytestReturnNotNoneWarning: Expected None, but tests/test_cases.py::test_get_cases returned [1, 2, 3], which will be an error in a future version of pytest. Did you mean to use `assert` instead of `return`? warnings.warn( -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html ====================================================================================================================================================== 4 passed, 1 warning in 0.02s
三、最终代码
避免警告提示,可以在代码中添加:
pytestmark = pytest.mark.filterwarnings("ignore::pytest.PytestReturnNotNoneWarning")
完整代码为:
import pytest pytestmark = pytest.mark.filterwarnings("ignore::pytest.PytestReturnNotNoneWarning") def pytest_addoption(parser): parser.addoption("--excelpath", action="store", default=None, help="The Excel path that stores test datas.") @pytest.fixture def excelpath(request): return request.config.getoption("--excelpath") def test_get_cases(excelpath): print(f'excelpath: {excelpath}') # values = parse_excel(excelpath) # return values return [1, 2, 3] # demo for values @pytest.mark.parametrize('case', test_get_cases(excelpath)) def test_runner(case): print(case)