前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pytest fixture参数化params

Pytest fixture参数化params

作者头像
王大力测试进阶之路
发布2020-08-17 23:49:03
1.3K0
发布2020-08-17 23:49:03
举报
文章被收录于专栏:橙子探索测试橙子探索测试

unittest使用ddt来实现测试用例参数化、或parameterized实现测试用例参数化,pytest测试用例里面对应的参数可以用 parametrize 实现参数化,今天我们来了解下fixture参数化params

fixture的参数可以解决大量重复代码工作,比如数据库的连接、查询、关闭等.同样可以使用参数化来测试多条数据用例。

fixture源码:

传入参数scope,params,autouse,ids,name

代码语言:javascript
复制
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,request 是pytest的内置 fixture ,主要用于传递参数

1、获取账号密码案例:

代码语言:javascript
复制
import pytest

data = [("username1", "password1"), ("username2", "password2")]
# data = (("username1", "password1"), ("username2", "password2"))
# data = [["username1", "password1"], ["username2", "password2"]]

@pytest.fixture(scope = "function", params = data)
def get_data(request):
  print(request.param)
  return request.param

def test_login(get_data):
    print("账号:%s"%get_data[0],"密码:%s"%get_data[1])

if __name__ == '__main__':
    pytest.main(["-s", "test_C_01.py"])
    
    
    
 test_C_01.py ('username1', 'password1')
账号:username1 密码:password1
.('username2', 'password2')
账号:username2 密码:password2
.

============================== 2 passed in 0.08s ==============================

Process finished with exit code 0

2、前置准备后置清理案例:

代码语言:javascript
复制

import pytest
# 封装删除用户sql
def delete_user(user):
    sql = "delete from user where mobile = '%s'"%user
    print("删除用户sql:%s"%sql)
# 测试数据
mobile_data = ["18200000000", "18300000000"]

@pytest.fixture(scope="function", params=mobile_data)
def users(request):
    '''注册用户参数化'''
    # 前置操作
    delete_user(request.param)
    yield request.param
  # 后置操作
    delete_user(request.param)

def test_register(users):
    print("注册用户:%s"%users)

if __name__ == '__main__':
    pytest.main(["-s", "test_C_01.py"])
    
    
test_C_01.py 删除用户sql:delete from user where mobile = '18200000000'
注册用户:18200000000
.删除用户sql:delete from user where mobile = '18200000000'
删除用户sql:delete from user where mobile = '18300000000'
注册用户:18300000000
.删除用户sql:delete from user where mobile = '18300000000'


============================== 2 passed in 0.12s ==============================

Process finished with exit code 0
本文参与?腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-08-13,如有侵权请联系?cloudcommunity@tencent.com 删除

本文分享自 橙子探索测试 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体分享计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
http://www.vxiaotou.com