Is it possible to test successful loading of static page components in Django automatic test?
For example, using django test client, besides testing the client.get('x').status_code
to be 200, I want to test if all page's static resources (linked css and js files) are successfully loaded.
If its not possible using client
, Is there a plugin or suplementary test system, e.g. Selenium, to enable such type of tests?
Configuring static filesMake sure that django.contrib.staticfiles is included in your INSTALLED_APPS . In your templates, use the static template tag to build the URL for the given relative path using the configured STATICFILES_STORAGE . Store your static files in a folder called static in your app.
Django caches (or rather the browsers cache) the static files indefinitely during development. Now even after the files are changed, the browsers will serve the stale file from the cache.
Static Files in ProductionUse a web server like Nginx to route traffic destined for your static files directly to the static root (configured via STATIC_ROOT ) Use WhiteNoise to serve up static files directly from the WSGI or ASGI web application server.
collectstatic. Collects the static files into STATIC_ROOT . Duplicate file names are by default resolved in a similar way to how template resolution works: the file that is first found in one of the specified locations will be used. If you're confused, the findstatic command can help show you which files are found.
I guess you want to find out if django's staticfile finder is able to find your static resources.
Consider your app name is my_app
. You have a folder called static
inside it. You again have a folder called my_app
inside it which contains your static resource, let's say some image named 'test.jpg'.
myapp
|-- __init__.py
`-- models.py
`-- static
`-- myapp
`-- test.jpg
from django.contrib.staticfiles import finders
from django.contrib.staticfiles.storage import staticfiles_storage
class TestStaticFiles(TestCase):
"""Check if app contains required static files"""
def test_images(self):
abs_path = finders.find('myapp/test.jpg')
self.assertTrue(staticfiles_storage.exists(abs_path))
finders
looks inside static/
subdirectory of all apps to find the static resource.
I just found myself with a very similar issue, although I wanted to verify if the file was included in the page rather than check it was loaded, because I include it selectively.
To do so, I simply checked using assertContains:
def test_static_file_included(self):
response = self.client.get(reverse('my-view'))
self.assertContains(response, 'staticfilename.js')
Keep in mind that staticfilename.js
could be included somewhere else in the page.
assertContains
will check if the response status_code is ok, then check if the search str is included in response.content
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With