Search code examples
pythondjangounit-testingpython-unittestdjango-unittest

Python / Django - How to get all methods in a unittest class to share the same database?


This is my code:

Link to my imports are here: https://github.com/django/django/blob/master/django/core/urlresolvers.py https://github.com/django/django/blob/master/django/contrib/auth/models.py https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/status.py https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/test.py

from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APITestCase

class UserTests(APITestCase):
    def test_create_user(self):
        """
        Ensure we can create a new user object.
        """
        url = reverse('user-list')
        data = {'username': 'a', 'password': 'a', 'email': 'a@hotmail.com'}
        # Post the data to the URL to create the object
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        # Check the database to see if the object is created.
        # This check works.
        self.assertEqual(User.objects.count(), 1)

    def test_get_user(self):
        """
        Ensure we can get a list of user objects.
        """
        # This fails and returns an error
        self.assertEqual(User.objects.count(), 1)

When I run the test, it raises an error saying AssertionError: 0 != 1 because in the function test_get_user, the user created in test_create_user is not visible. Is there a way for me to get all the methods in a class to share the same database so that if I create a user in test_create_user, I can access it in the methods which come below it?

Edit: The reason I want them to share the same database for all the methods is because all of my test cases in the UserTests class will need a user created so I don't want to have to repeat the same code all the time even when it is tested in test_create_user.

I know I can use def setUp(self) but I'm doing a "create user" test in my first method so I want to be able to test if I can create it first before creating it in def setUp(self).


Solution

  • You should set up your data explicitly in each test. Tests must not depend on each other.