mgalgs
mgalgs

Reputation: 16739

How to serve InMemoryStorage media files during Django tests

I have some Selenium-based integration tests (subclassed under django.contrib.staticfiles.testing.StaticLiveServerTestCase) for my Django app that require a functioning user-uploaded media configuration. I've been using S3 storage (django_s3_storage.storage.S3Storage from etianen/django-s3-storage) and that works just fine, but it incurs S3 costs each time I run my tests, plus the network overhead of going out to S3 is a lot during some of my media-heavy tests.

The newly added (in Django 4.2) InMemoryStorage solves both of these problems (S3 costs and overhead) perfectly, but I can't get the test server to actually serve the uploaded media files. I've added:

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

to my urlpatterns.py, but that has no effect since Django tests are always run with DEBUG=False.

But even if I force it in to my urlpatterns by inlining the relevant portion of django.conf.urls.static.static like so:

import re
from django.views.static import serve

urlpatterns += [
    re_path(
        r"^%s(?P<path>.*)$" % re.escape(settings.MEDIA_URL.lstrip("/")),
        serve,
        kwargs={"document_root": settings.MEDIA_ROOT},
    ),
]

it still doesn't work since the serve function looks like it's not storage-aware; it only works with media files on the filesystem.

The result is that my media files all return 404s when my Selenium browser requests them.

Is there a storage-aware equivalent to django.views.static.serve that I can use to serve my InMemoryStorage files during testing?

Upvotes: 1

Views: 459

Answers (0)

Related Questions