views:

102

answers:

2

Few times while browsing tests dir in various Django apps I stumbled across models.py and settings.py files (in django-tagging for example).

But there's no code to be found that syncs test models or applies custom test settings - but tests make use of them just as if django would auto-magically load them. However if I try to run django-tagging's tests: manage.py test tagging, it doesn't do even a single test.

This is exactly what I need right now to test my app, but don't really know how.

So, how does it work?

A: 

You mean, "How do I write unit tests in Django?" Check the documentation on testing.

When I've done it, I wrote unit tests in a test/ subdirectory. Make sure the directory has an empty __init__.py file. You may also need a models.py file. Add unit tests that derive from unittest.TestCase (in module unittest). Add the module 'xxxx.test' to your INSTALLED_APPS in settings.py (where 'xxxx' is the base name of your application).

Here's some sample code of mine to get you started:

#!/usr/bin/env python
# http://docs.djangoproject.com/en/dev/topics/testing/

from sys import stderr
import unittest
from django.test.client import Client
from expenses.etl.loader import load_all, load_init

class TestCase(unittest.TestCase):
    def setUp(self):
        print "setUp"

    def testLoading(self):
        print "Calling load_init()"
        load_init()
        print "Calling load_all()"
        load_all()
        print "Done"

if __name__ == '__main__':
    unittest.main()

If you mean, "How do I get data loaded into my unit tests?", then use fixtures, described on the same documentation page.

hughdbrown
No, not really.The thing is, my notification app binds with external recipient model (according to my app's RECIPIENT_MODEL setting) and I would like to test it independently of other apps. To do that I need some kind of placeholder model for tests.
kurczak
So your question is closer to, "How do unit tests work in django-tagging, because I want mine to run like that?"
hughdbrown
Yes, more like it.
kurczak
+1  A: 

If you want to run the tests in django-tagging, you can try:

django-admin.py test --settings=tagging.tests.settings

Basically, it uses doctests which are in the tests.py file inside the tests package/directory. The tests use the settings file in that same directory (and specified in the command line to django-admin). For more information see the django documentation on writing doctests.

ars
So simple, yet so useful. I didn't know about the `--settings` parameter. Thank you.
kurczak
You're welcome; glad to help. :)
ars