超详细的pytest教程(二)之前后置方法和fixture机制

前言

上一篇文章入门篇咱们介绍了pytest的基本使用,这一篇文章专门给大家讲解pytest中关于用例执行的前后置步骤处理,pytest中用例执行的前后置处理既可以通过测试夹具(fixtrue)来实现,也可以通过xunit 风格的前后置方法来实现。接下来我们一起看看如何具体使用。

一、xunit风格的前后置方法

1、函数用例的前后置方法

在模块中以函数形式定义用例,可以通过setup_function和teardown_function来定义函数用例的前后置方法,使用案例如下:

def setup_function(function):
    print("函数用例前置方法执行")

  
def teardown_function(function):
    print("函数用例后置方法执行")


def test_01():
    print('----用例方法01------')

运行结果:

C:\testcases>pytest -s
========================= test session starts =========================
platform win32 -- Python 3.7.3, pytest-5.4.2, py-1.8.0, pluggy-0.13.0 
cachedir: .pytest_cache
rootdir: C:\testcases
plugins:  testreport-1.1.2
collected 1 item                                                      
test_demo.py
函数用例前置方法执行
----用例方法01------ .
函数用例后置方法执行
========================= 1 passed in 0.27s =========================

2、测试类中用例的前后置方法

  • 类级别的前后置方法
  • pytest中测试类级别的前后置方法setup_class和teardown_class,分别在测试类中的用例执行之前执行,和测试类中所有用例执行完毕之后执行,具体使用如下:
  • class TestDome: def test_01(self): print('----测试用例:test_01------') def test_02(self): print('----测试用例:test_02------') @classmethod def setup_class(cls): print("测试类前置方法---setup_class---") @classmethod def teardown_class(cls): print("测试类后置方法---teardown_class---")
  • 用例级别的前后置方法
  • pytest中测试类中用例级别的的前后置方法setup_method和teardown_method,分别在测试类中的用例执行之前执行,和测试类中所有用例执行完毕之后执行,具体使用如下:
  • class TestDome: def test_01(self): print('----测试用例:test_01------') def test_02(self): print('----测试用例:test_02------') @classmethod def setup_class(cls): print("测试类前置方法---setup_class---") @classmethod def teardown_class(cls): print("测试类后置方法---teardown_class---") def setup_method(function): print("测试用例前置方法---setup_method---") def teardown_method(function): print("测试用例后置方法---teardown_method---")

运行结果:

C:\testcases>pytest -s
==================== test session starts ====================
platform win32 -- Python 3.7.3, pytest-5.4.2, py-1.8.0, pluggy-0.13.0
rootdir: C:\testcases
plugins:
<think>嗯,用户现在想了解pytest中的前置条件后置条件的使用方法,特别是setupteardown方法或者fixtures的用法。我之前已经回答过类似的问题,但可能需要更详细的结构化说明。首先,我应该回顾pytest中的传统setup/teardown方法更现代的fixture系统。 用户可能已经知道unittest中的setupteardown,但pytest提供了更灵活的方式。需要比较两种方法,并说明为什么fixtures更好。例如,fixtures的作用域、依赖注入、参数化等优势。 接下来,我需要分步骤解释传统方法fixture的用法。传统方法包括模块级、类级、方法级的setupteardown,这部分需要给出代码示例,比如使用setup_module、setup_class等,并说明它们的执行顺序范围。 然后,重点转向fixtures。用户可能需要知道如何定义fixture,使用@pytest.fixture装饰器,以及如何在测试函数中调用它们。还要解释fixture的作用域(function、class、module、session),以及如何通过scope参数来设置。例如,一个数据库连接的fixture可能在整个会话中只创建一次,这样可以提高测试效率。 另外,fixture的自动使用(autouse=True)也是一个有用的特性,不需要显式声明即可自动运行。这部分需要举例说明,比如自动初始化资源的情况。 后置处理部分,fixture可以通过yield或者addfinalizer来定义teardown代码。需要对比两种方法,说明yield更简洁,而addfinalizer适合多个清理步骤的情况。 参数化fixture也是一个重要点,用户可能需要动态生成测试数据。比如,使用params参数传递不同数据,测试函数会根据参数个数多次执行。 还有,fixture之间的依赖关系,比如一个fixture可以依赖另一个fixture,这能帮助构建复杂的测试环境。例如,数据库连接fixture可能依赖配置文件的fixture。 最后,比较传统方法fixture的优缺点,强调fixture的灵活性可维护性,特别是在大型项目中。同时,提醒用户注意执行顺序作用域,避免资源泄漏。 用户可能的问题会涉及如何组织fixture,处理测试依赖,或者解决作用域冲突。需要确保回答清晰,结构分明,代码示例正确,并且符合LaTeX格式要求。同时,根据用户提供的引用,虽然内容是关于Flask的测试上下文,但可以忽略,专注于pytest本身的特性。</think>### pytest前置条件与后置条件使用详解 在pytest中,前置条件后置条件主要通过两种方式实现: 1. **传统xUnit风格**(类级别的setup/teardown) 2. **fixture系统**(推荐方式) #### 一、xUnit风格实现(兼容unittest) ```python # 模块级(整个.py文件) def setup_module(module): print("模块初始化") def teardown_module(module): print("模块清理") # 类级 class TestClass: @classmethod def setup_class(cls): print("类初始化") @classmethod def teardown_class(cls): print("类清理") # 方法级 def setup_method(self, method): print("方法初始化") def teardown_method(self, method): print("方法清理") def test_example(self): assert True ``` 执行顺序为: $$模块初始化 \rightarrow 类初始化 \rightarrow 方法初始化 \rightarrow 测试方法 \rightarrow 方法清理 \rightarrow 类清理 \rightarrow 模块清理$$ #### Fixture系统(现代方式) fixture通过`@pytest.fixture`装饰器定义,支持更精细的控制: 1. **基础使用** ```python import pytest @pytest.fixture def database_connection(): conn = create_connection() # 前置操作 yield conn # 返回对象 conn.close() # 后置操作 def test_query(database_connection): result = database_connection.execute("SELECT 1") assert result == 1 ``` 2. **作用域控制** ```python @pytest.fixture(scope="session") # 可选作用域:function/class/module/session def redis_client(): client = Redis() yield client client.flushall() ``` 3. **自动执行** ```python @pytest.fixture(autouse=True) def clear_cache(): Cache.clear() yield Cache.reset() ``` 4. **参数化fixture** ```python @pytest.fixture(params=["mysql", "postgresql"]) def db_type(request): return request.param def test_db(db_type): assert connect(db_type).status == "OK" ``` #### 三、最佳实践对比 | 特性 | xUnit风格 | Fixture系统 | |-----------|--------------------|---------------------| | 作用域控制 | 固定级别 | 自由定义(支持4种作用域) | | 代码复用 | 类内共享 | 跨模块共享 | | 依赖管理 | 无 | 显式声明依赖关系 | | 后置处理 | 必须成对实现 | 支持yieldaddfinalizer | | 执行顺序控制 | 固定层级顺序 | 通过fixture依赖关系控制 | | 参数化支持 | 仅配合参数化装饰器使用 | 内置参数化机制 | | 推荐使用场景 | 简单测试类 | 中大型项目/复杂依赖场景 | #### 四、高级技巧 1. **组合fixture** ```python @pytest.fixture def user_session(db_connection): with db_connection.start_session() as s: yield UserSession(s) ``` 2. **使用finalizer** ```python @pytest.fixture def temp_dir(request): path = create_temp_dir() def cleanup(): shutil.rmtree(path) request.addfinalizer(cleanup) return path ``` 3. **插件集成** ```pytest.ini [pytest] usefixtures = redis_client # 全局自动使用fixture ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

喜欢软测的小北葵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值