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 的执行顺序!如果你还有其他问题或者需要更详细的解释,随时告诉我。

相关推荐
还是鼠鼠1 小时前
图书管理系统 Axios 源码__新增图书
前端·javascript·vscode·ajax·前端框架·node.js·bootstrap
还是鼠鼠4 小时前
图书管理系统 Axios 源码 __删除图书功能
前端·javascript·vscode·ajax·前端框架·node.js·bootstrap
轻口味4 小时前
Vue.js `Suspense` 和异步组件加载
前端·javascript·vue.js
m0_zj5 小时前
8.[前端开发-CSS]Day08-图形-字体-字体图标-元素定位
前端·css
还是鼠鼠6 小时前
图书管理系统 Axios 源码__编辑图书
前端·javascript·vscode·ajax·前端框架
北极象6 小时前
vue3中el-input无法获得焦点的问题
前端·javascript·vue.js
百度网站快速收录6 小时前
网站快速收录:如何优化网站头部与底部信息?
前端·html·百度快速收录·网站快速收录
Loong_DQX6 小时前
【react+redux】 react使用redux相关内容
前端·react.js·前端框架
GISer_Jing6 小时前
react redux监测值的变化
前端·javascript·react.js
engchina7 小时前
CSS 样式化表格:从基础到高级技巧
前端·css