测试框架pytest教程(7)实现 xunit 风格的setup

pytest支持setup和teardown,对于使用unittest和nose框架的用户来说对这些很熟悉,但是在pytest可以使用功能更强大的fixture来实现固定装置。

模块级别

如果单个模块中有多个测试函数和测试类,您可以选择实现以下固定方法,这些方法通常会为所有函数调用一次:

python 复制代码
def setup_module(module):
    """setup any state specific to the execution of the given module."""


def teardown_module(module):
    """teardown any state that was previously setup with a setup_module
    method.
    """
复制代码

类级别

在调用类的所有测试方法之前和之后,在类级别调用以下方法

python 复制代码
@classmethod
def setup_class(cls):
    """setup any state specific to the execution of the given class (which
    usually contains tests).
    """


@classmethod
def teardown_class(cls):
    """teardown any state that was previously setup with a call to
    setup_class.
    """

方法级别

在每个方法调用周围都会调用以下方法

python 复制代码
def setup_method(self, method):
    """setup any state tied to the execution of the given method in a
    class.  setup_method is invoked for every test method of a class.
    """


def teardown_method(self, method):
    """teardown any state that was previously setup with a setup_method
    call.
    """

直接在模块中定义

python 复制代码
def setup_function(function):
    """setup any state tied to the execution of the given function.
    Invoked for every test function in the module.
    """


def teardown_function(function):
    """teardown any state that was previously setup with a setup_function
    call.
    """
相关推荐
lifewange5 小时前
pytest 找不到文件?直接在 pytest.ini 配置根目录 + 路径(最简单方案)
开发语言·python·pytest
老神在在00116 小时前
保姆级教程:Pytest + Allure 接口自动化测试从 0 到 1 完整指南(含环境搭建、用例编写、报告生成、报错排坑全流程)
pycharm·pytest·测试
清水白石00816 小时前
从手写初始化到 pytest fixture:让 Python 测试既干净、可复用,又能驾驭异步并发
开发语言·python·pytest
测试员周周17 小时前
【AI测试数据及模型质量2】换一批测试数据,模型得分差20%——AI评测翻车的根子,90%在数据质量
人工智能·python·ui·单元测试·测试用例·集成测试·pytest
nbwenren9 天前
2026实测:Gemini 3.1 Pro 从需求文档到 pytest 测试用例一条龙教程
测试用例·pytest
我的xiaodoujiao9 天前
API 接口自动化测试详细图文教程学习系列16--项目实战演练3
python·学习·测试工具·pytest
我的xiaodoujiao9 天前
API 接口自动化测试详细图文教程学习系列15--项目实战演练2
python·学习·测试工具·pytest
技术钱10 天前
PyTest配置与API测试用例
servlet·测试用例·pytest
weixin_4196583112 天前
pytest 零基础入门实战指南
python·pycharm·pytest