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 会在当前模块内首次使用前执行一次,并在模块结束时清理。

相关推荐
weixin-a153003083161 小时前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
ai小鬼头1 小时前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
wen's1 小时前
React Native 0.79.4 中 [RCTView setColor:] 崩溃问题完整解决方案
javascript·react native·react.js
黄雪超1 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice2 小时前
对象的finalization机制Test
java·开发语言·jvm
思则变2 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
一只叫煤球的猫2 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
vvilkim2 小时前
Electron 自动更新机制详解:实现无缝应用升级
前端·javascript·electron
vvilkim2 小时前
Electron 应用中的内容安全策略 (CSP) 全面指南
前端·javascript·electron
lijingguang2 小时前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#