Skip to content
Advertisement

Django Unit Test – IDs of created objects

Sample models.py

models.py

class Food(models.Model):
    name = models.CharField(max_length=50, verbose_name='Food')

    def __str__(self):
        return self.name

Suppose that I have written unit test/s:

from django.test import TestCase
from myapp.models import Food

class TestWhateverFunctions(TestCase):
    """
    This class contains tests for whatever functions.
    """

    def setUp(self):
        """
        This method runs before the execution of each test case.
        """
        Food.objects.create(name='Pizza') # Will the created object have id of 1?
        Food.objects.create(name='Pasta') # Will the created object have id of 2?

    def test_if_food_is_pizza(self):
        """
        Test if the given food is pizza.
        """
        food = Food.objects.get(id=1)

        self.assertEqual(food.name, 'Pizza')

    def test_if_food_is_pasta(self):
        """
        Test if the given food is pasta.
        """
        food = Food.objects.get(id=2)

        self.assertEqual(food.name, 'Pasta')

I was wondering if it’s safe to assume that the id’s of the created objects in setUp() method will always start at id 1 and so on and so forth? If not, is there a specific reason why if the test database is always destroyed after running all tests?

Advertisement

Answer

It is not safe to assume that the ids will always start at 1 and increment. They may have higher ids if other tests have run beforehand and created Food rows, and unit tests are not executed in any guaranteed order.

Save references to the model instances on your test setup:

class TestWhateverFunctions(TestCase):

    def setUp(self):
        self.food1 = Food.objects.create(name='Pizza')
        self.food2 = Food.objects.create(name='Pasta')
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement