Python 中如何实现参数化测试?( 二 )


同样提醒下,原来的测试方法已经消失了,取而代之的是三个新的测试方法,只是新方法的命名规则与 ddt 的例子不同罢了 。
介绍完 unittest,接着看已经死翘翘了的nose以及新生的nose2 。nose 系框架是带了插件(plugins)的 unittest,以上的用法是相通的 。
另外,nose2 中还提供了自带的参数化实现:
import unittestfrom nose2.tools import params@params(1, 2, 3)def test_nums(num):assert num < 4class Test(unittest.TestCase):@params((1, 2), (2, 3), (4, 5))def test_less_than(self, a, b):assert a < b最后,再来看下 pytest 框架,它这样实现参数化测试:
import pytest@pytest.mark.parametrize("first,second", [(3,1), (-1,0), (1.5,1.0)])def test_values(first, second):assert(first > second)测试结果如下:
==================== test session starts ====================platform win32 -- Python 3.6.1, pytest-5.3.1, py-1.8.0, pluggy-0.13.1rootdir: C:UserspythoncatPycharmProjectsstudy collected 3 itemstestparam.py .Ftestparam.py:3 (test_values[-1-0])first = -1, second = 0@pytest.mark.parametrize("first,second", [(3,1), (-1,0), (1.5,1.0)])def test_values(first, second):> assert(first > second)E assert -1 > 0testparam.py:6: AssertionError. [100%]========================= FAILURES ==========================_________________________ test_values[-1-0] _________________________first = -1, second = 0@pytest.mark.parametrize("first,second", [(3,1), (-1,0), (1.5,1.0)])def test_values(first, second):> assert(first > second)E assert -1 > 0testparam.py:6: AssertionError===================== 1 failed, 2 passed in 0.08s =====================Process finished with exit code 0依然要提醒大伙注意,pytest 也做到了由一变三,然而我们却看不到有新命名的方法的信息 。这是否意味着它并没有产生新的测试方法呢?或者仅仅是把新方法的信息隐藏起来了?
 
4、最后小结上文中介绍了参数化测试的概念、实现思路,以及在三个主流的 Python 测试框架中的使用方法 。我只用了最简单的例子,为的是快速科普(言多必失) 。
但是,这个话题其实还没有结束 。对于我们提到的几个能实现参数化的库,抛去写法上大同小异的区别,它们在具体代码层面上,又会有什么样的差异呢?
具体来说,它们是如何做到把一个方法变成多个方法,并且将每个方法与相应的参数绑定起来的呢?在实现中,需要解决哪些棘手的问题?
在分析一些源码的时候,我发现这个话题还挺有意思,所以准备另外写一篇文章 。那么,本文就到此为止了,谢谢阅读 。
 来源:Python猫
作者:豌豆花下猫




推荐阅读