在python中单元测试是什么

524次阅读
没有评论

在python中,单元测试是用来对一个模块、一个函数或者一个类来进行正确性检验的测试工作。

在python中单元测试是什么

单元测试

通常是测试一小块代码的功能,比如一个函数,类的一个方法。

单元测试通常是开发人员做的一种测试,通常是测试函数,方法这种级别的代码块的。单元测试大都是 设计出不同的调用参数来调用函数,来看 函数 的输出是否符合预期。当然如果你的代码写的不好的话,单元测试也会比较麻烦。比如一个功能模块没有内聚到函数中,而是分散在代码文件里面。那样,就不容易用一个函数调用对这些功能进行测试。

使用pytest进行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
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-07-16发表,共计1334字。
新手QQ群:570568346,欢迎进群讨论 Python51学习