在conftest中设置命令行参数,并给到环境变量

1、当我们有多套测试环境的时候,我们可以使用命令行快速切换测试环境,这个时候不需要去修改代码中的环境地址。
2.即在conftest中写命令行参数配置,并将该地址给到环境变量,用例中的地址也通过环境变量读取。在用例执行之前将去调用环境变量中的地址。

# conftest
# 通过命令行参数设置公共登录地址,此方法可以在cmd更改地址
import pytest
import os
# 设置命令行参数
def pytest_addoption(parser):
    parser.addoption(
        '--cmdhost',
        action='store',
        default='http://www.example.com', # 默认值
        help='test case project host address'
    )

# 设置url到环境变量,并设置前置(后面的用例都通过环境变量获取url)
@pytest.fixture(scope="function", autouse=True) # autouse=True自动生效,即执行用例之前就会生效
def login(request): #pytest内置fixture
    os.environ['host']=request.config.getoption('--cmdhost') # 通过request.config方法获取命令行参数url,给到环境变量os.environ['host']
    print('当前的运行地址是%s'%os.environ['host'])

用例测试

import os

# 在执行的时候,输入pytest -s 会使用conftest里面默认的地址
def test_a():
    print(os.environ['host'])

===================================================== test session starts ======================================================
platform win32 -- Python 3.6.0, pytest-4.5.0, py-1.8.0, pluggy-0.13.1
rootdir: D:\code\py_dev_test\pytest框架\pytest_base\命令行参数
plugins: allure-pytest-2.8.6, base-url-1.4.2, html-1.19.0, metadata-1.8.0
collected 1 item                                                                                                                

test_a.py 当前的运行地址是http://www.example.com
http://www.example.com
#如果切换了环境,我们可以在命令行切换地址,pytest --cmd="http://www.baidu.com"(引号里面的内容为切换的环境地址) -s
import os
def test_a():
    print(os.environ['host'])
===================================================== test session starts ======================================================
platform win32 -- Python 3.6.0, pytest-4.5.0, py-1.8.0, pluggy-0.13.1
rootdir: D:\code\py_dev_test\pytest框架\pytest_base\命令行参数
plugins: allure-pytest-2.8.6, base-url-1.4.2, html-1.19.0, metadata-1.8.0
collected 1 item                                                                                                                

test_a.py 当前的运行地址是http://www.baidu.com
http://www.baidu.com


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值