-
-
Save rolo/4234567 to your computer and use it in GitHub Desktop.
Django UserFactory with factory_boy - using random instead of clock to avoid username clashes
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
import random | |
from django.contrib.auth.models import User | |
from factory import Factory, LazyAttribute, Sequence | |
class UserFactory(Factory): | |
""" | |
Creates a new ``User`` object. | |
Username will be a random 30 character md5 value. | |
Email will be ``[email protected]`` with ``N`` being a counter. | |
Password will be ``test123`` by default. | |
""" | |
FACTORY_FOR = User | |
username = LazyAttribute(lambda x: '%030x' % random.randrange(256 ** 15)) | |
email = Sequence(lambda n: 'user{0}@example.com'.format(n)) | |
@classmethod | |
def _prepare(cls, create, **kwargs): | |
password = 'test123' | |
if 'password' in kwargs: | |
password = kwargs.pop('password') | |
user = super(UserFactory, cls)._prepare(create, **kwargs) | |
user.set_password(password) | |
if create: | |
user.save() | |
return user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment