Search code examples
djangounit-testing

How to spread django unit tests over multiple files?


  • I have a python-django application
  • I'm using the unit testing framework
  • The tests are arranged in the file "tests.py" in the module directory
  • I'm running the tests via ./manage.py test app

Now..

  • The tests.py file is getting rather large/complex/messy
  • I'd like to break tests.py up into smaller collections of tests...

How?


Solution

  • The behavior has changed in Django 1.6, so there is no longer a need to create a package. Just name your files test*.py.

    From Django 1.7 documentation

    When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.TestCase) in any file whose name begins with test, automatically build a test suite out of those test cases, and run that suite.

    From Django 1.6 documentation,

    Test discovery is based on the unittest module’s built-in test discovery. By default, this will discover tests in any file named “test*.py” under the current working directory.

    Previous behavior, from Django 1.5 documentation:

    When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.TestCase) in models.py and tests.py, automatically build a test suite out of those test cases, and run that suite.

    There is a second way to define the test suite for a module: if you define a function called suite() in either models.py or tests.py, the Django test runner will use that function to construct the test suite for that module. This follows the suggested organization for unit tests. See the Python documentation for more details on how to construct a complex test suite.