欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python单元测试

程序员文章站 2022-03-11 16:17:07
...

python中的单元测试,主要有3种方式:

1.unittest

2.nose(nose2)

3.pytest

关于unittest的使用,非常简单,继承TeseCase:

https://docs.python.org/2/library/unittest.html#unittest.TestCase.setUp

setUp()

Method called to prepare the test fixture. This is called immediately before calling the test method; other than AssertionError or SkipTest, any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.

tearDown()

Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. Any exception, other thanAssertionError or SkipTest, raised by this method will be considered an additional error rather than a test failure (thus increasing the total number of reported errors). This method will only be called if the setUp() succeeds, regardless of the outcome of the test method. The default implementation does nothing.

setUpClass()

A class method called before tests in an individual class are run. setUpClass is called with the class as the only argument and must be decorated as a classmethod():

@classmethod
def setUpClass(cls):
    ...

See Class and Module Fixtures for more details.

New in version 2.7.

tearDownClass()

A class method called after tests in an individual class have run. tearDownClass is called with the class as the only argument and must be decorated as a classmethod():

@classmethod
def tearDownClass(cls):
    ...

The TestCase class provides several assert methods to check for and report failures. The following table lists the most commonly used methods (see the tables below for more assert methods):

Method Checks that New in
assertEqual(a, b) a == b  
assertNotEqual(a, b) a != b  
assertTrue(x) bool(x) is True  
assertFalse(x) bool(x) is False  
assertIs(a, b) a is b 2.7
assertIsNot(a, b) a is not b 2.7
assertIsNone(x) x is None 2.7
assertIsNotNone(x) x is not None 2.7
assertIn(a, b) a in b 2.7
assertNotIn(a, b) a not in b 2.7
assertIsInstance(a, b) isinstance(a, b) 2.7
assertNotIsInstance(a, b) not isinstance(a, b) 2.7

有些数据需要mock的情况下,unittest.mock库提供解决办法。

如果要获取详情,则可以这样:

you can run tests with more detailed information by passing in the verbosity argument:

if __name__ == '__main__':
    unittest.main(verbosity=2)

nose  pip install nose 或者 pip  install nose2安装,它会自动寻找unittest.TestCase的派生类。

python经典的单元测试框架:pytest

https://docs.pytest.org/en/latest/

后期重点使用pytest来进行单元测试,内容很多,也不在赘述,直接看官方文档。

 

 

 

相关标签: pytest