Wednesday, September 30, 2009

Django unit testing with docstrings

Here's how I was able to get docstring tests to work in Django. Directory structure:
project/
  |  
  +-- app/
  |    |
  |    +-- __init__.py
  |    |
  |    +-- tests.py
  |    |
  |    +-- mymodule.py
  |    |
  |    etc.
  |
  +-- urls.py
  |
  +-- __init__.py
  |
  etc.

The docstring tests are in mymodule.py. The file tests.py (note: plural) contains:
import doctest
import mymodule

doctest.testmod(mymodule)
Then, if you are in the directory project, you can run the unit tests with
python ./manage.py test app

Original Approach

My first cut was to put this in tests.py:
import unittest
import doctest
import mymodule

suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite(mymodule))
runner = unittest.TextTestRunner()
runner.run(suite)
While that ran, it also raised the following exceptions, which I didn't bother to figure out.
Traceback (most recent call last):

  File "./manage.py", line 11, in 
    execute_manager(settings)

  File "/usr/lib/python2.5/site-packages/
      django/core/management/__init__.py",
      line 348, in execute_manager utility.execute()

  File "/usr/lib/python2.5/site-packages/
      django/core/management/__init__.py",
      line 293, in execute
      self.fetch_command(subcommand).run_from_argv(self.argv)

  File "/usr/lib/python2.5/site-packages/
      django/core/management/base.py", 
      line 192, in run_from_argv
      self.execute(*args, **options.__dict__)

  File "/usr/lib/python2.5/site-packages/
      django/core/management/base.py", 
      line 219, in execute
      output = self.handle(*args, **options)

  File "/usr/lib/python2.5/site-packages/
      django/core/management/commands/test.py", 
      line 23, in handle failures = 
      test_runner(test_labels, verbosity=verbosity, 
      interactive=interactive)

  File "/usr/lib/python2.5/site-packages/
      django/test/simple.py", 
      line 179, in run_tests
      suite.addTest(build_suite(app))

  File "/usr/lib/python2.5/site-packages/
      django/test/simple.py",
      line 63, in build_suite
      suite.addTest(test_module.suite())

  File "/usr/lib/python2.5/unittest.py",
      line 437, in __call__
      return self.run(*args, **kwds)

References

  1. Introduction to Python/Django testing: Basic Doctests Gave me some hints.
  2. Breaking out the Django Tests Suggested where to poke around in the Django code.

No comments:

Post a Comment