• Pytest(8)parametrize参数化


    前言

    当某个接口中的一个字段,里面规定的范围为1-5,你5个数字都要单独写一条测试用例,就太麻烦了,这个时候可以使用pytest.mark.parametrize装饰器可以实现测试用例参数化。
     

    官方示例

    下面是一个典型的范例,检查特定的输入所期望的输出是否匹配:

    # test_expectation.py 
    import pytest 
    
    @pytest.mark.parametrize("test_input, expected", [("3+5", 8), ("2+4", 6), ("6*9", 42),]) 
    def test_eval(test_input, expected): 
      assert eval(test_input) == expected
    

    测试用例传参需要用装饰器@pytest.mark.parametrize,里面写两个参数

    • 第一个参数类型是字符串,多个参数中间用逗号隔开,这里填写的就是参数化的字段
    • 第二个参数类型是list,多组数据用元祖类型,这里填写的就是参数化的数据,通常我们把数据都会存放在yaml或者json文件中

    装饰器@parametrize定义了三组不同的(test_input, expected)数据,test_eval则会使用这三组数据执行三次:

    test_1.py::test_eval[3+5-8] 
    test_1.py::test_eval[2+4-6] 
    test_1.py::test_eval[6*9-42] PASSED                                       [ 33%]PASSED                                       [ 66%]FAILED                                      [100%]
    test_1.py:10 (test_eval[6*9-42])
    54 != 42
    
    Expected :42
    Actual   :54
    <Click to see difference>
    
    test_input = '6*9', expected = 42
    
        @pytest.mark.parametrize("test_input, expected", [("3+5", 8), ("2+4", 6), ("6*9", 42),])
        def test_eval(test_input, expected):
    >       assert eval(test_input) == expected
    E       assert 54 == 42
    
    test_1.py:13: AssertionError
    

    参数组合(笛卡尔积)

    可以对一个函数使用多个parametrize的装饰器,这样多个装饰器的参数会组合进行调用:

    import pytest 
    
    @pytest.mark.parametrize("x", [0, 1]) 
    @pytest.mark.parametrize("y", [2, 3]) 
    def test_foo(x, y): 
      print("测试数据组合:x->%s, y->%s" % (x, y))
    

    测试结果

    collecting ... collected 4 items
    
    test_example.py::test_foo[2-0] PASSED                                    [ 25%]测试数据组合:x->0, y->2
    
    test_example.py::test_foo[2-1] PASSED                                    [ 50%]测试数据组合:x->1, y->2
    
    test_example.py::test_foo[3-0] PASSED                                    [ 75%]测试数据组合:x->0, y->3
    
    test_example.py::test_foo[3-1] PASSED                                    [100%]测试数据组合:x->1, y->3
    
  • 相关阅读:
    linux安装nginx
    python-- python threadpool 的前世今生
    如何用 Go 实现热重启
    使用expect快速登录线上机器
    curl 使用手册
    date命令时间戳和时间之间的转换
    linux设置程序运行超时时间
    你见过的最全面的python重点
    golang学习之旅:使用go语言操作mysql数据库
    Python多进程编程
  • 原文地址:https://www.cnblogs.com/jiakecong/p/14291960.html
Copyright © 2020-2023  润新知