如何判断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
相关产品推荐
相关产品推荐

