Python has a nice module called doctest that lets you embed test cases with the function documentation. This is a really nice time saver because these test cases also serve as examples, which I would have to write anyways. I was working on a function where I decided to write a few doctests, but I did not like waiting for django’s test runner to create the database and then run the tests, which wasn’t necessary for these specific tests. So, I thought why not manually run the doctests in a django shell?
ipython has support for outputting in doctest mode (%doctest_mode magic function), but it doesn’t come with any magic functions that will let you quickly run doctests. So, I ended up writing the following magic function that will let you accomplish this.
To use this, here is what you do.
The magic function.
1 2 3 4 5 6 7 8 9
def dodoctest(self, arg): """Initializes the test runner and runs the doc tests for the specified object.""" ip = self.api ip.ex("""import doctest, unittest; suite = unittest.TestSuite() suite.addTest(doctest.DocTestSuite(%s)) runner = unittest.TextTestRunner() runner.run(suite) """ % arg)
The call to register the above magic function.