Search code examples
pythondjangoautomated-testsdjango-testing

Django: test successful loading of static files


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?


Solution

  • 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.