pytest文档42-fixture参数化params
时间:2022-07-22
本文章向大家介绍pytest文档42-fixture参数化params,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
前言
参数化是自动化测试里面必须掌握的一个知识点,用过 unittest 框架的小伙伴都知道使用 ddt 来实现测试用例的参数化。 pytest 测试用例里面对应的参数可以用 parametrize 实现,随着用例的增多,我们的需求也会越来越多,那么如何在 fixture 中使用参数呢?
fixture 源码
先看下 fixture 源码,有这几个参数:scope,params,autouse,ids,name。
def fixture(scope="function", params=None, autouse=False, ids=None, name=None):
"""Decorator to mark a fixture factory function.This decorator can be used, with or without parameters, to define a
fixture function.The name of the fixture function can later be referenced to cause its
invocation ahead of running tests: test
modules or classes can use the ``pytest.mark.usefixtures(fixturename)``
marker.Test functions can directly use fixture names as input
arguments in which case the fixture instance returned from the fixture
function will be injected.Fixtures can provide their values to test functions using ``return`` or ``yield``
statements. When using ``yield`` the code block after the ``yield`` statement is executed
as teardown code regardless of the test outcome, and must yield exactly once.:arg scope: the scope for which this fixture is shared, one of
``"function"`` (default), ``"class"``, ``"module"``,
``"package"`` or ``"session"``.``"package"`` is considered **experimental** at this time.:arg params: an optional list of parameters which will cause multiple
invocations of the fixture function and all of the tests
using it.
The current parameter is available in ``request.param``.:arg autouse: if True, the fixture func is activated for all tests that
can see it. If False (the default) then an explicit
reference is needed to activate the fixture.:arg ids: list of string ids each corresponding to the params
so that they are part of the test id. If no ids are provided
they will be generated automatically from the params.:arg name: the name of the fixture. This defaults to the name of the
decorated function. If a fixture is used in the same module in
which it is defined, the function name of the fixture will be
shadowed by the function arg that requests the fixture; one way
to resolve this is to name the decorated function
``fixture_<fixturename>`` and then use
``@pytest.fixture(name='<fixturename>')``.
"""
if callable(scope) and params is None and autouse is False:
# direct decoration
return FixtureFunctionMarker("function", params, autouse, name=name)(scope)
if params is not None and not isinstance(params, (list, tuple)):
params = list(params)
return FixtureFunctionMarker(scope, params, autouse, ids=ids, name=name)
重点看 params 参数:一个可选的参数列表,它将导致多次调用fixture函数和使用它的所有测试
获取当前参数可以使用 request.param
:arg params: an optional list of parameters which will cause multiple
invocations of the fixture function and all of the tests
using it.
The current parameter is available in ``request.param``.
fixture 之 params 使用示例
request 是pytest的内置 fixture ,主要用于传递参数
# test_fixture_params.py
import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/# 测试数据,存放在list
user_data = ["user1", "user2"]@pytest.fixture(scope="function", params=user_data)
def users(request):
'''注册用户参数化'''
return request.paramdef test_register(users):
print("注册用户:%s"%users)if __name__ == '__main__':
pytest.main(["-s", "test_fixture_params"])
运行结果
>pytest test_fixture_params.py -s
============================= test session starts =============================
platform win32 -- Python 3.6.0, pytest-4.5.0, py-1.5.4, pluggy-0.13.1
rootdir: D:softdemo
plugins: allure-pytest-2.8.6
collected 2 itemstest_fixture_params.py 注册用户:user1
.注册用户:user2
.========================== 2 passed in 0.02 seconds ===========================
前置与后置
如果每次注册用户之前,需先在前置操作里面清理用户注册表的数据,可以执行SQL,传不同用户的参数
# test_fixture_params.py
import pytest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/def delete_sql(user):
'''这里执行SQL'''
sql = "delete from auth_user WHERE username = '%s';"%user
print("执行的sql:%s"%sql)
# 调用执行SQL的封装函数# 测试数据,存放在list
user_data = ["user1", "user2"]@pytest.fixture(scope="function", params=user_data)
def users(request):
'''注册用户参数化'''# 前置操作
delete_sql(request.param)yield request.param# # 后置操作
# delete_sql(request.param)def test_register(users):
print("注册用户:%s"%users)if __name__ == '__main__':
pytest.main(["-s", "test_fixture_params.py"])
运行结果
collected 2 itemstest_fixture_params.py 执行的sql:delete from auth_user WHERE username = 'user1';
注册用户:user1
.执行的sql:delete from auth_user WHERE username = 'user2';
注册用户:user2
.========================== 2 passed in 0.06 seconds ===========================
后置操作可以写到 yield 后面,参考上面的格式。
- WordPress设置评论到达一定数量后自动关闭评论功能
- Python 项目实践一(外星人入侵)第一篇
- 外媒:域名Covermate.com超35万终端交易
- 移除WordPress 管理后台的主题编辑功能
- 百度区域链开放平台“BaaS”启用了二级子域名chain.baidu.com
- Qt界面UI之QML初见(学习笔记四)
- 清新唯美的jQuery天气预报插件(网页天气预报插件)
- 32和64位的CentOS 6.0下 安装 Mono 2.10.8 和Jexus 5.0
- 跨平台的 .NET 运行环境 Mono 3.2 新特性
- Ibatisnet Quick Start
- 常见的3种Hive参数配置方法
- 6杂域名超16万元结拍
- GridView控件使用经验
- WordPress登陆文件wp-login.php添加相关参数,安全有保障
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- MapperReduce常见错误及解决方案
- MapReduce案例之寻找共同好友
- JavaScript或ES6如何实现多继承总结【Mixin混合继承模式】
- Hadoop之MapReduce开发总结
- python之文件操作
- 血的教训!千万别在生产使用这些 redis 指令
- Python selenium chrome parses blob url
- 实战|仅用18行JavaScript构建一个倒数计时器
- 译|通过Node和Redis进行API速率限制
- EasySwoole实现Execl导入导出
- 设计模式:参与者风格
- vuepress集成element-ui
- 如何利用unli-app框架快速构建EasyRTC_SFU安卓app项目?
- 离线安装Superset 0.37
- GO 语言 FAQ