在日常的UI自动化测试中,可能使用涉及到多个场景,例如测试、预发、生产环境,这就需要我们进行环境切换,如果在不同的环境下我们要指定不同的系统配置,每次修改框架代码配置这个很不自动化,给测试造成了不必要的麻烦。
针对这种情况,pytest提供了一种方法:pytest_addoption注册参数,使用这个注册参数就可以解决了这种问题,可以在执行用例、命令的时候传递参数。
用法pytest_addoption注册参数一般和内置 fixture pytestconfig 配合使用,pytest_addoption 注册命令行参数, 通过pytestconfig配置对象读取参数的值。示例如下:
# 注册自定义参数 cys 到配置对象
def pytest_addoption(parser):
parser.addoption("--cys", action="store",
default='这个cys的默认值说明',
help="将命令行参数 ’--cys' 添加到 pytest 配置中")
# 从配置对象中读取自定义参数的值
@pytest.fixture(scope="session")
def cys(request):
return request.config.getoption("--cys")
用例运行:
# 将自定义参数的值打印出来
@pytest.fixture(autouse=True)
def suite_1(cys):
print('n --cys的值:', cys)
if __name__ == '__main__':
# 使用参数
pytest.main(['-s'])
可以看出suite_1函数虽然没有进行参数赋值,但是它通过pytestconfig获取了配置对象方法。
参数说明同时parser.addoption()的一些参数含义使用如下:
name:自定义命令行参数的名字,可以是:"foo", "-foo" 或 "--foo";
action:在命令行中遇到此参数时要采取的基本操作类型;
nargs:应该使用的命令行参数的数量;
const:某些操作和nargs选择所需的常量值;
default:如果参数不在命令行中,则生成的默认值。
type:命令行参数应该转换为的类型;
choices:参数允许值的容器;
help:对参数作用的简要说明;
以下拿几个常用的参数使用来介绍一下:
1、action=“store”:默认,只存储参数的值,该值类型任意,并且同时的话default也可以是任何类型值。
2、action = "apped",存储的是一个list列表值,而且同时default也要是一个列表值,pytest 会把 default 默认参数的值和多个自定义参数的值放在一个列表中,例如:
# 注册自定义参数 cys 到配置对象
def pytest_addoption(parser):
parser.addoption("--cys", action="append",
default=['这个cys的默认值说明'],
help="将命令行参数 ’--cys' 添加到 pytest 配置中")
# 从配置对象中读取自定义参数的值
@pytest.fixture(scope="session")
def cys(request):
return request.config.getoption("--cys")
# 将自定义参数的值打印出来
@pytest.fixture(autouse=True)
def suite_1(cys):
print('n --cys的值:', cys)
if __name__ == '__main__':
# 使用参数
pytest.main(['-s','--cys=111','--cys=222'])
3、type:type类型包含python的数据类型,例如str,int,list,dict,float等,默认是str类型。这里同样注意的是,如果指定type类型的话,default也要指定相同的数据类型。
# 注册自定义参数 cys 到配置对象
def pytest_addoption(parser):
parser.addoption("--cys", action="store",
default=888,
type = int,
help="将命令行参数 ’--cys' 添加到 pytest 配置中")
# 从配置对象中读取自定义参数的值
@pytest.fixture(scope="session")
def cys(request):
return request.config.getoption("--cys")
# 将自定义参数的值打印出来
@pytest.fixture(autouse=True)
def suite_1(cys):
print('n --cys的值:', cys)
if __name__ == '__main__':
# 使用参数
pytest.main(['-s','--cys=111'])
4、choices参数允许值的容器,也就是说参数取值要在这个容器中,超出给定值就会报错,例如:
# 注册自定义参数 cys 到配置对象
def pytest_addoption(parser):
parser.addoption("--cys", action="store",
default=888,
choices=['python', 'java', 'c++'],
help="将命令行参数 ’--cys' 添加到 pytest 配置中")
# 从配置对象中读取自定义参数的值
@pytest.fixture(scope="session")
def cys(request):
return request.config.getoption("--cys")
# 将自定义参数的值打印出来
@pytest.fixture(autouse=True)
def suite_1(cys):
print('n --cys的值:', cys)
if __name__ == '__main__':
# 使用参数
pytest.main(['-s','--cys=python'])
如果,此时我传了一个不在choices中的参数,运行就会报错:



