pytest.fixture

pytest 中,@pytest.fixture 提供了全局前置、局部前置等功能,以便在测试运行前后设置所需的环境和资源。具体用法如下:

1. 全局前置(scope="session"

使用 scope="session"autouse=True,实现一个在测试会话全局范围内只运行一次的前置。例如:

import pytest

@pytest.fixture(scope="session", autouse=True)

def global_setup(): # 会话范围内的全局前置逻辑

print("\nSetting up session-wide resources.")

yield # 会话范围内的清理逻辑

print("\nTearing down session-wide resources.")

此代码段会在整个测试会话开始前运行一次,并在测试会话结束时清理。

2. 局部前置(默认scope="function"

对于特定测试函数或模块可以定义局部前置,通过将 scope 设置为 function(默认值)或 module 实现。例如:

复制代码
 

python

复制代码

import pytest @pytest.fixture(scope="function") def function_setup(): # 局部的前置逻辑,针对每个测试函数执行 print("\nSetting up resources for individual test.") yield # 局部清理 print("\nTearing down resources for individual test.") def test_example_1(function_setup): # 这个测试会使用局部前置 `function_setup` assert True def test_example_2(function_setup): # 另一个测试也会使用局部前置 `function_setup` assert True

这样,function_setup 会在 test_example_1test_example_2 执行前后分别运行一遍。

3. 模块范围前置(scope="module"

如果需要在整个模块范围内执行前置,可以将 scope 设置为 module

复制代码
 

python

复制代码

import pytest @pytest.fixture(scope="module") def module_setup(): # 模块级别的前置逻辑 print("\nSetting up module-level resources.") yield # 模块级别的清理逻辑 print("\nTearing down module-level resources.") def test_module_example_1(module_setup): assert True def test_module_example_2(module_setup): assert True

在此示例中,module_setup 会在当前模块内首次使用前执行一次,并在模块结束时清理。

相关推荐
zhougl9963 小时前
cookie、session、token、JWT(JSON Web Token)
前端·json
Ryan今天学习了吗3 小时前
💥不说废话,带你上手使用 qiankun 微前端并深入理解原理!
前端·javascript·架构
高端章鱼哥3 小时前
前端新人最怕的“居中问题”,八种CSS实现居中的方法一次搞懂!
前端
冷亿!3 小时前
Html爱心代码动态(可修改内容+带源码)
前端·html
Predestination王瀞潞3 小时前
Java EE开发技术(第六章:EL表达式)
前端·javascript·java-ee
掘金013 小时前
在 Vue 3 项目中使用 MQTT 获取数据
前端·javascript·vue.js
QuantumLeap丶3 小时前
《uni-app跨平台开发完全指南》- 03 - Vue.js基础入门
前端·vue.js·uni-app
j_xxx404_3 小时前
C++ STL:list|了解list|相关接口|相关操作
开发语言·c++
一 乐3 小时前
个人理财系统|基于java+小程序+APP的个人理财系统设计与实现(源码+数据库+文档)
java·前端·数据库·vue.js·后端·小程序
wyzqhhhh3 小时前
同时打开两个浏览器页面,关闭 A 页面的时候,要求 B 页面同时关闭,怎么实现?
前端·javascript·react.js