知行编程网知行编程网  2022-11-21 08:30 知行编程网 隐藏边栏  0 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于Python和单元测试那些事儿的相关知识,希望可以帮到处于编程学习途中的小伙伴

Python 和单元测试

我们来说说目前几个和测试有关的东西(全程 Python 3)。


Mock

模拟是个好东西。在测试中遇到不可预测或不稳定因素时,请改用 Mock。比如查询数据库(当然像我们现在使用的MongoDB,因为它非常灵活,可以直接在代码中替换对应的集合),比如异步任务等,例如:

import logging
from unittest.mock import Mock
logging.basicConfig(level=logging.DEBUG)
#  code
class ASpecificException(Exception):
    pass
def foo():
    pass
def bar():
    try:
        logging.info("enter function <foo> now")
        foo()
    except ASpecificException:
        logging.exception("we caught a specific exception")
#  unittest
def test_foo():
    foo = Mock(side_effect=ASpecificException())  # noqa
    logging.info("enter function <bar> now")
    bar()
    logging.info("everything just be fine")
if __name__ == "__main__":
    test_foo()

运行一下

root@arch tests: python test_demo.py
INFO:root:enter function <bar> now
INFO:root:enter function <foo> now
INFO:root:everything just be fine

一个简单的测试就是这样写的。来,跟我一起读,模拟大法好!


doctest

doctest 是一个比较简单的测试,用 docstring 编写,所以它可以用于测试和文档示例,非常有用。缺点是如果测试过于复杂(例如,如果在测试之前导入了一堆东西),doctest 可能会过于臃肿。例如:

import logging
logging.basicConfig(level=logging.DEBUG)
def foo():
    """A utility function that returns True
    >>> foo()
    True
    """
    return True
if __name__ == "__main__":
    import doctest
    logging.debug("start of test...")
    doctest.testmod()
    logging.debug("end of test...")

测试结果

root@arch tests: python test_demo.py
DEBUG:root:start of test...
DEBUG:root:end of test...


unittest

这个文档确实有点长,我觉得还是仔细阅读文档比较好。

import unittest
class TestStringMethods(unittest.TestCase):
    def setUp(self):
        self.alist = []
    def tearDown(self):
        print(self.alist)
    def test_list(self):
        for i in range(5):
            self.alist.append(i)
if __name__ == '__main__':
    unittest.main()

输出结果

root@arch tests: python test_demo.py
[0, 1, 2, 3, 4]
.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

unittest框架配合上Mock,单元测试基本无忧啦。


pytest

上面的单元测试运行起来比较麻烦,当然你也可以写一个脚本遍历所有的单元测试文件并执行。但是,pytest 对 unittest 有更好的支持。

pytest 默认支持函数式测试,但我们可以不这样做(在很多情况下它仍然非常有用)。进入项目根目录,输入pytest。它会自动发现以test_开头的文件,并在unittest中执行以test_开头的函数和以test_开头的方法。

root@arch tests: pytest
============================================= test session starts ==============================================
platform linux -- Python 3.5.2, pytest-3.0.5, py-1.4.31, pluggy-0.4.0
rootdir: /root/tests, inifile:
collected 1 items
test_afunc.py .
====================================1 passed in 0.03 seconds =======================================================
root@arch tests:


总结

编译器没给python做检查,就只有靠我们手写测试了 :(

另外,pytest和unittest还有很多强大的功能,比如fixture,比如跳过某个部分的测试。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享