pytest8.x版本 中文使用文档-------29.示例:一个会话级夹具(session-fixture),可以查看所有已收集的测试

一个会话级别的夹具(fixture)可以有效地访问所有收集到的测试项。以下是一个夹具函数的示例,该函数遍历所有收集到的测试项,检查它们的测试类是否定义了一个名为 callme 的方法,并调用它:

# conftest.py 文件的内容  
  
import pytest  
  
@pytest.fixture(scope="session", autouse=True)  
def callattr_ahead_of_alltests(request):  
    print("callattr_ahead_of_alltests called")  
    seen = {None}  # 用于跟踪已经检查过的类,初始化为包含 None 的集合
    session = request.node  # 获取当前会话的根节点  
    for item in session.items:  # 遍历会话中的所有测试项  
        cls = item.getparent(pytest.Class)  # 获取测试项所属的测试类(如果存在的话)  
        if cls not in seen:  # 如果这个类还没有被检查过  
            if hasattr(cls.obj, "callme"):  # 检查这个类的实例(cls.obj)是否有 `callme` 方法  
                cls.obj.callme()  # 如果有,就调用它  
            seen.add(cls)  # 将这个类添加到已检查的集合中

现在,测试类可以定义一个 callme 方法,该方法将在运行任何测试之前被调用:

# test_module.py 文件的内容  
  
class TestHello:  
    @classmethod  
    def callme(cls):  
        print("callme called!")  
  
    def test_method1(self):  
        print("test_method1 called")  
  
    def test_method2(self):  
        print("test_method2 called")  
  
  
class TestOther:  
    @classmethod  
    def callme(cls):  
        print("callme other called")  
  
    def test_other(self):  
        print("test other")  
  
# works with unittest as well ...
import unittest


class SomeTest(unittest.TestCase):
    @classmethod
    def callme(self):
        print("SomeTest callme called")

    def test_unit1(self):
        print("test_unit1 method called")

如果你在没有捕获输出的情况下运行这个命令:

$ pytest -q -s test_module.py

你将看到以下输出:

callattr_ahead_of_alltests called  
callme called!  
callme other called  
SomeTest callme called  
test_method1 called  
.test_method2 called  
.test other  
.test_unit1 method called  
.  
4 passed in 0.12s

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值