tawmas
tawmas

Reputation: 7833

How do I group unit tests in Django at a higher granularity than the app?

In a Django project, unit test are usually organized by app, with Django providing a facility to run all of the tests, the tests for a single app, a single test case, or a single test method.

Yet, I find that test cases in a single application usually belong to separate logical groups or clusters, and it would be often useful to be able to only run a single group of tests. Imagine, for example:

I searched around. But while it is relatively straightforward to split your tests in multiple files (see for example these two questions), there doesn't seem to be a straightforward way to run the test groups separately.

So, am I missing something? What is the secret sauce to group tests?

Upvotes: 4

Views: 2014

Answers (2)

Zulu
Zulu

Reputation: 9275

For Django < 1.6
Personaly I do :

You have a init file :

myapp/tests/__init__.py :

from test1 import *
from test2 import *

def suite():
    import unittest
    #import doctest # If you want to use doctest

    TEST_CASES = ( 
     'sendim.tests.test1',
     'sendim.tests.test2',
    )   
    suite = unittest.TestSuite()

    #suite.addTest(doctest.DocTestSuite(object)) # object which have doctest
    for t in TEST_CASES :
        suite.addTest(unittest.TestLoader().loadTestsFromModule(__import__(t, globals(), locals(), fromlist=["*"])))
    return suite

And for example a testcase in a file named 'TestCase1' :

myapp/tests/test1.py :

from django.utils import unittest

class TestCase1(unittest.TestCase) :
    # Your testcase

If you launch ./manage.py test myapp, it will lauch every testcases.
Else if you launch `./manage.py test myapp.TestCase1, it will execute only this one.

Upvotes: 2

Garethr
Garethr

Reputation: 1977

It's worth looking at the nose test framework for python for one approach to this problem.

Specifically you can tag tests or set attributes on them. Then only run a subset of tests (across an app or your whole project) tagged with a given tag or tags.

https://nose.readthedocs.org/en/latest/plugins/attrib.html?highlight=tags

Note that nose extends unittest, so you're existing django unittest suite will likely already run with the nose runner.

Upvotes: 2

Related Questions