如何为接收参数的pytest fixture实现自动清理逻辑?
带参数pytest fixture的清理方案
不需要拆分创建和删除为两个fixture,你可以通过在fixture内部维护已创建用户的记录,利用fixture自身的生命周期特性完成统一清理,具体实现如下:
@pytest.fixture def create_user_in_third_party(): from clients import third_party_client created_users = [] def _create_user_in_third_party(user: User): third_party_client.create_user(user) created_users.append(user) return user yield _create_user_in_third_party # 测试结束后批量清理所有创建的用户 for user in created_users: third_party_client.delete_user(user)
原方案失效原因
你之前把内部函数写成了生成器,但测试中调用该函数时仅得到生成器对象,并未对其进行迭代,导致yield之后的删除代码永远不会执行。而上述方案在fixture层面维护用户列表,借助fixture的yield机制(执行到yield时进入测试阶段,测试结束后自动执行yield后的代码)完成清理,全程无需拆分fixture。
测试使用示例
在测试中直接调用fixture返回的函数创建用户即可,测试结束后会自动清理所有通过该函数创建的用户:
def test_third_party_user_function(create_user_in_third_party): test_user = User(name="TestUser") create_user_in_third_party(test_user) # 编写你的测试逻辑
内容的提问来源于stack exchange,提问作者user10205830
相关产品推荐
相关产品推荐

