怎么使用python做单元测试-创新互联
这篇文章主要介绍怎么使用python做单元测试,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

python内置了一个unittest,但是写起来稍微繁琐,比如都要写一个TestCase类,还得用 assertEqual, assertNotEqual等断言方法。 而使用pytest运行测试统一用assert语句就行,兼容unittest,目前很多知名开源项目如PyPy,Sentry也都在用。关于pytest的使用可以参考其官方文档,虽然有很多高级特性,但是掌握其中一小部分基本就够用了。
下面是py.test的基本用法,以常见的两种测试类型(验证返回值和抛出异常)为例:
def add(a, b):
"""return a + b
Args:
a (int): int
b (int): int
Returns:
a + b
Raises:
AssertionError: if a or b is not integer
"""
assert all([isinstance(a, int), isinstance(b, int)])
return a + b
def test_add():
assert add(1, 2) == 3
assert isinstance(add(1, 2) , int)
with pytest.raises(Exception): # test exception
add('1', 2)基本使用就是这么简单。真实场景下远远比这个复杂,甚至有时候构造测试的时间比写业务逻辑的时间还要长。但是再复杂的逻辑也是一点点功能堆积,如果可以确保每一部分都正确,整体上是不会出错的。单元测试同时也提醒我们,函数完成的功能尽可能单一,这样才利于测试。
下面几个是我常用的pytest命令:
py.test test_mod.py # run tests in module py.test somepath # run all tests below somepath py.test -q test_file_name.py # quite输出 py.test -s test_file_name.py # -s参数可以打印测试代码中的输出,默认不打印,print没结果 py.test test_mod.py::test_func # only run tests that match the "node ID", py.test test_mod.py::TestClass::test_method # run a single method in
以上是怎么使用python做单元测试的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!
网站名称:怎么使用python做单元测试-创新互联
标题URL:http://www.jxjierui.cn/article/dpgisj.html


咨询
建站咨询
