很多程序员不是很了解单元测试,为什么要进行单元测试呢?很简单,主要是提高代码的正确性,同时保证重构不出错。接下来,让我们学习如何使用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学习推荐:
。
本文为原创文章,版权归知行编程网所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ python参数调用注意事项12/28
- ♥ 如何在python数据挖掘中使用pandas包?11/29
- ♥ 如何在python中四舍五入08/18
- ♥ python插入排序是一种算法吗?如何使用?01/04
- ♥ 如何使用python脚本实现表单打印?01/06
- ♥ python中用来表示注释的东西08/12
内容反馈