Django Unit Tests for Different Databases

Test | | Industry Thoughts

We run our unit tests against SQLite. This allows us to run the tests very frequently (because SQLite with an in-memory data is FAST). Most of our tests do not depend on the database backend, so this is not a problem.

Today however, I fixed a bug that affected MySQL but not SQLite, so my unit test passed with or without the fix in place. I wanted to run this test case against MySQL while continuing to run the bulk of our test suite against SQLite. I did not find anything on the web about doing this so I devised a method for it.

My method leverages Django’s multidb functionality, we are able to register the default database as well as an additional mysql database. The default database will be used for the entire test suite. What I needed was a way to direct my single test case to the mysql database. I did this using a unittest.TestCase subclass and a Django database router.

The unittest.TestCase subclass utilizes the unittest.TestCase.setUp() method to store the database name in thread local storage. The router looks for a database name in thread local storage, and routes queries accordingly. The TestCase.tearDown() method removes the database name from thread local storage to restore routing to the default database.

The only other issue is that the unittest.TestCase class must set the multi_db attribute to True. This is necessary to ensure that any test fixtures are loaded to both databases not just default. This is also handled by the mixin.

If you need something like this, the relevant code can be found in this gist.

Ben Timby

I am the Chief Technology Officer and Co-Founder of SmartFile. I'm in charge of the operations and engineering of SmartFile Web Application. I'm also well-versed in several different programming languages including python and django. View my GitHub profile at

More Posts


Leave a Reply

  • (will not be published)