pytest学习10--命令行传参addoption
前言:
命令行参数是根据命令行选项将不同的值传递给测试函数,比如平常在cmd执行 “pytest--html=report.html”这里面的“--html=report.html”就是从命令行传入的参数,对应的参数名称是html,参数值是report.html
Conftest.py配置参数
1、首先需要在conftest.py添加命令行选项,命令行传入参数 ‘--cmdopt’, 用例如果需要用到从命令行传入的参数,就需要调用cmdopt函数
示例:conftest.py文件
# !/usr/bin/env python # -*-coding:utf-8 -*- """ # File : conftest.py # Time :2021/11/20 16:52 # Author :author Kong_hua_sheng_25304 # version :python 3.8 # Description: """ import pytest @pytest.mark.hookwrapper def pytest_runtest_makereport(item,call): """ :param item: 测试用例对象 :param call: 测试用例执行步骤 执行完常规钩子函数 返回的report报告有个属性叫report.when 先习性when = 'setup' 返回setup的执行结果 然后执行when = ‘call' 返回call的执行结果 然后执行when = 'teardown' 返回 teardown的执行结果 :return: """ print("------------------------") # 获取钩子方法的调用结果 out = yield # 从钩子方法的调用结果中 获取测试报告 report = out.get_result() print('测试报告:%s'%report) print('步骤:%s'%report.when) print('nodeid:%s'%report.nodeid) print('description : %s'%str(item.function.__doc__)) print('运行结果: %s'%report.outcome) def pytest_addoption(parser): parser.addoption("--cmdopt",action = 'store',default='type1',help='my option:type1 or type2') @pytest.fixture(scope='session',autouse=True) def cmdopt(request): return request.config.getoption("--cmdopt") @pytest.fixture(scope='session',autouse=True) def fix_a(request): print("setup 前置函数") def fin_down(): print("teardown后置函数") request.addfinalizer(fin_down)
测试用例文件:
import pytest def test_a(cmdopt): """用例描述Test_a""" if cmdopt == 'type1': print("---first---type1-") elif cmdopt == 'type2': print("---second---type2---") print("用例描述 ----------test_a------------")
在cmd中执行命令pytest -s test_a.py运行结果如下:
执行pytest -s --cmdopt type2 test_a.py