Django Unit Tests for Different Databases

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 database as well as an additional database. The database will be used for the entire test suite. What I needed was a way to direct my single test case to the database. I did this using a unittest.TestCase subclass and a Django database router.

The subclass utilizes the 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 method removes the database name from thread local storage to restore routing to the database.

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

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

SmartFile is a business file mangement platform that gives you more control, compliance and security.

TO SIGN UP