Code without tests is broken as designed - Jacob Kaplan-Moss (Django co-creator)
I am a fan of TDD (test driven development) and get nervous anytime I am working with a codebase that does not have a robust automated testing framework.
Therefore, it's important as part of my learning Django to try out the testing framework to see how it feels to work with.
According to the Django official docs the preferred testing approach is using the unittest
module that is built-in to the Python standard library.
Django's testing framework provides several extensions on top of the standard unittest.TestCase
base class. These include a test client for making dummy Web browser requests and four test case classes:
SimpleTestCase
-
TestCase
TransactionTestCase
LiveServerTestCase
An overly simplified summary of their use cases is SimpleTestCase
is used when a database is unnecessary. While TestCase
is used when you want to test the database.
TransactionTestCase
is helpful to directly test databases transactions while LiveServerTestCase
launches a live server thread for testing with browser-based tools such as Selenium.
One strange convention I found was the fact the unittest
and django.test
methods are written in camelCase rather than the standard snake_case pattern normally found in Python. Apparently, this stems for the fact that unittest
is based on the jUnit
testing framework from Java which utilises camelCase. This seems a bit bizarre to me, but I will stick with the communities conventions.
Testing with a database
When testing with a database, we need to use TestCase
, which will let us create a test database. In other words, we don't need to run tests on our actual database. Instead we can make a separate test database, fill it with sample data pertinent to our scenarios, then test against it.
This is much safer and a more performant approach to testing against our actual production database.
To make use of this, we use the hook setUpTestData()
to create our test data; it is much faster thatn using the setUp()
hook from Python's unittest
because it creates the test data only once per test case rather than per test.
Note: test functions must start with the word "test" to be run.
Top comments (0)