如何解决pytest scope =“模块”夹具不会在测试模块后删除模型实例
我在测试文件中的scope ='module'的夹具中创建消息实例。但是当测试到达另一个模块时,该消息实例仍存在于数据库中。
在... / apps / dialogs / test / api / test_message.py中
@pytest.fixture(scope='module')
def message_by_auth_user(django_db_setup,django_db_blocker,message_factory: type,user_factory: type,user_with_auth: User) -> Message:
"""Return message by auth user."""
with django_db_blocker.unblock():
message = message_factory(written_by=user_with_auth) # Message object (1)
message_text = message.message # 'text_message_№_1'
return message
在... / apps / users / test / api / test_users.py
中
@pytest.mark.django_db
def test_get_users_view_with_filter(bool_value: bool,user_count_change: int,filter_pattern: str,api_auth_client: APIClient,user_with_auth: User,user_factory: type):
message_count = Message.objects.all().count() # 1
message = Message.objects.first() # Message object (1)
message_text = message.message # 'text_message_№_1'
更新
在我用“ yield”替换“ return”之后,并且在“ yield”之后,我手动删除了该对象,一切正常。但是测试是否应该像我的其他装置那样自动执行呢?例如,如果scope ='function',则测试会自动删除对象(每次测试之后),而不会产生任何'yield'
如果未手动删除消息实例,则即使整个scope ='module',它也将存在于整个会话中。为什么会这样?
@pytest.fixture(scope='module')
def message_by_auth_user(django_db_setup,user_with_auth: User) -> Message:
"""Return message by auth user."""
with django_db_blocker.unblock():
message = message_factory(written_by=user_with_auth)
yield message
message.delete() # This code is executed when fixture run teardown,after testing current module
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。