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