Enable setup.py test in your Django apps

Erich Holscher has posted a blog entry with the same title about a year ago. This helped me out quite a lot to get python setup.py test working with a reusable app.

Unfortunatelly the code in his blog post is not working anymore exactly like this. Django has changed its internal structure of its default test runner. So here is how you can get setup.py test working today.

Let's assume you have a repository layout for your app like this:

|-\ django_app/
| |- __init__.py
| |- models.py
| |- etc ...
|
|-\ django_app_tests/
| |-\ test_app
| | |- models.py
| | |- etc ...
| |- manage.py
| |- settings.py
| |- etc ...
|
|- setup.py

You would usually run your tests with:

cd django_app_tests
python manage.py test test_app

Right? Now lets create a new file django_app_tests/runtests.py:

# This file mainly exists to allow python setup.py test to work.
import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_app_tests.settings'
test_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, test_dir)

from django.test.utils import get_runner
from django.conf import settings

def runtests():
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True)
    failures = test_runner.run_tests(['test_app'])
    sys.exit(bool(failures))

if __name__ == '__main__':
    runtests()

This will make running tests a bit easier:

cd django_app_tests
python runtests.py

Now lets tell setuptools what it should do when you call setup.py test. Go to your setup.py file and add test_suite='django_app_tests.runtests.runtests to the setup() function.

Thats it -- now you can run your app tests with python setup.py test.


Comments

blog comments powered by Disqus