【Python】单元测试框架 - pytest

Posted by 西维蜀黍 on 2019-11-18, Last Modified on 2024-05-07

一个实例

# content of test_sample.py
 
def func(x):
    return x+1
 
def test_func():
    assert func(3) == 5

再一个实例

当需要编写多个测试样例的时候,我们可以将其放到一个测试类当中,如:

# content of test_class.py

class TestClass:
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

我们可以通过执行测试文件的方法,执行上面的测试:

$ py.test -q test_class.py
.F                                                                                                                                                  [100%]
======================================================================== FAILURES =========================================================================
___________________________________________________________________ TestClass.test_two ____________________________________________________________________

self = <testAA.TestClass instance at 0x10dd68d40>

    def test_two(self):
        x = "hello"
>       assert hasattr(x, 'check')
E       AssertionError: assert False
E        +  where False = hasattr('hello', 'check')

testAA.py:8: AssertionError
1 failed, 1 passed in 0.05 seconds