From 2d9ec4d735871b44c7a05d6e0aa3f92763f667f5 Mon Sep 17 00:00:00 2001 From: Alex Stovbur Date: Wed, 7 Mar 2018 23:20:25 +0200 Subject: [PATCH] Fixed #29188 -- Fixed ContentFile.size after a write(). --- django/core/files/base.py | 4 ++++ tests/files/tests.py | 10 ++++++++++ 2 files changed, 14 insertions(+) diff --git a/django/core/files/base.py b/django/core/files/base.py index 2c0d4904d2..fb819ed31f 100644 --- a/django/core/files/base.py +++ b/django/core/files/base.py @@ -149,6 +149,10 @@ class ContentFile(File): def close(self): pass + def write(self, data): + self.__dict__.pop('_size', None) # Clear the computed size. + return self.file.write(data) + def endswith_cr(line): """Return True if line (a text or byte string) ends with '\r'.""" diff --git a/tests/files/tests.py b/tests/files/tests.py index 3999794154..663d2d976f 100644 --- a/tests/files/tests.py +++ b/tests/files/tests.py @@ -206,6 +206,16 @@ class ContentFileTestCase(unittest.TestCase): with file.open() as f: self.assertEqual(f.read(), b'content') + def test_size_changing_after_writing(self): + """ContentFile.size changes after a write().""" + f = ContentFile('') + self.assertEqual(f.size, 0) + f.write('Test ') + f.write('string') + self.assertEqual(f.size, 11) + with f.open() as fh: + self.assertEqual(fh.read(), 'Test string') + class InMemoryUploadedFileTests(unittest.TestCase): def test_open_resets_file_to_start_and_returns_context_manager(self):