Search code examples
pythondjangodjango-testing

Media file cannot be found with self.client.get() in Python TestCase


I have an image in media folder in my project's root. I can ./manage.py runserver and access my file successfully via 127.0.0.1:8000/media/img.jpg url in browser. But the following test fails with 404!=200. Why?

class MyTestCase(TestCase):
    def test_image_shows(self):
         response = self.client.get('/media/img.jpg')
         self.assertEquals(response.status_code, 200)

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Solution

  • That's not straightforward nor elegant, but that's the best simple way I found for myself :

    1) Add a static rule in your urls.py (it's not enabled in production) :

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    

    2) Enable DEBUG for your test case (so that static rule gets enabled):

    from django.test import TestCase
    from django.test.utils import override_settings
    
    @override_settings(DEBUG=True)
    class SomeTestCase(TestCase):
        def test_something(self):
            assert self.client.get('/medias/something.jpg').status_code == 200
    

    You may also want to specify a different MEDIA_ROOT for tests not to pollute your dev MEDIA_ROOT if you write medias during your tests. An example can be found on caktus blog.