微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐