Skip to content

Commit

Permalink
Fixed #19367 -- Fixed saving ContentFile in filesystem storage
Browse files Browse the repository at this point in the history
This was not working properly when ContentFile was initialized with
an unicode string.
Thanks Alexey Boriskin for the report and the test.
  • Loading branch information
claudep committed Dec 6, 2012
1 parent 553838a commit 34dcf51
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
9 changes: 6 additions & 3 deletions django/core/files/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from django.utils.encoding import smart_text
from django.core.files.utils import FileProxyMixin
from django.utils import six
from django.utils.encoding import python_2_unicode_compatible
from django.utils.encoding import force_bytes, python_2_unicode_compatible

@python_2_unicode_compatible
class File(FileProxyMixin):
Expand Down Expand Up @@ -134,8 +134,11 @@ class ContentFile(File):
A File-like object that takes just raw content, rather than an actual file.
"""
def __init__(self, content, name=None):
content = content or b''
stream_class = StringIO if isinstance(content, six.text_type) else BytesIO
if six.PY3:
stream_class = StringIO if isinstance(content, six.text_type) else BytesIO
else:
stream_class = BytesIO
content = force_bytes(content)
super(ContentFile, self).__init__(stream_class(content), name=name)
self.size = len(content)

Expand Down
20 changes: 19 additions & 1 deletion tests/regressiontests/file_storage/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,13 @@ def test_multiple_calls(self):

class ContentFileTestCase(unittest.TestCase):

def setUp(self):
self.storage_dir = tempfile.mkdtemp()
self.storage = FileSystemStorage(self.storage_dir)

def tearDown(self):
shutil.rmtree(self.storage_dir)

def test_content_file_default_name(self):
self.assertEqual(ContentFile(b"content").name, None)

Expand All @@ -576,7 +583,18 @@ def test_content_file_input_type(self):
retrieved content is of the same type.
"""
self.assertTrue(isinstance(ContentFile(b"content").read(), bytes))
self.assertTrue(isinstance(ContentFile("español").read(), six.text_type))
if six.PY3:
self.assertTrue(isinstance(ContentFile("español").read(), six.text_type))
else:
self.assertTrue(isinstance(ContentFile("español").read(), bytes))

def test_content_saving(self):
"""
Test that ContentFile can be saved correctly with the filesystem storage,
both if it was initialized with string or unicode content"""
self.storage.save('bytes.txt', ContentFile(b"content"))
self.storage.save('unicode.txt', ContentFile("español"))


class NoNameFileTestCase(unittest.TestCase):
"""
Expand Down

0 comments on commit 34dcf51

Please sign in to comment.