Django - Testing


How does django help you with unit testing?

You can put app-specific unit tests in a file within your Django apps. For example, unit tests for the guestbook app would go into guestbook/

from django.test import TestCase
from guestbook.models import Greeting

class SimpleTest(TestCase):
    def setUp(self):
        Greeting(content='This is a test greeting').save()

    def test_setup(self):
        self.assertEqual(1, len(Greeting.objects.all()))
        self.assertEqual('This is a test greeting', Greeting.objects.all()[0].content)

Here we first test that we only have one entity in the test datastore, and then confirm that its content matches the test string 'This is a test greeting'. Django will automatically execute these unit tests when you run test. Django provides a handy django.test.TestCase class which extends Python's unittest.TestCase — we highly recommend that you use Django's TestCase as opposed to unittest in particular because the former automatically flushes your DB after every test which guarantees that each test starts with a clean slate. django.test.TestCase also comes with lots of other useful additions you should check out. See the Testing Django applications section in the Django documentation for more information.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License