Skip to content
Merged
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
1 change: 1 addition & 0 deletions python/changelog.d/864.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Data import and other file upload and download errors now include the server's error message. File attachment, artifact, and test result uploads raise `requests.HTTPError` instead of `Exception`.
Comment thread
alexluck-sift marked this conversation as resolved.
Resolved
8 changes: 3 additions & 5 deletions python/lib/sift_client/_internal/low_level_wrappers/upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from sift_client._internal.low_level_wrappers.base import LowLevelClientBase
from sift_client._internal.util.executor import run_sync_function
from sift_client._internal.util.http import raise_for_status
from sift_client.transport import WithRestClient

if TYPE_CHECKING:
Expand Down Expand Up @@ -88,7 +89,7 @@ async def upload_attachment(
Raises:
ValueError: If the path doesn't point to a regular file, or a file object has no
file_name.
Exception: If the upload fails.
requests.HTTPError: If the upload fails.
"""
upload: Path | BinaryIO
if isinstance(source, (str, Path)):
Expand Down Expand Up @@ -179,10 +180,7 @@ def _upload_file_sync(
},
)

if response.status_code != 200:
raise Exception(
f"Request failed with status code {response.status_code} ({response.reason})."
)
raise_for_status(response)
Comment thread
alexluck-sift marked this conversation as resolved.
Resolved

response_data = response.json()
return response_data.get("remoteFile", {}).get("remoteFileId")
Expand Down
9 changes: 5 additions & 4 deletions python/lib/sift_client/_internal/util/file.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from typing import TYPE_CHECKING

import sift_client as _sift_client_module
from sift_client._internal.util.http import raise_for_status
from sift_client._internal.util.progress import alive_bar
from sift_client.errors import SiftWarning

Expand Down Expand Up @@ -64,7 +65,7 @@ def upload_file(
The parsed JSON response from the server.

Raises:
ValueError: If the upload request fails.
requests.HTTPError: If the upload request fails.
"""
file_size = file_path.stat().st_size

Expand All @@ -84,7 +85,7 @@ def upload_file(
data=wrapped,
headers={"Content-Disposition": f'attachment; filename="{file_path.name}"'},
)
response.raise_for_status()
raise_for_status(response)
return response.json()


Expand Down Expand Up @@ -126,7 +127,7 @@ def download_file(
if extra_headers:
headers.update(extra_headers)
with rest_client.get(signed_url, stream=True, headers=headers) as response:
response.raise_for_status()
raise_for_status(response)
total_bytes = int(response.headers.get("Content-Length", 0)) or None
with alive_bar(
total_bytes,
Expand Down Expand Up @@ -161,7 +162,7 @@ def read_url_bytes(signed_url: str, *, rest_client: RestClient) -> bytes:
# Presigned URLs carry their own auth, so strip the session's Authorization header.
headers: dict[str, str | None] = {"Authorization": None}
with rest_client.get(signed_url, headers=headers) as response:
response.raise_for_status()
raise_for_status(response)
return response.content


Expand Down
23 changes: 23 additions & 0 deletions python/lib/sift_client/_internal/util/http.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from __future__ import annotations

from typing import TYPE_CHECKING

from requests import HTTPError

if TYPE_CHECKING:
from requests import Response


def raise_for_status(response: Response) -> None:
"""Like ``Response.raise_for_status``, with the server's response body in the message.

Raises:
requests.HTTPError: If the response has a 4xx or 5xx status.
"""
try:
response.raise_for_status()
except HTTPError as error:
body = response.text.strip()
if body:
raise HTTPError(f"{error}\nServer response: {body}", response=response) from error
raise
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from unittest.mock import MagicMock, patch

import pytest
from requests import HTTPError, Request, Response

from sift_client._internal.low_level_wrappers.upload import UploadLowLevelClient

Expand Down Expand Up @@ -114,3 +115,26 @@ def test_posts_file_object_without_opening_a_path(self):

assert remote_file_id == "rf1"
client._rest_client.post.assert_called_once()

def test_upload_error_includes_server_body(self):
response = Response()
response.status_code, response.reason = 400, "Bad Request"
response.url = "https://example.test/api/v0/remote-files/upload"
response.request = Request("POST", response.url).prepare()
response._content = b"invalid entity_type"
client = UploadLowLevelClient.__new__(UploadLowLevelClient)
client._rest_client = MagicMock()
client._rest_client.post.return_value = response

with pytest.raises(HTTPError, match="Server response: invalid entity_type"):
client._upload_file_sync(
io.BytesIO(b"x"),
"t.csv",
"text/csv",
None,
"v1",
"artifact_versions",
None,
None,
None,
)
40 changes: 39 additions & 1 deletion python/lib/sift_client/_tests/_internal/util/test_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,45 @@

from unittest.mock import MagicMock

from sift_client._internal.util.file import download_file, read_url_bytes
import pytest
from requests import HTTPError, Request, Response

from sift_client._internal.util.file import download_file, read_url_bytes, upload_file


@pytest.fixture
def upload_request(tmp_path):
path = tmp_path / "data.csv"
path.write_text("time,value\n11/02/2026,1\n")
response = Response()
response.status_code = 400
response.reason = "Bad Request"
response.url = "https://example.test/api/v2/data-imports:upload/import-id"
response.request = Request("POST", response.url).prepare()
response.encoding = "utf-8"
rest_client = MagicMock()
rest_client.post.return_value = response
return path, rest_client, response


class TestUploadFile:
def test_http_error_includes_server_body(self, upload_request):
path, rest_client, response = upload_request
response._content = b"failed to parse row 20: parsing time"

with pytest.raises(HTTPError, match="Server response: failed to parse row 20"):
upload_file(response.url, path, rest_client=rest_client)

def test_success_returns_parsed_json(self, upload_request):
path, rest_client, response = upload_request
response.status_code = 200
response.reason = "OK"
response._content = b'{"jobId":"job-id"}'

result = upload_file(response.url, path, rest_client=rest_client)

assert result == {"jobId": "job-id"}
rest_client.post.assert_called_once()


class _FakeResponse:
Expand Down
61 changes: 61 additions & 0 deletions python/lib/sift_client/_tests/_internal/util/test_http.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
from __future__ import annotations

import pytest
from requests import HTTPError, Request, Response

from sift_client._internal.util.http import raise_for_status

URL = "https://example.test/api/v2/data-imports:upload/import-id"


def _response(status_code: int, reason: str, body: bytes) -> Response:
response = Response()
response.status_code = status_code
response.reason = reason
response.url = URL
response.request = Request("POST", URL).prepare()
response.encoding = "utf-8"
response._content = body
return response


class TestRaiseForStatus:
@pytest.mark.parametrize(
("status_code", "reason", "body"),
[
(
400,
"Bad Request",
'failed to parse row 20: parsing time "10-29-2026 16:53:45" as '
'"2006-01-02 15:04:05": cannot parse "10-29-2026 16:53:45" as "2006"',
),
(500, "Internal Server Error", "upload failed\n"),
(502, "Bad Gateway", "<html>Bad Gateway</html>"),
],
)
def test_error_includes_server_body(self, status_code, reason, body):
response = _response(status_code, reason, body.encode("utf-8"))

with pytest.raises(HTTPError) as exc_info:
raise_for_status(response)

message = str(exc_info.value)
assert body.strip() in message
assert str(status_code) in message
assert reason in message
assert URL in message
assert exc_info.value.response is response
assert exc_info.value.request is response.request

@pytest.mark.parametrize("body", [b"", b" \n\t"])
def test_empty_body_preserves_http_error(self, body):
response = _response(400, "Bad Request", body)

with pytest.raises(HTTPError) as exc_info:
raise_for_status(response)

assert str(exc_info.value) == f"400 Client Error: Bad Request for url: {URL}"
assert exc_info.value.response is response

def test_success_does_not_raise(self):
raise_for_status(_response(200, "OK", b'{"jobId":"job-id"}'))
Loading