Search code examples
djangodjango-tests

Django test model with fake user


I have a django model I want to test. The model includes a 'user' field. Is there a way of creating a temporary user for the purposes of testing?

tests.py

from django.test import TestCase
from .models import Task
from django.utils import timezone
from .forms import Taskform

# models test
class TaskTest(TestCase):

    def create_task(self, title="Title", description="A description"):
        return Task.objects.create(title=title, pub_date=timezone.datetime.now(), completed=False, description=description, user='user')

    def test_task_creation(self):
        w = self.create_task()
        self.assertTrue(isinstance(t, Task))
        self.assertEqual(t.__unicode__(), t.title)

Solution

  • Well a User is actually just another Django model (of course it has some extra bindings in Django which makes it a "popular" and "special" model, but it has the same interface, and you can construct instances like with other models). So you can import that model, and create a User.

    For example:

    from django.contrib.auth.models import User
    
    my_user = User.objects.create(username='Testuser')

    Typically in tests, one however uses a factory (for example with the Factory Boy) to make it easy to construct objects with some data. For example:

    import factory
    from factory.django import DjangoModelFactory
    
    class UserFactory(DjangoModelFactory):
    
        username = factory.Sequence('testuser{}'.format)
        email = factory.Sequence('testuser{}@company.com'.format)
    
        class Meta:
            model = User

    You can then create a user with:

    my_user2 = UserFactory()
    my_user3 = UserFactory(username='alice')
    my_user4 = UserFactory(username='bob', email='bob@work.com')