• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

如何使用python做单元测试?

python 搞java代码 3年前 (2022-05-21) 20次浏览 已收录 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)

www#gaodaima.com来源gao!%daima.com搞$代*!码$网搞代码

基本使用就是这么简单。真实场景下远远比这个复杂,甚至有时候构造测试的时间比写业务逻辑的时间还要长。但是再复杂的逻辑也是一点点功能堆积,如果可以确保每一部分都正确,整体上是不会出错的。单元测试同时也提醒我们,函数完成的功能尽可能单一,这样才利于测试。

 

下面几个是我常用的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教程网

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何使用python做单元测试?
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址