Pytest----定制自定义命令行参数
作者:redrose2100   类别:    日期:2022-05-15 05:25:00    阅读:903 次   消耗积分:0 分

如:增加一个 —country的命令行参数,通过命令行传入所在的国家

1 在用例根目录下创建conftest.py文件,编写代码如下:

首先 pytest_addoption 函数用来定义命令行的参数
country为自定义的fixture,用来获取从命令行传进来的参数值,这样测试用例中就可以通过加载fixture来获取命令行传入的参数的值了

  1. import pytest
  2. def pytest_addoption(parser):
  3. parser.addoption("--country", action="store", default="China",
  4. help="set country")
  5. @pytest.fixture()
  6. def country(request):
  7. return request.config.getoption("--country")

2 编写测试用例,如下:

  1. def test_demo(country):
  2. print("当前所在的国家:",country)
  • 在终端中执行如下命令执行脚本
  1. pytest -s --country=中国

执行结果如下:可以发现自定义命令行参数已经生效了,已经可以正常将命令行的中参数值传入到测试用例中了

  1. G:\redrose2100\src\demo>pytest -s --country=中国
  2. ========================================================================== test session starts ===========================================================================
  3. platform win32 -- Python 3.9.5, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
  4. rootdir: G:\redrose2100\src\demo
  5. plugins: allure-pytest-2.9.43, rerunfailures-10.0
  6. collected 1 item
  7. test_example.py 当前所在的国家: 中国
  8. .
  9. =========================================================================== 1 passed in 0.02s ============================================================================
  10. G:\redrose2100\src\demo>
始终坚持开源开放共享精神,同时感谢您的充电鼓励和支持!
版权所有,转载本站文章请注明出处:redrose2100, http://blog.redrose2100.com/article/207
个人成就
  • 2022年 : 371 篇 
  • 2023年 : 211 篇 
  • 2024年 : 31 篇 
  • 2025年 : 0 篇 
  • 博客总数: 613 
  • 阅读总量: 587610 
测试开发技术全栈公众号
DevOps技术交流微信群