• Novice学Pytest(2)assert断言


    一、前言

      什么是断言,为什么要断言,要如何断言。。。刚入门时,可能很多小伙伴会有各种疑问(大神请绕过~)。顾名思义,断言是判断一个用例的执行结果,断言通过,用例执行成功,否则用例执行失败。工作中写自动化脚本时,少不了断言,我们工作项目用的是pytest。pytest使用的是python自带的assert关键字来进行断言,assert关键字后面可以接一个表达式,只要表达式的最终结果为True,so断言通过。

    二、简单举例

      想在抛出异常之后输出一些提示信息,执行之后就方便查看是什么原因了

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    """
    __Title__   =
    __Time__    =  2021/8/7 16:02
    __Author__  =  Isaymore
    __Blog__    =  https://www.cnblogs.com/huainanhai/
    """
    
    def f():
        return 3
    
    def test_function():
        a = f()
        assert a % 2 == 0,"判断a为偶数,当前a的值为:%s" % a

      执行结果:

    三、常用断言

      pytest断言实际用的是python的assert断言方法,常用的有以下几种 

    • assert xx :判断 xx 为真
    • assert not xx :判断 xx 不为真
    • assert a in b :判断 b 包含 a
    • assert a == b :判断 a 等于 b
    • assert a != b :判断 a 不等于 b
    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    
    """
    __Title__   =
    __Time__    =  2021/8/7 16:02
    __Author__  =  Isaymore
    __Blog__    =  https://www.cnblogs.com/huainanhai/
    """
    
    def f(x):
        return x
    def test_bool():
        assert f(0)
    
    def test_str():
        assert "s" in f("Isaymore")
    
    def test_equl():
        assert f(2) == 2

      执行结果:

    四、异常断言

      可以使用pytest.raises作为上下文管理器,当抛出异常时可以获取到对应的异常实例

    # 断言异常
    def test_zerodivision():
        with pytest.raises(ZeroDivisionError) as excinfo:
            1 / 0
        # 断言异常类型 type
        assert excinfo.type == ZeroDivisionError
        # 断言异常值 value
        assert "division by zero" in str(excinfo.value)

      断言异常场景:断言抛出的异常是不是符合预期

      预期:抛出异常是ZeroDivisionError: division by zero

      如何断言:通常是断言异常的type和value

      断言例子:1/0的异常类型是ZeroDivisionError,异常的value值是division by zero

      excinfo:是一个异常信息实例

      主要属性:.type、.value、.traceback

      Notes:断言type时,异常类型不需要加引号,断言value值需转str

    五、异常断言拓展

      1、match:可以将match关键字参数传递给上下文管理器,以测试正则表达式与异常的字符串表示形式是否匹配

    def test_zero_division_long():
        with pytest.raises(ZeroDivisionError,match=".*zero.*") as excinfo:
            1 / 0
    
    def test_zero_division_long2():
        with pytest.raises(ZeroDivisionError,match="zero") as excinfo:
            1 / 0

      执行结果:

      2、断言装饰器

    # 断言装饰器
    @pytest.mark.xfail(raises=ZeroDivisionError)
    def test_f():
        1 / 0

      执行结果:

    六、总结  

    • 代码抛出异常,但如果和raises指定的异常类相匹配,就不会断言失败
    • with pytest.raise(ZeroDivisionError) 对于故意测试异常代码的情况,使用可能会更好
    • 而@pytest.mark.xfail(raises=ZeroDivisionError) 对于检查未修复的错误(即,可能会发生异常),使用检查断言可能会更好

    参考链接:https://www.cnblogs.com/poloyy/p/12641778.html

  • 相关阅读:
    (四)STL中的算法
    (三)openssl库实现对称和非对称加密
    (十一)etcd项目
    (十二)插件之dlopen/dlsym/dlclose 加载动态链接库
    (十一)访问权限关键字publi/private/protected
    RESTful架构
    (零)TCP/IP详解综述
    (二)辗转相除法求最大公约数
    (一)简单的TcpServer
    SpringMVC异常处理
  • 原文地址:https://www.cnblogs.com/huainanhai/p/15112772.html
Copyright © 2020-2023  润新知