Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,16 @@ def seek(self, offset: int, whence: int = io.SEEK_SET) -> int:
"""
current_position = self._position

# Same rules as io.BytesIO: a negative absolute position is an error, and a relative seek
# stops at the start of the object, so S3 never receives a negative Range
if whence == io.SEEK_SET:
if offset < 0:
raise ValueError(f"negative seek value {offset}")
self._position = offset
elif whence == io.SEEK_CUR:
self._position += offset
self._position = max(0, self._position + offset)
elif whence == io.SEEK_END:
self._position = self.size + offset
self._position = max(0, self.size + offset)
else:
raise ValueError(f"invalid whence ({whence}, should be {io.SEEK_SET}, {io.SEEK_CUR}, {io.SEEK_END})")

Expand Down
39 changes: 39 additions & 0 deletions tests/functional/streaming/_boto3/test_s3_seekable_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,3 +335,42 @@ def test_truncate(s3_seekable_obj):
def test_write(s3_seekable_obj):
with pytest.raises(NotImplementedError):
s3_seekable_obj.write(b"data")


def test_seek_set_negative_offset_raises(s3_client):
# GIVEN an S3Object at the start of the object
obj = S3Object(bucket="bucket", key="key", boto3_client=s3_client)

# WHEN seeking to a negative absolute position
# THEN it raises like a regular file and keeps the current position
with pytest.raises(ValueError, match="negative seek value -5"):
obj.seek(-5, io.SEEK_SET)
assert obj.tell() == 0


def test_seek_cur_before_start_stops_at_zero(s3_client):
# GIVEN an S3Object positioned at byte 10
obj = S3Object(bucket="bucket", key="key", boto3_client=s3_client)
obj.seek(10, io.SEEK_SET)

# WHEN seeking backwards past the start of the object
# THEN the position stops at 0, like a regular file
assert obj.seek(-20, io.SEEK_CUR) == 0
assert obj.tell() == 0


def test_seek_end_before_start_reads_from_zero(s3_client, s3_client_stub):
# GIVEN a 10-byte object
obj = S3Object(bucket="bucket", key="key", boto3_client=s3_client)
s3_client_stub.add_response("head_object", {"ContentLength": 10})
s3_client_stub.add_response(
"get_object",
{"Body": PowertoolsStreamingBody(raw_stream=io.BytesIO(b"0123456789"), content_length=10)},
{"Bucket": "bucket", "Key": "key", "Range": "bytes=0-"},
)

# WHEN seeking further back from the end than the object is long
# THEN the position stops at 0 and the next read asks S3 for the object from the start
assert obj.seek(-20, io.SEEK_END) == 0
assert obj.read() == b"0123456789"
s3_client_stub.assert_no_pending_responses()