Code

Ticket #4501: 4501-coverage.diff

File 4501-coverage.diff, 2.7 KB (added by ericholscher, 5 years ago)

Initial patch

Line 
1diff --git a/django/core/management/commands/test.py b/django/core/management/commands/test.py
2index 8ebf3da..b57a2f0 100644
3--- a/django/core/management/commands/test.py
4+++ b/django/core/management/commands/test.py
5@@ -6,6 +6,8 @@ class Command(BaseCommand):
6     option_list = BaseCommand.option_list + (
7         make_option('--noinput', action='store_false', dest='interactive', default=True,
8             help='Tells Django to NOT prompt the user for input of any kind.'),
9+        make_option('--coverage', action='store_true', dest='coverage', default=False,
10+            help='Tells Django to run coverage analysis on your test modules.'),
11     )
12     help = 'Runs the test suite for the specified applications, or the entire site if no apps are specified.'
13     args = '[appname ...]'
14@@ -18,8 +20,48 @@ class Command(BaseCommand):
15 
16         verbosity = int(options.get('verbosity', 1))
17         interactive = options.get('interactive', True)
18+        use_coverage = options.get('coverage', False)
19         test_runner = get_runner(settings)
20 
21+
22+        if use_coverage:
23+            try:
24+                import coverage
25+                if verbosity > 1:
26+                    print "Running test runner with coverage."
27+                #coverage.use_cache(0)
28+                coverage.start()
29+            except:
30+                if verbosity > 0:
31+                    print "coverage.py module is not available."
32+                use_coverage = False
33+
34         failures = test_runner(test_labels, verbosity=verbosity, interactive=interactive)
35+
36         if failures:
37             sys.exit(failures)
38+
39+        #We only want coverage when our tests are passing.
40+        if use_coverage:
41+            coverage.stop()
42+            coverage_models = []
43+            if test_labels:
44+                for label in test_labels:
45+                    if '.' in label:
46+                        #Test the app, don't know if we really want coverage here.
47+                        label = label.split('.')[0]
48+                    coverage_models.append(__import__(label, globals(), locals(), ['']))
49+            else:
50+                from django.db.models.loading import get_apps
51+                for app in get_apps():
52+                    if app.__name__.find('django.contrib') == -1:
53+                        coverage_models.append(app)
54+
55+
56+            print '---------------------------------------------------------------'
57+            print ' Unit Test Code Coverage Results'
58+            print '---------------------------------------------------------------'
59+
60+            coverage.report(coverage_models, show_missing=1)
61+
62+            print '---------------------------------------------------------------'