Django coverage test for URLs 0%, why?

2019-03-31 08:51发布

问题:

Using Django Nose. I have tests for my URL's but coverage is still giving me 0% for URLs, why?

python manage.py test profiles

This is my coverage:

Name                               Stmts   Miss  Cover   Missing
----------------------------------------------------------------
profiles                               0      0   100%
profiles.migrations                    0      0   100%
profiles.migrations.0001_initial       6      0   100%
profiles.models                        0      0   100%
profiles.urls                          4      4     0%   1-9
----------------------------------------------------------------
TOTAL                                 10      4    60%
----------------------------------------------------------------

This is one of my URL test...

url_tests.py

import nose.tools as noz
from django.test import TestCase
from django.core.urlresolvers import resolve, reverse

class URLsTest(TestCase):

    def test_user_list(self):
        url = reverse('api_user_list', args=[])
        noz.assert_equal(url, '/api/user/')

回答1:

Usually this has to do with coverage.py being started too late in the process. The simplest way to ensure it starts early enough is to run the test runner under coverage:

$ coverage run nosetests.py ....

One relevant detail of urls.py: it contains only code that executes when it is imported. So the entire file is executed when Django starts up and imports urls.py. This is different than most files, which define classes or functions whose bodies are executed later.