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 小时前
css word-spacing属性
前端·css
千叶寻-1 小时前
正则表达式
前端·javascript·后端·架构·正则表达式·node.js
光影少年6 小时前
angular生态及学习路线
前端·学习·angular.js
无尽夏_8 小时前
HTML5(前端基础)
前端·html·html5
Jagger_8 小时前
敏捷开发流程-精简版
前端·后端
FIN66689 小时前
昂瑞微冲刺科创板:创新驱动,引领射频芯片国产化新征程
前端·安全·前端框架·信息与通信·芯片
GISer_Jing9 小时前
ByteDance——jy真题
前端·javascript·面试
睡美人的小仙女1279 小时前
浏览器为何屏蔽本地文件路径?
前端
真的想不出名儿9 小时前
Vue 中 props 传递数据的坑
前端·javascript·vue.js
FIN66689 小时前
昂瑞微:深耕射频“芯”赛道以硬核实力冲刺科创板大门
前端·人工智能·科技·前端框架·信息与通信·智能