python单元测试
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来进行单元测试,内容很多,也不在赘述,直接看官方文档。
推荐阅读
-
基于python发送邮件的乱码问题的解决办法_PHP教程
-
Ubuntu 12.04下源代码安装MySQL5.6以及Python-MySQLdb
-
PHP、Python 相关正则函数一点实例
-
为什么Python 比 PHP 更有效率?(不考虑人的主观因素,如编程风格和架构设计等)
-
总结python中的线程与协程
-
十大妙招可大大节省Python开发者的时间_PHP教程
-
PyQt5每天必学之滑块控件QSlider_python
-
Java的ProcessBuilder有没办法运行一个zip包里的php脚本或者python脚本?
-
Python 修饰器与 functools_html/css_WEB-ITnose
-
Python字符串处理实例详解