lsekfe 发表于 2022-8-25 11:14:03

Pytest的热门知识点断言和报告!

使用assert语句进行断言
def f():
   return 3
def test_function():
   assert f() == 4
在Python中,我们可以使用标准的Pythonassert断言语句来验证测试中的期望结果和实际结果。大多数语言的断言也是这个单词。
  如果此断言失败,你将看到函数调用的返回值:

上面就是简单的断言。
  异常断言
  我们可以使用pytest.raises作为上下文管理器来进行异常断言,看如下代码:
import pytest

def test_zero_division():
    with pytest.raises(ZeroDivisionError):
      1 / 0
def test_recursion_depth():
    with pytest.raises(RuntimeError) as excinfo:
      def f():
            f()
      f(1)
    assert 'maximum recursion' in str(excinfo.value)如果需要访问实际的异常信息,咱们可以使用如上的第二个case。运行结果如下:

使用上下文对比
  上下文的对比,主要解决对大量用例进行了特定对比:
  长字符串断言:显示上下文差异
  长序列断言:显示第一个失败的索引
  字典断言:显示不同的key-value对
  看如下列子:
def test_set_comparison():
    set1 = set("1308")
    set2 = set("8035")
    assert set1 == set2运行结果:

看运行结果,我们很容易理解,我们对比结果的时候,不需要拿着每个字符去对比,这样也节省代码逻辑。
  自定义断言对比信息
  很多时候,我们不能只看系统给的错误信息,有时想想自己定义断言信息,这个时候,我们可以用到Pytest中的钩子方法。
  因为我也是第一次学习,所以,我们按照文档,先写成如下:
from test_8 import Foo
def pytest_assertrepr_compare(op,left,right):
    if isinstance(left,Foo) and isinstance(right,Foo) and op == "==":
      return ['Foo实例对比:',
                '   值: %s != %s' % (left.val,right.val)]如上代码,文件名命名一定要是’conftest.py‘,其他的命名不好使,切记。
class Foo(object):
    def __init__(self,val):
      self.val = val

    def __eq__(self,other):
      return self.val == other.val

def test_compare():
    f1 = Foo(1)
    f2 = Foo(2)
    assert f1 == f2
然后运行如上case,结果如下:

大家发现没有,这个地方运行case,Pytest后面带的参数也不一样,对,就是’-q‘。




页: [1]
查看完整版本: Pytest的热门知识点断言和报告!