Davtho1983
Davtho1983

Reputation: 3954

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)

Upvotes: 3

Views: 4736

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477608

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='[email protected]')

Upvotes: 8

Related Questions