Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

s3: Fix newline handling for text-mode files #1352

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions storages/backends/s3.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import mimetypes
import os
import io
import posixpath
import tempfile
import threading
Expand Down Expand Up @@ -123,7 +124,6 @@ def __init__(self, name, mode, storage, buffer_size=None):
self._storage = storage
self.name = name[len(self._storage.location) :].lstrip("/")
self._mode = mode
self._force_mode = (lambda b: b) if "b" in mode else (lambda b: b.decode())
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are the changes to _force_mode necessary? It's interesting that there are no failing tests when those are moved.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the TextIOWrapper takes care of decoding the file as it's read, so this is no longer necessary

self.obj = storage.bucket.Object(name)
if "w" not in mode:
# Force early RAII-style exception if object does not exist
Expand Down Expand Up @@ -184,6 +184,8 @@ def _get_file(self):
self._file.seek(0)
if self._storage.gzip and self.obj.content_encoding == "gzip":
self._file = self._decompress_file(mode=self._mode, file=self._file)
elif "b" not in self._mode:
self._file = io.TextIOWrapper(self._file._file, encoding="utf-8")
self._closed = False
return self._file

Expand All @@ -195,12 +197,12 @@ def _set_file(self, value):
def read(self, *args, **kwargs):
if "r" not in self._mode:
raise AttributeError("File was not opened in read mode.")
return self._force_mode(super().read(*args, **kwargs))
return super().read(*args, **kwargs)

def readline(self, *args, **kwargs):
if "r" not in self._mode:
raise AttributeError("File was not opened in read mode.")
return self._force_mode(super().readline(*args, **kwargs))
return super().readline(*args, **kwargs)

def readlines(self):
return list(self)
Expand Down
67 changes: 45 additions & 22 deletions tests/test_s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from django.test import TestCase
from django.test import override_settings
from django.utils.timezone import is_aware
from moto import mock_s3
from moto import mock_aws

from storages.backends import s3
from tests.utils import NonSeekableContentFile
Expand Down Expand Up @@ -305,25 +305,6 @@ def test_storage_open_read_string(self):
self.assertEqual(content_str, "")
file.close()

def test_storage_open_readlines(self):
"""
Test readlines with file opened in "r" and "rb" modes
"""
name = "test_open_readlines_string.txt"
with io.BytesIO() as temp_file:
temp_file.write(b"line1\nline2")
file = self.storage.open(name, "r")
file._file = temp_file

content_lines = file.readlines()
self.assertEqual(content_lines, ["line1\n", "line2"])

temp_file.seek(0)
file = self.storage.open(name, "rb")
file._file = temp_file
content_lines = file.readlines()
self.assertEqual(content_lines, [b"line1\n", b"line2"])

def test_storage_open_write(self):
"""
Test opening a file in write mode
Expand Down Expand Up @@ -1059,10 +1040,10 @@ def test_reopening(self):
self.assertIsNone(f._multipart)


@mock_s3
@mock_aws
class S3StorageTestsWithMoto(TestCase):
"""
Using mock_s3 as a class decorator automatically decorates methods,
Using mock_aws as a class decorator automatically decorates methods,
but NOT classmethods or staticmethods.
"""

Expand Down Expand Up @@ -1145,6 +1126,48 @@ def test_content_type_not_detectable(self):
s3.S3Storage.default_content_type,
)

def test_storage_open_read_with_newlines(self):
"""
Test opening a file in "r" and "rb" mode with various newline characters
"""
name = "test_storage_open_read_with_newlines.txt"
with io.BytesIO() as temp_file:
temp_file.write(b"line1\nline2\r\nmore\rtext\n")
self.storage.save(name, temp_file)
file = self.storage.open(name, "r")
content_str = file.read()
file.close()
self.assertEqual(content_str, "line1\nline2\nmore\ntext\n")

with io.BytesIO() as temp_file:
temp_file.write(b"line1\nline2\r\nmore\rtext\n")
self.storage.save(name, temp_file)
file = self.storage.open(name, "rb")
content_str = file.read()
file.close()
self.assertEqual(content_str, b"line1\nline2\r\nmore\rtext\n")

def test_storage_open_readlines_with_newlines(self):
"""
Test readlines with file opened in "r" and "rb" mode with various newline characters
"""
name = "test_storage_open_readlines_with_newlines.txt"
with io.BytesIO() as temp_file:
temp_file.write(b"line1\nline2\r\nmore\rtext")
self.storage.save(name, temp_file)
file = self.storage.open(name, "r")
content_lines = file.readlines()
file.close()
self.assertEqual(content_lines, ['line1\n', 'line2\n', 'more\n', 'text'])

with io.BytesIO() as temp_file:
temp_file.write(b"line1\nline2\r\nmore\rtext")
self.storage.save(name, temp_file)
file = self.storage.open(name, "rb")
content_lines = file.readlines()
file.close()
self.assertEqual(content_lines, [b'line1\n', b'line2\r\n', b'more\r', b'text'])


class TestBackwardsNames(TestCase):
def test_importing(self):
Expand Down
9 changes: 7 additions & 2 deletions tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@ setenv =
DJANGO_SETTINGS_MODULE = tests.settings
PYTHONWARNINGS = always
PYTHONDONTWRITEBYTECODE = 1
commands = pytest --cov=storages tests/ {posargs}
commands = pytest --cov=storages {posargs}
deps =
cryptography
django3.2: django~=3.2.9
django4.1: django~=4.1.0
django4.2: django~=4.2.0
django5.0: django~=5.0b1
djangomain: https://github.com/django/django/archive/main.tar.gz
moto
moto>=5.0
pytest
pytest-cov
rsa
Expand All @@ -41,3 +41,8 @@ commands =
ruff .
black --check .
skip_install = true

[pytest]
# Default test paths to run, if no other paths are specified on the CLI
# (specify paths after a -- e.g. `tox -- tests/test_s3.py`)
testpaths = tests/
Loading