Fix image saving on backends that expect a rewound file pointer

Fixes #10046
pull/10078/head
Matt Westcott 2023-02-08 19:16:46 +00:00 zatwierdzone przez Matt Westcott
rodzic 5d90ae6c82
commit 13b0a50b25
3 zmienionych plików z 37 dodań i 2 usunięć

Wyświetl plik

@ -214,6 +214,8 @@ class WagtailImageFieldFile(models.fields.files.ImageFieldFile):
finally:
if close:
self.close()
else:
self.seek(0)
class WagtailImageField(models.ImageField):

Wyświetl plik

@ -5,6 +5,7 @@
# - Calling .path on the storage or image file raises NotImplementedError
# - File.open() after the file has been closed raises an error
# - File.size exceptions raise DummyExternalStorageError
# - Storage._save() fails loudly if the content file's pointer is not at the start
from django.core.files.base import File
from django.core.files.storage import FileSystemStorage, Storage
@ -26,11 +27,16 @@ class DummyExternalStorage(Storage):
# File object
return DummyExternalStorageFile(open(self.wrapped.path(name), mode))
# Wrap all other functions
def _save(self, name, content):
file_pos = content.tell()
if file_pos != 0:
raise ValueError(
"Content file pointer should be at 0 - got %d instead" % file_pos
)
return self.wrapped._save(name, content)
# Wrap all other functions
def delete(self, name):
self.wrapped.delete(name)

Wyświetl plik

@ -1,9 +1,11 @@
import json
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from wagtail.admin.tests.test_contentstate import content_state_equal
from wagtail.models import PAGE_MODEL_CLASSES, Page, Site
from wagtail.test.dummy_external_storage import DummyExternalStorage
from wagtail.test.testapp.models import (
BusinessChild,
BusinessIndex,
@ -429,3 +431,28 @@ class TestFormDataHelpers(TestCase):
def test_rich_text_with_alternative_editor(self):
result = rich_text("<h2>title</h2><p>para</p>", editor="custom")
self.assertEqual(result, "<h2>title</h2><p>para</p>")
class TestDummyExternalStorage(WagtailTestUtils, TestCase):
def test_save_with_incorrect_file_object_position(self):
"""
Test that DummyExternalStorage correctly warns about attempts
to write files that are not rewound to the start
"""
# This is a 1x1 black png
png = (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00"
b"\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00"
b"\x1f\x15\xc4\x89\x00\x00\x00\rIDATx\x9cc````"
b"\x00\x00\x00\x05\x00\x01\xa5\xf6E@\x00\x00"
b"\x00\x00IEND\xaeB`\x82"
)
simple_png = SimpleUploadedFile(
name="test.png", content=png, content_type="image/png"
)
simple_png.read()
with self.assertRaisesMessage(
ValueError,
"Content file pointer should be at 0 - got 70 instead",
):
DummyExternalStorage().save("test.png", simple_png)