[Django]-Django : testing static files

14👍

Another method which I find slightly easier as there’s less to type/import:

from django.contrib.staticfiles import finders

result = finders.find('css/base.css')

If the static file was found, it will return the full path to the file. If not found, it will return None

Source: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#finders-module


As of Django 1.7+, you can also find out/test where Django is looking through the finders module:

searched_locations = finders.searched_locations

In addition to the SimpleTestCase.assertTemplateUsed(response, template_name, msg_prefix='') assertion provided by Django, you could also make use of:
response.templates from the Response class to get a list of templates that were used to render the response.

Source: https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.Response.templates

9👍

how about this:

from django.contrib.staticfiles import finders
from django.contrib.staticfiles.storage import staticfiles_storage

absolute_path = finders.find('somefile.json')
assert staticfiles_storage.exists(absolute_path)

This uses the staticfiles finders to find a file called ‘somefile.json’ and then checks if the file actually exists on the storage you configured?

👤ojii

7👍

You could use class testing.StaticLiveServerTestCase from the staticfiles module:
http://django.readthedocs.org/en/latest/ref/contrib/staticfiles.html#specialized-test-case-to-support-live-testing

4👍

As isbadawi comments, the test server always runs with DEBUG = False. So you can’t rely on the DEBUG handling of static files, you need an explicit production-like way of handling them for the test to find them. You could have a special section in your urls.py that turns on the development serve() for when you run test:

if 'test' in sys.argv:
    static_url = re.escape(settings.STATIC_URL.lstrip('/'))
    urlpatterns += patterns('',
        url(r'^%s(?P<path>.*)$' % static_url, 'django.views.static.serve', {
            'document_root': settings.STATIC_ROOT,
        }),
    )

2👍

0👍

FWIW, for significant projects, I would offer the opinion that testing static files might be outside the scope of pure Django testing since Django’s runserver is not intended to be used for serving static files. This kind of testing would usually be reserved for integration tests that involves testing your deployment more so than the development code.

👤Harlin

Leave a comment