1、pytest_addoption:动态添加命令行参数(钩子函数)
一、背景:
- 自动化用例需要支持在不同的环境运行:有时候是test测试环境,有时候是dev生产环境
- 执行不同的业务逻辑:给某个参数传入不同的参数值来执行不同的业务逻辑
二、解决方案:
可以通过“自定义一个命令行参数,并在命令行中输入这个参数,然后在测试中用例中接收这个参数,通过判断这个参数的值来做不同的逻辑”来实现
那么我们的需求就变为:pytest中如何自定义一个命令行参数呢?这时候我们就需要用到pytest的钩子函数:pytest_addoption
三、具体实现:
1、新建一个conftest.py文件,然后在conftest.py文件中通过pytest_addoption方法来添加命令行参数,通过定义的fixture来获得参数的值
1 import pytest 2 3 4 def pytest_addoption(parser): 5 6 # 注册自定义参数cmdopt到配置对象 7 parser.addoption( 8 "--cmdopt", action="store", default="type1", help="my option: type1 or type2" 9 ) 10 # 注册自定义参数env到配置对象 11 parser.addoption( 12 "--env", action="store", default="dev", help="env:表示测试环境,默认dev环境" 13 ) 14 15 16 @pytest.fixture() 17 def cmdopt(pytestconfig): 18 # 从配置对象获取cmdopt的值 19 return pytestconfig.getoption("--cmdopt") 20 21 22 @pytest.fixture() 23 def env(request): 24 # 从配置对象获取env的值 25 return request.config.getoption("--env")
备注:
1)新增了两个命令行参数:--cmdopt和--env
2)然后定义了两个fixture
3)在测试用例中想要获得参数--cmdopt的值、就可以调用cmdopt函数,想要获得参数--env的值、就可以调用env函数
2、编写测试用例test_option.py
1 import pytest 2 3 4 def test_option(env): 5 if env == 'dev': 6 print("当前环境为:{},域名切换为开发环境".format(env)) 7 elif env == 'test': 8 print("当前环境为:{},域名切换为测试环境".format(env)) 9 else: 10 print("环境错误,当前环境{}不存在".format(env)) 11 12 13 if __name__ == '__main__': 14 pytest.main(['-s', 'test_option.py'])
备注:获取env的值,针对不同的env值做不同的操作
3、测试用例运行:
1)不带参数运行:默认dev环境
pytest -s test_option.py ================================================================== test session starts ============================== platform darwin -- Python 3.11.0, pytest-7.4.0, pluggy-1.2.0 rootdir: /Users/chunyanzhang/Projects/Pycharm/Pytest/testcase plugins: allure-pytest-2.13.2 collected 1 item test_option.py 当前环境为:dev,域名切换为开发环境 . ============================================================== 1 passed in 0.02s ===============================
2) 带参数运行:可以指定为test环境
1 pytest -s --env=test test_option.py 2 ============================================== test session starts ================================== 3 platform darwin -- Python 3.11.0, pytest-7.4.0, pluggy-1.2.0 4 rootdir: /Users/chunyanzhang/Projects/Pycharm/Pytest/testcase 5 plugins: allure-pytest-2.13.2 6 collected 1 item 7 8 test_option.py 当前环境为:test,域名切换为测试环境 9 . 10 11 ================================= 1 passed in 0.00s ==================================================
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具