如何使用factory_boy设置用户组

时间:2015-02-06 14:11:21

标签: django django-testing factory-boy

我是Django的新手。我正在尝试使用groupsUser设置factory_boy字段。默认的User类有一个字段_groups。我尝试过设置,但这没有帮助。

class GroupFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Group

    name = Sequence(lambda n: "group_{0}".format(n))


class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User

    username = factory.Sequence(lambda n: "user_{0}".format(n))
    password = "test"
    first_name = u'ßhamra'
    last_name = u'ßhamra'
    _groups = factory.SubFactory(GroupFactory)


    @classmethod
    def _create(cls, model_class, *args, **kwargs):
        """
        Override the default ``_create`` with our custom call.
        Due to internal behavior or create user create method that                forces is_staff kwarg


    """
    g = GroupFactory("abc")
    manager = cls._get_manager(model_class)
    is_staff = kwargs.pop('is_staff', None)
    user = manager.create_user(*args, **kwargs)


    if is_staff:
        user.is_staff = is_staff
        user.save()
    return user

2 个答案:

答案 0 :(得分:7)

以下代码使用标准的django组。您必须使用工厂男孩后期生成来向用户添加组。

工厂

import factory
import django.contrib.auth.models as auth_models
from django.contrib.auth.hashers import make_password

user_password = 'password'

class SubscribedGroupFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = auth_models.Group

    name = 'subscribed'

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = auth_models.User

    first_name = "Sophia"
    last_name = "Ball"
    username = "clowngirl@heaven.com"
    password = make_password(user_password)
    email = "clowngirl@heaven.com"
    is_active = True

    @factory.post_generation
    def groups(self, create, extracted, **kwargs):
        if not create:
            return

        if extracted:
            for group in extracted:
                self.groups.add(group)

测试

from app.factories import UserFactory, SubscribedGroupFactory, user_password
class TestCenterTest(TestCase):

    def test_test_center_redirect(self):
        user = UserFactory.create(groups=(SubscribedGroupFactory.create(),))
        self.client.login(username=user.email, password=user_password)
        response = self.client.get('/test-center/')
        self.assertEqual(302, response.status_code)

答案 1 :(得分:0)

由于GroupManyToManyField的关联User,您无法使用SubFactory(仅适用于ForeignKey字段):with { {1}},SubFactory将首先创建factory_boy,然后将其传递给GroupUserFactory将其用作User.objects.create(_groups=Group)。这不会奏效。

请查看文档的Recipes部分:http://factoryboy.readthedocs.org/en/latest/recipes.html#simple-manytomany

此处,以下代码应该有效:

  class UserFactory(factory.django.DjangoModelFactory):
      # All other declarations here

      groups = factory.List([
          factory.RelatedFactory(GroupFactory),
      ])