pytest中@pytest.fixture常用顺序function

ytest中@pytest.fixture用法讲解

备注:内容来自chatGPT

在 pytest 中,@pytest.fixture 是一个非常强大的功能,用于设置测试所需的环境和状态。它可以通过 scope 参数控制其生命周期。以下是 scope="function" 时的执行顺序以及一些详细解释。

bash 复制代码
scope 的类型

pytest.fixture 的 scope 参数可以有以下几种取值:

  • function:每个测试函数都会调用该 fixture。
  • class:每个测试类的实例共享该 fixture。
  • module:每个模块内的测试共享该 fixture。
  • session:整个测试会话共享该 fixture。
bash 复制代码
scope="function" 的执行顺序

当 scope 设置为 function 时,fixture 的执行顺序如下:

1、测试函数开始之前

@pytest.fixture 装饰器定义的 fixture 会在测试函数执行前被调用。

如果 fixture 依赖于其他 fixture,依赖的 fixture 会被先执行。

2、执行测试函数:

  • 一旦 fixture 被调用,控制流会转到被测试的函数。
  • 测试函数运行时,可以直接使用 fixture 的返回值。

3、测试函数结束后:

测试函数执行完毕后,fixture 代码中的清理代码会被执行(如果定义了 yield,则在 yield 后的代码会执行)。

图示

这里用文字描述一下顺序,图形化展示比较复杂,但我可以用一种更直观的方式来解释:

bash 复制代码
+-------------------+
|  Fixture Setup    | <--- 执行 @pytest.fixture 定义的代码
|  (setup code)     |
+-------------------+
         |
         V
+-------------------+
|   Test Function    | <--- 执行测试函数
|  (test code)      |
+-------------------+
         |
         V
+-------------------+
|  Fixture Teardown  | <--- 执行清理代码
|  (teardown code)   |
+-------------------+

例子

下面是一个示例,展示了如何使用 @pytest.fixture:

python 复制代码
```bash
import pytest

@pytest.fixture(scope="function")
def sample_fixture():
    # setup code
    print("Setting up fixture")
    yield "data"  # 这里是 fixture 的返回值
    # teardown code
    print("Tearing down fixture")

def test_one(sample_fixture):
    print(f"Test One: {sample_fixture}")

def test_two(sample_fixture):
    print(f"Test Two: {sample_fixture}")
复制代码
执行示例
运行上述代码时,你会看到以下输出,表明了执行顺序:

```python
Setting up fixture
Setting up fixture
Test One: data
Tearing down fixture
Setting up fixture
Test Two: data
Tearing down fixture

总结

scope="function" 的 fixture 每个测试函数都会独立执行一次。

  • 在执行测试之前会先执行 setup 代码,测试执行后再执行 teardown 代码。
  • 如果有多个 fixture 互相依赖,pytest 会自动处理它们的执行顺序。

希望这能帮助你更好地理解 pytest.fixture 的执行顺序!如果你还有其他问题或者需要更详细的解释,随时告诉我。

相关推荐
雨田言炎21 小时前
十、QThread多线程
linux·服务器·开发语言·前端·qt
IT_陈寒21 小时前
Vite热更新失效?我的几个犯傻操作害我debug两小时
前端·人工智能·后端
晓得迷路了21 小时前
栗子前端技术周刊第 141 期 - Next.js 16.3、npm 安全事件、2026 CSS 现状调查报告结果...
前端·javascript·npm
2601_9657984721 小时前
Launch Your Wellness App Fast: The Truth About Meditation Source Code
前端·macos·ios·objective-c·cocoa
周小董1 天前
[1367]npm 安装 canvas 报错 node-gyp ERR
前端·npm·node.js
智脑API1 天前
Codex config.toml check_for_update_on_startup 怎么关闭?离线环境与版本提醒排查
运维·服务器·前端
存在的五月雨1 天前
前端布局-flex
前端
Zzj_tju1 天前
Tool-Using LLM 论文精读路线:从 ReAct 到可验证工具调用
前端·react.js·前端框架
To_OC1 天前
别再瞎写 React Router!7 个高频踩坑点一次性讲透
前端·javascript·react.js
岭南灯火1 天前
前端通用交互式几何编辑器的开发经验
前端·设计模式·架构