Pytest知识整合小记(二、pytest用例的前置与后置、断言)

一、用例运行级别

1.模块级(setup_module/teardown_module)开始于模块始末,全局的

  1. 函数级(setup_function/teardown_function)只对函数用例生效(不在类中)

  2. 类级(setup_class/teardown_class)只在类中前后运行一次(在类中)

4.方法级(setup_method/teardown_method)开始于方法始末(在类中)

5.类里面的(setup/teardown)运行在调用方法的前后

优先级:setup_module 》setup_class》setup_method》setup 》用例》teardown》teardown_method》teardown_class》teardown_module

二、异常

1.assert

与Unittest 不同,pytest简化了异常接收,统一只用assert,如:

assert a==b

assert a

assert关键字后面可以添加任何表达式,表达式的值通过bool转换等于False则意味着失败。

2.预期异常

with pytest.raises():

测试通过,证明如期发生了我们预期的异常,如果是抛出其他类型的异常,则与我们所预期的不一致,测试失败。

三、标记用例

1.@pytest.mark.xxxx

标记一类的测试用例作为统一名称,运行的时候可以运行统一标记的用例

2.@pytest.mark.skip(reason="have some problem here")

跳过对应用例

3.@pytest.mark.skipif(runflag=0,reason="have some problem here")

根据条件情况跳过对应用例

4.@pytest.mark.xfail(runflag=0,reason="have some problem here")

预期失败的用例,不会跳过,会被执行,但不影响后续测试,且有预期标记XPASS

posted @ 2025-05-14 15:21  寻虫测试  阅读(30)  评论(0)    收藏  举报