Getting Started with Python and Django - Part 3

Continued from Part 2

Unit Testing Django Models

In order to create tests for whateverapp, we populate the whateverapp/tests.py with the tests we would like to run.

The this example, I'm using the library factory_boy to create factory objects to use in our unit tests instead of fixtures, which are difficult to maintain over time. In this example, you can see how easy it is to handle complex structures, such as models, which are linked by foreign keys.

./whateverproject/whateverapp/tests.py

from django.test import TestCase  
from whateverapp.models import *  
import factory


class CityFactory(factory.DjangoModelFactory):  
    class Meta:
        model = City

    name = "New York City"


class HotelFactory(factory.DjangoModelFactory):  
    class Meta:
        model = Hotel

    name = "Omni",
    room_charge = 489.00
    rooms_available = True,
    rating = "5 Star"
    city = factory.SubFactory(CityFactory)


class HotelTestCase(TestCase):

    def test_basic_addition(self):
        self.assertEqual(1 + 1, 2)

    def test_get_rating(self):
        city = CityFactory.create()
        hotel = HotelFactory.create()
        self.assertEqual(hotel.rating, "5 Star")
        self.assertEqual(hotel.city.name, city.name)

Running the test:

$ ./manage.py test whateverapp
..
----------------------------------------------------------------------
Ran 2 tests in 0.002s

OK

There are two tests in this example:

  • One is the extremely simple test test_basic_addition which demonstrates a test case that will pass.
  • The second is test_get_rating, which is also really simple but demonstrates how we use factories to set up our testable objects. Notice how factory.SubFactory(CityFactory) is used to handle our foreign key relationship as well without the need for dealing with fixtures.

Source Code on GitHub: https://github.com/justinbellamy/whateverprojectPython