其他分享
首页 > 其他分享> > pytest学习笔记

pytest学习笔记

作者:互联网

测试数据驱动

Here is an example pytest_generate_tests function implementing a parametrization scheme similar to Michael Foord’s unittest parametrizer but in a lot less code:,unittest也有这样的设计:https://github.com/testing-cabal/unittest-ext/blob/master/params.py

# content of ./test_parametrize.py
import pytest

def pytest_generate_tests(metafunc):
    # called once per each test function
    funcarglist = metafunc.cls.params[metafunc.function.__name__]
    argnames = sorted(funcarglist[0])
    metafunc.parametrize(argnames, [[funcargs[name] for name in argnames]
            for funcargs in funcarglist])

class TestClass(object):
    # a map specifying multiple argument sets for a test method
    params = {
        'test_equals': [dict(a=1, b=2), dict(a=3, b=3), ],
        'test_zerodivision': [dict(a=1, b=0), ],
    }

    def test_equals(self, a, b):
        assert a == b

    def test_zerodivision(self, a, b):
        with pytest.raises(ZeroDivisionError):
            a / b

Our test generator looks up a class-level definition which specifies which argument sets to use for each test function. Let’s run it:

$ pytest -q
F..                                                                  [100%]
================================= FAILURES =================================
________________________ TestClass.test_equals[1-2] ________________________

self = <test_parametrize.TestClass object at 0xdeadbeef>, a = 1, b = 2

    def test_equals(self, a, b):
>       assert a == b
E       assert 1 == 2
E         -1
E         +2

test_parametrize.py:18: AssertionError
1 failed, 2 passed in 0.12 seconds

这不就是数据驱动嘛,脚本只要写一条,有多条数据就有多条用例

标签:function,metafunc,equals,笔记,学习,pytest,test,def
来源: https://blog.csdn.net/u012897401/article/details/86598614