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.
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
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.