品易云推流 关闭
文章详情页
文章 > Python基础教程 > 如何使用python做单元测试?

如何使用python做单元测试?

头像

2020-11-06 14:45:121951浏览 · 0收藏 · 0评论

很多编程小白不太理解单元测试,为什么要进行单元测试呢?很简单,主要是提高代码的正确,同时确保重构不出错。接下来我们一起学习怎么用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学习网教学中心

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图