zoukankan      html  css  js  c++  java
  • Pytest单元测试框架之parametrize参数化

    1、参数化的本质:相同的步骤,但测试数据不同,比如登录的场景

    import math
    import pytest

    # 方式一:分离出List
    def list_Test():
    list = [
    [2, 2, 4],
    [2, 3, 8],
    [1, 9, 1],
    [0, 9, 0],
    ]
    return list
    @pytest.mark.parametrize('a,b,expect',list_Test())
    def test_add_one(a,b,expect):
    # 断言 -- 某数的平方=expect对象
    assert math.pow(a,b) == expect

    # 方式二:分离出tuple
    def tuple_Test():
    tuple = [
    (2, 2, 4),
    (2, 3, 8),
    (1, 9, 1),
    (0, 9, 0),
    ]
    return tuple
    @pytest.mark.parametrize('a1,b1,expect1',tuple_Test())
    def test_add_two(a1,b1,expect1):
    # 断言 -- 某数的平方=expect对象
    assert math.pow(a1,b1) == expect1

    # 方式三:分离出dict
    def dict_Test():
    dict = [
    {'a': 2, 'b': 2, 'expect': 4},
    {'a': 2, 'b': 3, 'expect': 8},
    {'a': 2, 'b': 4, 'expect': 16},
    {'a': 1, 'b': 9, 'expect': 1},
    ]
    return dict
    @pytest.mark.parametrize('datas',dict_Test())
    def test_add_three(datas):
    # 断言 -- 某数的平方=expect对象
    assert math.pow(datas['a'],datas['b']) == datas['expect']

    # 方式四: 使用pytest.param方法进行分离
    def param_Test():
    param = [
    pytest.param(1, 1, 1,id='one'),
    pytest.param(2, 2, 4,id='two'),
    pytest.param(3, 3, 27,id='three')
    ]
    return param
    # ids参数默认为None,用于定义测试用例的名称
    @pytest.mark.parametrize('a,b,expect',param_Test())
    def test_add_four(a,b,expect):
    # 断言 -- 某数的平方=expect对象
    assert math.pow(a,b) == expect

    if __name__ == '__main__':
    pytest.main(['-v','-s','test_mark.param.py'])

    运行代码结果如下:

     2、固件request

    在Pytest的测试框架中,参数化也会使⽤到pytest内置的固件request,通过request.param来获取参数,对上面的案例代码进行修改,fixture参数列表中request也是内建fixture
    import pytest
    import math

    def datas():
    dict_param = [
    {'a': 2, 'b': 2, 'expect': 4},
    {'a': 2, 'b': 3, 'expect': 8},
    {'a': 2, 'b': 4, 'expect': 16},
    ]
    return dict_param

    @pytest.fixture(params=datas())
    def getParams(request):
    return request.param

    def test_math_pow(getParams):
    # 断言 -- 某数的平方=expect对象
    assert math.pow(getParams['a'],getParams['b']) == getParams['expect']

    if __name__ == '__main__':
    pytest.main(['-v','-s','test_mark.param.py'])

    代码运行结果如下:
  • 相关阅读:
    点击劫持漏洞之理解 python打造一个挖掘点击劫持漏洞的脚本
    URL重定向漏洞,python打造URL重定向漏洞检测脚本
    动态链接库(DLL)
    vs不支持通过afxgetmainwnd()获取窗口句柄(转)
    HALCON学习-下载、安装
    HALCON学习-资料
    MFC,ADO方式实现数据库操作
    VS2010 EXCEL2010 表格操作的编程实现
    Git Compare with base,比较大文件时,长时间等待,无法加载
    VS2010编译VS2008工程时,LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt
  • 原文地址:https://www.cnblogs.com/Teachertao/p/14675018.html
Copyright © 2011-2022 走看看