![](/img/trans.png)
[英]How to create a test-only Django model in general (and with pytest-django specifically)
[英]How can I use pytest-django to create a user object only once per session?
首先,我厭倦了這個:
@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 object 直接傳遞給夾具:
@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
這工作得很好,但是現在每次我的 function 正在設置或拆除時,我的 create_user function 都會被調用。 這里有什么解決方案?
@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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.