diff --git a/src/kinto_http/client.py b/src/kinto_http/client.py index 86f6a6d..35b7914 100644 --- a/src/kinto_http/client.py +++ b/src/kinto_http/client.py @@ -923,20 +923,20 @@ def add_attachment( permissions=None, mimetype=None, ): - with open(filepath, "rb") as f: - filecontent = f.read() filename = os.path.basename(filepath) if mimetype is None: mimetype, _ = mimetypes.guess_type(filepath) - multipart = [("attachment", (filename, filecontent, mimetype))] endpoint = self._get_endpoint("attachment", id=id, bucket=bucket, collection=collection) - resp, _ = self.session.request( - "post", - endpoint, - data=json.dumps(data) if data is not None else None, - permissions=json.dumps(permissions) if permissions is not None else None, - files=multipart, - ) + + with open(filepath, "rb") as file: + resp, _ = self.session.request( + "post", + endpoint, + data=json.dumps(data) if data is not None else None, + permissions=json.dumps(permissions) if permissions is not None else None, + files=[("attachment", (filename, file, mimetype))], + ) + return resp @retry_timeout diff --git a/tests/test_client.py b/tests/test_client.py index 3f52bf3..428bb20 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -3,6 +3,7 @@ import pytest from pytest_mock.plugin import MockerFixture +from unittest.mock import patch, mock_open from kinto_http import ( BearerTokenAuth, @@ -1427,22 +1428,21 @@ def test_add_attachment_guesses_mimetype(record_setup: Client, tmp_path): client = record_setup mock_response(client.session) - p = tmp_path / "file.txt" - p.write_text("hello") - client.add_attachment( - id="abc", - bucket="a", - collection="b", - filepath=p, - ) + with patch("builtins.open", mock_open(read_data="hello")) as mock_file: + client.add_attachment( + id="abc", + bucket="a", + collection="b", + filepath="file.txt", + ) - client.session.request.assert_called_with( - "post", - "/buckets/a/collections/b/records/abc/attachment", - data=None, - permissions=None, - files=[("attachment", ("file.txt", b"hello", "text/plain"))], - ) + client.session.request.assert_called_with( + "post", + "/buckets/a/collections/b/records/abc/attachment", + data=None, + permissions=None, + files=[("attachment", ("file.txt", mock_file.return_value, "text/plain"))], + ) def test_get_permissions(client_setup: Client):