【问题标题】:use factoryboy for django User with py.test使用 py.test 为 django 用户使用 factoryboy
【发布时间】:2015-09-09 08:36:16
【问题描述】:

我正在将 Django 应用程序的 UnitTests 迁移到 py.test,但在 UnitTests 中,他们使用 factory-boy 来创建 django.contrib.auth.models.User 的实例。 pytest-factory-boy 如何做到这一点?

【问题讨论】:

  • 我建议不要使用太多这些“胶水”库,如 pytest-factory-boy。在我看来,它们使事情变得过于复杂,并且会使您的代码更难推理。您可以在测试服中使用香草工厂男孩并临时添加胶水。

标签: django python-2.7 django-authentication pytest factory-boy


【解决方案1】:

在 py.test 中创建用户,而不需要工厂非常简单。 py.test 已经有一个包含内置 Django admin_user 和 admin_client 固定装置的帮助程序,如here 所述。

这里有一些代码,用于在您的 conftest.py 中创建普通用户:

import pytest
from django.contrib.auth.models import User
@pytest.fixture
def user_client(client):
    """
    User fixture for tests with unprivileged user
    """
    user = User.objects.create_user(
        username='user',
        password='pass',
        first_name='Normal',
        last_name='User'
    )
    response = client.post(reverse('login'), data={'username': 'user', 'password': 'pass'})

    assert response.status_code == 302
    return user_client

【讨论】:

  • 您不应该直接导入用户。在您的应用程序代码中,您应该使用 settings.AUTH_USER_MODEL 并且对于您的测试代码,pytest-django 插件提供了方便的 django_user_model 夹具。然后 user = User.objects.create_user 变成 django_user_model.objects.create_user(...
猜你喜欢
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-29
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多