Thursday, July 25, 2013

A Nose Specific Django Settings File

The Python Nose test framework has a several advantages over Django's default test framework.  I personally wanted to use Nose because of the xunit plugin which can output results in xunit format.  I needed this output format so that test results could be interpreted by Bamboo, the continuous integration solution we're using at my work.

For using Nose with Django, the django-nose package is an obvious choice.  However, it requires setting several settings values in your settings.py file that were only used by Nose.  Also, I like being able to run my tests using Django's default test runner.  I'm familiar with the output format, with the syntax for specifying how to run a single test, etc. and I didn't want to limit myself to running only Nose tests.

The approach I took was to create a new settings file for running nose tests.  This would contain just the settings needed for configuring django-nose, and import the main settings file to fill in the rest.  This is kind of the opposite of the usual pattern of importing a "local_settings.py" file at the bottom of your main "settings.py" to specify scenario specific settings (e.g. development vs production).

The comments in the script specify how to use it.  I hope it's helpful.

"""
Specify this settings file to run nose tests format instead of the standard Django test runner.
Useful for getting coverage reports and for getting xunit compaible reports for use with a CI server.
To run all tests:
> python manage.py test --settings=settings_folder.nose_settings apps
To run tests only for a specific app:
> python manage.py test --settings=settings_folder.nose_settings apps.myapp.tests
"""
try:
from settings import *
except ImportError:
pass
TEST_RUNNER = 'django_nose.NoseTestSuiteRunner'
NOSE_ARGS = [
'--testmatch=^test',
'--with-xunit',
'--xunit-file=xmlrunner/nosetests.xml',
'--with-coverage',
'--cover-xml',
'--cover-package=apps.myapp,apps.mysecondapp', # a list of packages to get coverage data for
'--cover-xml-file=xmlrunner/coverage.xml'
]
# Create directory for xml files
if not os.path.exists("xmlrunner"):
os.makedirs("xmlrunner")

No comments:

Post a Comment