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

标签 python pytest fixtures pytest-django django-fixtures

首先,我厌倦了这个:

@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/

相关文章:

python - FormSet 始终默认渲染两种形式 Django

python - 使用 GOOGLE Analytics API - 指标/维度

python-3.x - 如何将命令行参数从pytest传递给代码

python - 从 wpa_cli 状态获取 p2p_device_address

python - 根据列名中是否存在后缀对列进行排序

python - Pytest 的 Mock/Monkeypatch BeautifulSoup html 对象

python - 在tox+pytest中使用自己的包

java - FEST:当单元格位于带有 CellRenderPane 的 JTable 下时检索单元格值

django - 测试期间未加载 fixture

php - 在 Nelmio Alice fixture 生成器中将参数设置为数组