Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 9th, 2012  |  syntax: None  |  size: 1.92 KB  |  hits: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. """
  2. An alternative Django ``TEST_RUNNER`` which uses unittest2 test discovery from
  3. a base path specified in settings, rather than requiring all tests to be in
  4. ``tests`` module of an app.
  5.  
  6. If you just run ``./manage.py test``, it'll discover and run all tests
  7. underneath the ``TEST_DISCOVERY_ROOT`` setting (a path). If you run
  8. ``./manage.py test full.dotted.path.to.test_module``, it'll run the tests in
  9. that module (you can also pass multiple modules).
  10.  
  11. And (new in this updated version), if you give it a single dotted path to a
  12. package, and that package does not itself directly contain any tests, it'll do
  13. test discovery in all sub-modules of that package.
  14.  
  15. This code doesn't modify the default unittest2 test discovery behavior, which
  16. only searches for tests in files named "test*.py".
  17.  
  18. """
  19. from django.conf import settings
  20. from django.test import TestCase
  21. from django.test.simple import DjangoTestSuiteRunner, reorder_suite
  22. from django.utils.importlib import import_module
  23. from django.utils.unittest.loader import defaultTestLoader
  24.  
  25.  
  26.  
  27. class DiscoveryRunner(DjangoTestSuiteRunner):
  28.     """A test suite runner that uses unittest2 test discovery."""
  29.     def build_suite(self, test_labels, extra_tests=None, **kwargs):
  30.         suite = None
  31.         discovery_root = settings.TEST_DISCOVERY_ROOT
  32.  
  33.         if test_labels:
  34.             suite = defaultTestLoader.loadTestsFromNames(test_labels)
  35.             # if single named module has no tests, do discovery within it
  36.             if not suite.countTestCases() and len(test_labels) == 1:
  37.                 suite = None
  38.                 discovery_root = import_module(test_labels[0]).__path__[0]
  39.  
  40.         if suite is None:
  41.             suite = defaultTestLoader.discover(
  42.                 discovery_root,
  43.                 top_level_dir=settings.BASE_PATH,
  44.                 )
  45.  
  46.         if extra_tests:
  47.             for test in extra_tests:
  48.                 suite.addTest(test)
  49.  
  50.         return reorder_suite(suite, (TestCase,))