专栏首页从零开始学自动化测试pytest文档42-fixture参数化params

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:\soft\demo
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 后面,参考上面的格式。

本文分享自微信公众号 - 从零开始学自动化测试(yoyoketang),作者:上海悠悠

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2020-07-17

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 关于面试总结6-SQL经典面试题

    用一条SQL 语句查询xuesheng表每门课都大于80 分的学生姓名,这个是面试考sql的一个非常经典的面试题

    上海-悠悠
  • Selenium2+python自动化38-显示等待(WebDriverWait)

    前言: 在脚本中加入太多的sleep后会影响脚本的执行速度,虽然implicitly_wait()这种方法隐式等待方法随时一定程度上节省了很多时间。 但是一旦页...

    上海-悠悠
  • Selenium2+python自动化2-pip降级selenium3.0

    selenium版本安装后启动Firefox出现异常:'geckodriver' executable needs to be in PATH selenium...

    上海-悠悠
  • Pytest fixture参数化params

    unittest使用ddt来实现测试用例参数化、或parameterized实现测试用例参数化,pytest测试用例里面对应的参数可以用 parametrize...

    橙子探索测试
  • Ruby练习三

    用户2183996
  • 累了饿了困了?这些VR游戏新作让你容光焕发!

    VRPinea
  • 传统电竞愈演愈热,那VR电竞呢?

    近年来,电竞游戏风靡全球。国内电竞市场也在不断的发展壮大,渐渐的,电竞市场也成为了全民性的竞赛项目。今年5月,亚奥理事会正式宣布将《英雄联盟》等6项电子竞技游戏...

    VRPinea
  • 聊聊flink的ListCheckpointed

    flink-streaming-java_2.11-1.7.0-sources.jar!/org/apache/flink/streaming/api/chec...

    codecraft
  • 聊聊flink的ListCheckpointed

    flink-streaming-java_2.11-1.7.0-sources.jar!/org/apache/flink/streaming/api/chec...

    codecraft
  • 线下VR应该这样玩,The Void明年又将增设两个VR体验中心

    VRPinea

扫码关注云+社区

领取腾讯云代金券