Skip to content

Pytest 测试框架结构


简介

Pytest 测试框架的结构是指如何组织和管理你的测试代码、测试数据、配置和其他支持文件,使得测试过程高效、清晰并且易于维护。


基本项目结构

Pytest 的测试框架基于 Python 的标准目录结构,但在此基础上增加了一些约定和最佳实践。

my_project/
│
├── src/
│   └── my_module.py
│
├── tests/
│   ├── test_my_module.py
│   └── test_another.py
├── conftest.py
├── pytest.ini
├── requirements.txt
└── README.md

测试装置

测试装置又可以称为测试夹具,用于为测试提供固定的测试环境或资源。它允许在测试执行之前准备所需的资源,在测试执行后清理这些资源。

在 pytest 中,既支持 unittest 中的 setup 和 teardown 用法,也提供了更灵活的 fixture。

先介绍一下基础的 setup 和 teardown 用法。


setup 与 teardown 作用

  • setup:setup 用于为测试提供准备环境的代码。该函数在测试用例运行之前执行。通常被用来初始化测试环境,例如创建数据库连接、加载测试数据等。可以定义不同的作用域(函数级别、类级别、模块级别)的 setup。
  • teardown:teardown 函数用于在测试执行后进行清理工作。该函数测试用例运行完成后执行。通常用于释放资源,例如关闭数据库连接、删除临时文件等。可以定义不同的作用域(函数级别、类级别、模块级别)的 teardown。

setup/teardown 函数的作用域

类型 规则
setup_module/
teardown_module
全局模块级
setup_class/
teardown_class
类级,只在类中前后运行一次
setup_function/
teardown_function
函数级,在类外
setup_method/
teardown_method
方法级,类中的每个方法执行前后

# 模块级别(优先最高)
def setup_module():
    print("资源准备:setup module")

def teardown_module():
    print("资源准备:teardown module")

# 函数级别
def setup_function():
    print("资源准备:setup function")

def teardown_function():
    print("资源销毁:teardown function")

def test_func1():
    assert True

class TestDemo:
    # 执行测试类前后分别执行 setup_class teardown_class
    def setup_class(self):
        print("TestDemo setup_class")

    def teardown_class(self):
        print("TestDemo teardown_class")

    # 每个类里面的测试方法前后分别执行 setup teardown
    def setup_method(self):
        print("TestDemo setup")

    def teardown_method(self):
        print("TestDemo teardown")

    def test_method1(self):
        assert True

    def test_method2(self):
        assert False

执行结果


./assets/pytest测试框架结构.mp4


总结

  • 了解 Pytest 测试框架结构。
  • 掌握测试装置用法。