6.pytest_fixture之yield实现teardown

本文详细探讨了pytest_fixture中的`yield`关键字如何实现teardown功能。通过`scope="module"`控制作用域,`yield`后的代码作为teardown在所有用例执行完毕后运行。即使在用例中遇到异常,`yield`后的代码仍然会被执行。此外,还介绍了`addfinalizer`方法,用于注册终结函数,确保测试资源的正确关闭,即使在fixture创建或获取时发生错误。

上一篇讲到fixture通过scope参数控制setup级别,既然有setup作为用例之前前的操作,用例执行完之后那肯定也有teardown操作。
这里用到fixtureteardown操作并不是独立的函数,用yield关键字呼唤teardown操作;

scope=“module”

1.fixture参数scope="module"module作用是整个.py文件都会生效,用例调用时,参数写上函数名称就行;

import pytest

@pytest.fixture(scope="module")
def login():
    print("=================开始登陆login====================")
def test_01(login):
    print("====================test_01================")
def test_02():
    print("====================test_02================")

def test_03(login):
    print("====================test_03================")


if __name__ == "__main__":
    pytest.main(["-s","test_fix3.py"])

运行结果:

test_fix3.py::test_01 =================开始登陆login====================
PASSED                                             [ 33%]====================test_01================

test_fix3.py::test_02 PASSED                                             [ 66%]====================test_02================

test_fix3.py::test_03 PASSED                                             [100%
在 Python 测试框架中,`pytest` 提供了强大的测试资源管理机制,其中 `fixture` 是核心功能之一。`fixture` 允许将重复的初始化和清理逻辑集中管理,从而提升代码的可维护性和可重用性。 ### 代码结构与功能解析 #### 1. **Fixture 定义** 使用 `@pytest.fixture` 装饰器定义一个 `fixture` 函数,该函数可以包含初始化逻辑、返回值以及清理操作。例如: ```python import pytest @pytest.fixture def database_connection(): conn = create_db_connection() # 初始化资源 yield conn # 返回资源 conn.close() # 清理操作(yield 之后的部分) ``` 上述代码中,`database_connection` 是一个 `fixture`,用于创建数据库连接并在测试结束后关闭连接[^2]。 - `yield` 关键字表示资源的生命周期管理:在 `yield` 之前执行初始化,在 `yield` 之后执行清理。 - 如果没有需要清理的逻辑,可以直接 `return` 资源。 #### 2. **Fixture 的作用域 (Scope)** `fixture` 支持同的作用域,通过 `scope` 参数控制其生命周期: - `function`(默认):每个测试函数都会重新调用 `fixture`。 - `module`:在整个模块中只执行一次。 - `session`:在整个测试会话中只执行一次,适用于多个测试文件共享资源的情况。 例如: ```python @pytest.fixture(scope="module") def login(): print("Scope='module'") return "Ret-Login" ``` 此 `login` `fixture` 在整个模块中只会执行一次,并返回 `"Ret-Login"` 值[^1]。 #### 3. **Fixture 注入与使用** 在测试函数中,只需将 `fixture` 名称作为参数传入即可自动注入资源。例如: ```python def test_query(database_connection): result = database_connection.execute("SELECT * FROM users") assert len(result) > 0 ``` 这里 `test_query` 接收 `database_connection` 作为参数,`pytest` 会自动调用对应的 `fixture` 并传递其返回值[^3]。 #### 4. **全局 Fixture 与 conftest.py** 为了实现跨模块或跨文件共享 `fixture`,可以在项目根目录下创建 `conftest.py` 文件。该文件中的 `fixture` 可以被所有子目录下的测试文件自动识别。 例如: ```python # conftest.py import pytest @pytest.fixture(scope="session") def global_setup(): print("Global setup before all tests") yield print("Global teardown after all tests") ``` 上述 `global_setup` `fixture` 的作用域为 `session`,即在整个测试运行期间仅执行一次初始化和清理[^4]。 #### 5. **Fixture 参数化** `fixture` 还支持参数化,通过 `params` 参数生成多个测试变体。例如: ```python @pytest.fixture(params=[1, 2, 3]) def number_fixture(request): return request.param def test_number(number_fixture): assert number_fixture > 0 ``` 此例中,`number_fixture` 会依次提供 `[1, 2, 3]` 中的每个值,导致 `test_number` 执行三次。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值