From f16a9a556fb4225f9094048614f4fcec3db7e067 Mon Sep 17 00:00:00 2001 From: lucasesposito Date: Wed, 7 Aug 2024 03:45:16 +0200 Subject: [PATCH] Fixed #35658 -- Initialized InMemoryFileNode instances with a name. --- django/core/files/storage/memory.py | 11 +++++++---- tests/file_storage/tests.py | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/django/core/files/storage/memory.py b/django/core/files/storage/memory.py index 39a8aef3aea8..22b8c62bd1a2 100644 --- a/django/core/files/storage/memory.py +++ b/django/core/files/storage/memory.py @@ -45,10 +45,9 @@ class InMemoryFileNode(ContentFile, TimingMixin): modification, and access times. """ - def __init__(self, content="", name=""): - self.file = None + def __init__(self, content="", name=None): + super().__init__(content, name) self._content_type = type(content) - self._initialize_stream() self._initialize_times() def open(self, mode): @@ -142,7 +141,11 @@ def _resolve_child(self, path_segment, create_if_missing, child_cls): if create_if_missing: self._update_accessed_time() self._update_modified_time() - return self._children.setdefault(path_segment, child_cls()) + if child_cls is InMemoryFileNode: + child = child_cls(name=path_segment) + else: + child = child_cls() + return self._children.setdefault(path_segment, child) return self._children.get(path_segment) def listdir(self): diff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py index c7ca8735210a..b486578cdbce 100644 --- a/tests/file_storage/tests.py +++ b/tests/file_storage/tests.py @@ -1024,6 +1024,23 @@ def test_stringio(self): with temp_storage.open("tests/stringio") as f: self.assertEqual(f.read(), b"content") + @override_settings( + STORAGES={ + DEFAULT_STORAGE_ALIAS: { + "BACKEND": "django.core.files.storage.InMemoryStorage" + } + } + ) + def test_create_file_field_from_another_file_field_in_memory_storage(self): + f = ContentFile("content", "file.txt") + obj = Storage.objects.create(storage_callable_default=f) + new_obj = Storage.objects.create( + storage_callable_default=obj.storage_callable_default.file + ) + storage = callable_default_storage() + with storage.open(new_obj.storage_callable_default.name) as f: + self.assertEqual(f.read(), b"content") + class FieldCallableFileStorageTests(SimpleTestCase): def setUp(self):