You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断pytest中session级fixture是首次还是非首次调用

实现Session级Pytest Fixture:首次调用返回True,后续返回False

要实现这个需求,核心思路是让session级fixture返回一个带状态的闭包函数——因为session级fixture只会在测试会话开始时初始化一次,但返回的闭包可以在每次被调用时维护并更新状态。

具体代码实现如下:

import pytest

@pytest.fixture(scope="session")
def first():
    # 初始化状态变量,标记是否已被调用过
    has_been_called = False
    
    def check_first():
        nonlocal has_been_called
        if not has_been_called:
            # 首次调用:返回True,并更新状态
            has_been_called = True
            return True
        # 非首次调用:返回False
        return False
    
    # 返回闭包函数,供测试用例调用
    return check_first

测试验证

你可以用以下测试用例验证效果:

def test_first_invocation(first):
    assert first() is True

def test_second_invocation(first):
    assert first() is False

def test_third_invocation(first):
    assert first() is False

原理说明

  • session级fixture first 仅在测试会话启动时执行一次,创建了状态变量 has_been_called 和闭包函数 check_first。
  • 每次测试用例调用 first() 时,实际执行的是闭包函数 check_first,它会读取并更新外层的 has_been_called 状态。
  • 首次调用时状态为False,返回True并将状态置为True;后续所有调用都会直接返回False。

内容的提问来源于stack exchange,提问作者someone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 13:40:26