5

我对 Django 很陌生。我正在尝试设置使用groups字段。默认类有一个字段。我尝试设置它,但这没有帮助。Userfactory_boyUser_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
4

2 回答 2

11

下面的代码使用了标准的 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)
于 2016-03-31T14:05:03.077 回答
0

由于Group与 有ManyToManyField关系User,因此您不能使用SubFactory(仅适用于ForeignKey字段):使用SubFactory,factory_boy将首先创建Group然后将其传递给UserFactory将其用作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),
      ])
于 2015-02-06T15:00:21.823 回答