gpt4 book ai didi

python - 如何使用 pytest-django 为每个 session 只创建一次用户对象?

转载 作者:行者123 更新时间:2023-12-04 16:45:24 26 4
gpt4 key购买 nike

首先,我厌倦了这个:

@pytest.mark.django_db
@pytest.fixture(scope='session')
def created_user(django_db_blocker):
with django_db_blocker.unblock():
return CustomUser.objects.create_user("User", "UserPassword")

def test_api_create(created_user):
user = created_user()
assert user is not None
但我收到了 UndefinedTable错误。所以用 @pytest.mark.django_db 标记我的灯具不知何故实际上并没有注册我的 Django DB。所以接下来我尝试将 db 对象直接传递给 fixture :
@pytest.fixture(scope='session')
def created_user(db, django_db_blocker):
with django_db_blocker.unblock():
return CustomUser.objects.create_user("User", "UserPassword")

def test_api_create(created_user):
user = created_user()
assert user is not None
但后来我得到了一个错误
ScopeMismatch: You tried to access the 'function' scoped fixture 'db' with a 'session' scoped request object, involved factories
所以最后,为了确认一切正常,我尝试了:
@pytest.fixture
def created_user(db, django_db_blocker):
with django_db_blocker.unblock():
return CustomUser.objects.create_user("User", "UserPassword")

def test_api_create(created_user):
user = created_user()
assert user is not None
这工作得很好,但现在每次设置或拆除我的函数时都会调用我的 create_user 函数。这里的解决方案是什么?

最佳答案

@hoefling 有答案,我需要通过 django_db_setup反而。

@pytest.fixture(scope='session')
def created_user(django_db_setup, django_db_blocker):
with django_db_blocker.unblock():
return CustomUser.objects.create_user("User", "UserPassword")

关于python - 如何使用 pytest-django 为每个 session 只创建一次用户对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62722599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com