使用 pytest 进行 python 脚本测试

Pytest TIPS

使用 python 进行 python 脚本测试时的一些小 tips 记录

[tips.1] pytest 会执行指定目录下所有 Test 开头的类和函数

默认为运行目录,可以通过 --rootdir 参数指定

[tips.2] 可以通过 assert 断言判断是否满足预期, 断言不满足抛出异常,不会执行当前函数内的剩余代码

import math

def test_sqrt():
   num = 25
   assert math.sqrt(num) == 5

def testsquare():
   num = 7
   assert 7*7 == 40

def tesequality():
   assert 10 == 11

[tips.3] 对于预期错误的断言, 通过 pytest.raise 处理

import pytest

def test_raise_error():
    with pytest.raises(ZeroDivisionError) as e:
        # some code which expect to raise an exception, for example
        a = 8/0
posted @ 2022-11-25 14:15  coreylin  阅读(165)  评论(0编辑  收藏  举报