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.

  1. Edit your ~/.ipython/ file…
    1. Copy and paste the dodoctest function at the bottom (before the main() call).
    2. Copy and paste the ip.expose_magic call all the way at the end of the file (i.e. after the main() call).
  2. Run django shell (or ipython directly): shell
  3. Import your models: import myproject.myapp.models
  4. Call the %dodoctest function with your models as a parameter:
    %dodoctest myproject.myapp.models

The magic function.

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()
runner = unittest.TextTestRunner()
""" % arg)

The call to register the above magic function.

ip.expose_magic('dodoctest', dodoctest)
Back to blog...