用pytest给计算器的除法做异常处理之后,断言不起作用了

问题描述:

  • 环境:Pycharm, pytest
  • 问题复述:用了 try, except捕捉异常,然后assert断言就不起作用了,明明算出来的结果和期望结果不一样,但是case也Pass了,所以,想问问老师和同学们,通常我们测试工作中是怎么同时使用断言和异常处理的呢?

相关代码

test_calc.py 相关代码:

# data为一个字典,用key值"div"取出对应的测试数据,给 a, b 和 expect进行参数化
    @pytest.mark.parametrize('a, b, expect', get_data()["div"])
    # 定义一个方法用于测试 Calc里面的div方法,参数中的initialization会调用fixture,返回Calc的实例
    def test_div(self, a, b, expect, initialization):
        # 捕捉异常
        try:
            # 用Calc的实例调用div方法,将结果赋值给result
            result = initialization.div(a,b)
            # 用 assert 断言,比对 result和expect的值是否相等
            assert result == Decimal(str(expect))
            print("result is {}, expect is {}".format(result, expect))
        # 将捕捉到的异常打印出来
        except(ZeroDivisionError,TypeError,Exception) as e:
            print(e)

calc.py 相关代码:

# 定义类方法div,传入参数a和b, 方法的返回值是 a/b
    def div(self, a, b):
        return Decimal(str(a)) / Decimal(str(b))

data.yml相关代码:

div:
  - [8, 4, 1]  # 相同的整数相除
  - [2, 1, 2]  # 整数除以1
  - [0, 8, 0]  # 被除数是0
  - [1.5, 1.5, 1]  # 相同的浮点数相除
  - [2.8, 1, 2.8]  # 浮点数除以1
  - [3, 6, 0.5]  # 整数相除是浮点数
  - [6.6, 2.2, 3]  # 整数相除是浮点数
  - [2, 0, division by zero]  # 除数为0
  - [a, 1, incorrect type]  # 有字母

报错信息:

原因以及解决方式(没有可以写无):

pytest有专门的方法来断言异常https://docs.pytest.org/en/latest/reference.html#pytest-raises
或者你except的时候不要把所有异常都加上了,只加你预期的异常然后在except里再做断言处理也行

谢谢您,根据您说的,我改造了一下,这样是不是好一些了?

# data为一个字典,用key值"div"取出对应的测试数据,给 a, b 和 expect进行参数化
    @pytest.mark.parametrize('a, b, expect', get_data()["div"])
    # 定义一个方法用于测试 Calc里面的div方法,参数中的initialization会调用fixture,返回Calc的实例
    def test_div(self, a, b, expect, initialization):
        # 捕捉异常, 除数是0
        if b == 0:
            raise ZeroDivisionError
        # 捕捉异常, 被除数和除数如果不是int和float类型
        elif not (isinstance(a,int) or isinstance(a,float)) or not (isinstance(b,int) or isinstance(b,float)):
            raise TypeError
        else:
            print(f"type=={type(a)}")
            result = initialization.div(a, b)
            # 用 assert 断言,比对 result和expect的值是否相等
            assert result == Decimal(str(expect))
            print("result is {}, expect is {}".format(result, expect))

这部分你直接在测试用例里做了被测程序该做的事情,这样就没办法真实反应被测程序的情况了,另外你pytest.raise用的不对,我给你个简单的demo吧

谢谢老师,我这么改了一下,您受累给看一下哈:

data.yml相关代码:

div:
  - [8, 4, 1]  # 相同的整数相除, 会fail
  - [2, 1, 2]  # 整数除以1
  - [0, 8, 0]  # 被除数是0
  - [1.5, 1.5, 1]  # 相同的浮点数相除
  - [2.8, 1, 2.8]  # 浮点数除以1
  - [3, 6, 0.5]  # 整数相除是浮点数
  - [6.6, 2.2, 3]  # 整数相除是浮点数
  - [2, 0, ZeroDivisionError]  # 除数为0
  - [a, 1, Exception]  # 有字母
  - [2, b, Exception]  # 有字母
  - [含, 1, Exception]  # 有汉字

test_calc.py 相关代码:

# data为一个字典,用key值"div"取出对应的测试数据,给 a, b 和 expect进行参数化
    @pytest.mark.parametrize('a, b, expect', get_data()["div"])
    # 定义一个方法用于测试 Calc里面的div方法,参数中的initialization会调用fixture,返回Calc的实例
    def test_div(self, a, b, expect, initialization):
        # 捕捉异常, 除数是0
        if expect == "ZeroDivisionError":
            with raises(eval(expect)):
                initialization.div(a, b)
        elif expect == "Exception":
            with raises(eval(expect)):
                initialization.div(a, b)
        else:
            result = initialization.div(a, b)
            # 用 assert 断言,比对 result和expect的值是否相等
            assert result == Decimal(str(expect))
            print("result is {}, expect is {}".format(result, expect))

执行结果:

用法基本上就是这样了

好的,谢谢老师~