Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : testing static files

Tags:

Using the testing framework (TestCase) of Django 1.3, I would like to run some tests on static files (i.e., files not necessarily served by django itself on prod but that can be served for debug (runserver)). But if I run

self.client.get("/static/somefile.json") 

... I get a 404 error in my tests. (of course, this file is available on runserver)

Why not, but what would be the nicest way to check the presence of this json schema in my static files ? (in my case, I would also like to test this public json schema against a generated json output, so I want the content of the file)

like image 959
smad Avatar asked Aug 19 '11 14:08

smad


People also ask

Can Django serve static files in production?

During development, as long as you have DEBUG set to TRUE and you're using the staticfiles app, you can serve up static files using Django's development server. You don't even need to run the collecstatic command.

How do I access Django media files?

MEDIA_URL Setting Just below the MEDIA_ROOT setting add the following code to the end of settings.py file. Download this image and save it as python. png in the media directory. To access the file visit http://127.0.0.1:8000/media/python.png .


1 Answers

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

like image 74
Brownbay Avatar answered Oct 08 '22 15:10

Brownbay