dnscms: version image URLs by file hash so media can be cached as immutable
dnscms / ci (push) Successful in 1m10s
web / ci (push) Successful in 2m38s

This commit is contained in:
ponas committed 2026-10-15 01:43:10 +02:00
1 parent fb1453b419
commit cff6376129
4 files changed
+122 -5

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
import importlib
from django.apps import apps
from images.models import CustomImage
from tests.conftest import CustomImageFactory
backfill = importlib.import_module(
"images.migrations.0006_backfill_file_hash_and_size"
).backfill_file_hash_and_size
IMAGES_QUERY = "query { images { id url } }"
def test_graphql_image_url_is_versioned_by_file_hash(db, graphql_post):
image = CustomImageFactory()
image.file_hash = "0123456789abcdef0123456789abcdef01234567"
image.save(update_fields=["file_hash"])
response, body = graphql_post(IMAGES_QUERY)
assert response.status_code == 200
assert "errors" not in body, body
[data] = body["data"]["images"]
assert data["url"].startswith("http")
assert data["url"].endswith(f"{image.file.url}?v=01234567")
def test_graphql_image_url_without_file_hash_is_unversioned(db, graphql_post):
image = CustomImageFactory()
CustomImage.objects.filter(pk=image.pk).update(file_hash="")
response, body = graphql_post(IMAGES_QUERY)
assert "errors" not in body, body
[data] = body["data"]["images"]
assert data["url"].endswith(image.file.url)
def test_backfill_sets_file_hash_and_size(db):
image = CustomImageFactory()
CustomImage.objects.filter(pk=image.pk).update(file_hash="", file_size=None)
backfill(apps, None)
image.refresh_from_db()
assert len(image.file_hash) == 40
assert image.file_size == image.file.size
def test_backfill_skips_images_whose_file_is_missing(db):
image = CustomImageFactory()
CustomImage.objects.filter(pk=image.pk).update(file_hash="", file_size=None)
image.file.storage.delete(image.file.name)
backfill(apps, None)
# refresh_from_db() would read the missing file for its dimensions
fields = CustomImage.objects.filter(pk=image.pk).values("file_hash", "file_size")
assert fields.get() == {"file_hash": "", "file_size": None}