Created
February 23, 2020 17:25
-
-
Save MrCordeiro/cf053688cb85a6d4c46ec03e4188250a to your computer and use it in GitHub Desktop.
Using factory-boy to create users with permissions in Django Tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Holds all factories used in this app's test suite """ | |
import factory | |
from django.contrib.auth import get_user_model | |
User = get_user_model() | |
def get_or_create_xxx_group(): | |
""" Returns the XXX Group """ | |
try: | |
group_obj = Group.objects.get(name__iexact="xxx") | |
except Group.DoesNotExist: | |
group_obj = Group.objects.create(name="Xxx") | |
group_obj .permissions.add( | |
Permission.objects.get(codename="change_user"), | |
Permission.objects.get(codename="delete_user"), | |
) | |
return group_obj | |
class UserFactory(factory.django.DjangoModelFactory): | |
class Meta: | |
model = User | |
username = factory.Faker('email') | |
email = username | |
first_name = factory.Faker('first_name') | |
last_name = factory.Faker('last_name') | |
@factory.post_generation | |
def add_to_group(obj, create, extracted, **kwargs): | |
"""Add mock user into group matching their role""" | |
if create: | |
if obj.role == User.ADMIN: | |
obj.groups.add(get_or_create_xxx_group()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks mate!