【测试框架篇】单元测试框架pytest(5):setup和teardown的详细使用

一、前言

用过unittest的童鞋们应用都知道,有两个前置方法,两个后置方法如下:

  • setup()
  • setupClass()
  • teardown()
  • teardownClass()

Pytest也提供了类似于setup、teardown的方法,并且还超过四个,一共有十种分级别的方法:

  • **模块级别:**setup_module、teardown_module
  • **函数级别:**setup_function、teardown_function,不在类中的方法
  • **类级别:**setup_class、teardown_class
  • **方法级别:**setup_method、teardown_method
  • **方法细化级别:**setup、teardown

二、代码

用过unittest的童鞋,对这个前置、后置方法应该不陌生了,我们直接来看代码和运行结果

python 复制代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-


import pytest


def setup_module():
    print("=====整个.py模块开始前只执行一次:打开浏览器=====")


def teardown_module():
    print("=====整个.py模块结束后只执行一次:关闭浏览器=====")


def setup_function():
    print("===每个函数级别用例开始前都执行setup_function===")


def teardown_function():
    print("===每个函数级别用例结束后都执行teardown_function====")


def test_one():
    print("one")


def test_two():
    print("two")


class TestCase():
    def setup_class(self):
        print("====整个测试类开始前只执行一次setup_class====")

    def teardown_class(self):
        print("====整个测试类结束后只执行一次teardown_class====")

    def setup_method(self):
        print("==类里面每个用例执行前都会执行setup_method==")

    def teardown_method(self):
        print("==类里面每个用例结束后都会执行teardown_method==")

    def setup(self):
        print("=类里面每个用例执行前都会执行setup=")

    def teardown(self):
        print("=类里面每个用例结束后都会执行teardown=")

    def test_three(self):
        print("three")

    def test_four(self):
        print("four")


if __name__ == '__main__':
    pytest.main(["-q", "-s", "-ra", "setup_teardown.py"])

执行结果

注意,从执行结果我们可以看到:

  • **模块级别:**setup_module、teardown_module,只执行一次,在整个.py模块开始前和结束后都需要;
  • **函数级别:**setup_function、teardown_function,不在类中的方法,主要取决于有几个函数级别用例,有几个就执行几次,在每个函数级别用例开始前和结束后都需要;
  • **类级别:**setup_class、teardown_class,整个测试类开始前和结束后执行一次;
  • **方法级别:**setup_method、teardown_method,取决于类里面有多少测试用例,类里面每个测试用例开始前和结束后都需要执行一次;
  • **方法细化级别:**setup、teardown,跟前面方法级别使用类似,不过细化级别需要先执行;
相关推荐
花酒锄作田17 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪21 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
金銀銅鐵21 小时前
浅解 JUnit 4 第十一篇:@Before 注解和 @After 注解如何发挥作用?
junit·单元测试
曲幽21 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python