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
59 changes: 17 additions & 42 deletions mindee/input/url_input_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
from mindee.error.mindee_error import MindeeSourceError
from mindee.input.bytes_input import BytesInput
from mindee.logger import logger
from mindee.parsing.common.string_dict import StringDict


class URLInputSource:
Expand Down Expand Up @@ -70,11 +69,7 @@ def __fetch_file_content(
headers["Authorization"] = f"Bearer {token}"
auth = None if not username or not password else (username, password)

response = URLInputSource.__make_request(
self.url, auth, headers, 0, max_redirects=max_redirects
)

return response
return URLInputSource.__make_request(self.url, auth, headers, max_redirects)

def save_to_file(
self,
Expand Down Expand Up @@ -188,55 +183,35 @@ def __fill_filename(self, filename=None) -> str:
return filename

@staticmethod
def __make_request(
url,
auth,
headers,
redirects,
max_redirects,
http_client: httpx.Client | None = None,
) -> bytes:
def __make_request(url, auth, headers, max_redirects) -> bytes:
"""
Makes an HTTP request to the given URL, while following redirections.

:param url: The URL to request.
:param auth: Authentication tuple (username, password).
:param headers: Headers for the request.
:param redirects: Current number of redirects.
:param max_redirects: Maximum number of redirects to follow.
:return: The content of the response.
:raises MindeeSourceError: If max redirects are exceeded or the request fails.
"""
get_kwargs: StringDict = {
"headers": headers,
"timeout": 120,
"auth": auth,
"follow_redirects": True,
}
if http_client is None:
result = httpx.get(url, **get_kwargs)
else:
result = http_client.get(url, **get_kwargs)
if 299 < result.status_code < 400:
if redirects == max_redirects:
raise MindeeSourceError(
f"Can't reach URL after {redirects} out of {max_redirects} "
f"redirects, "
f"aborting operation."
with httpx.Client(max_redirects=max_redirects) as client:
try:
result = client.get(
url,
headers=headers,
auth=auth,
timeout=120,
follow_redirects=True,
)
return URLInputSource.__make_request(
result.headers["Location"],
auth,
headers,
redirects + 1,
max_redirects,
http_client,
)
except httpx.TooManyRedirects as exc:
raise MindeeSourceError(
f"Can't reach URL after {max_redirects} redirects, "
"aborting operation."
) from exc

if result.status_code >= 400 or result.status_code < 200:
if result.status_code >= 300 or result.status_code < 200:
raise MindeeSourceError(
f"Couldn't retrieve file from server, error code {result.status_code}."
)
if http_client is not None and not http_client.is_closed:
http_client.close()

return result.content
31 changes: 31 additions & 0 deletions tests/v1/input/test_url_input_source.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import pytest
import respx

from mindee.error.mindee_error import MindeeSourceError
from mindee.input.url_input_source import URLInputSource
Expand All @@ -17,3 +18,33 @@ def test_rejects_ftp():
def test_accepts_https():
input_source = URLInputSource("https://example.com/file.pdf")
assert input_source.url


def _mock_redirects(router: respx.MockRouter, count: int) -> None:
for index in range(count):
router.get(f"https://example.com/{index}").respond(
302, headers={"Location": f"/{index + 1}"}
)
router.get(f"https://example.com/{count}").respond(200, content=b"content")


def test_follows_redirects_up_to_the_limit(tmp_path):
source = URLInputSource("https://example.com/0")
with respx.mock() as router:
_mock_redirects(router, 3)

path = source.save_to_file(tmp_path, filename="file.pdf", max_redirects=3)

assert path.read_bytes() == b"content"


@pytest.mark.parametrize(("redirects", "max_redirects"), [(1, 0), (4, 3)])
def test_rejects_too_many_redirects(tmp_path, redirects, max_redirects):
source = URLInputSource("https://example.com/0")
with respx.mock(assert_all_called=False) as router:
_mock_redirects(router, redirects)

with pytest.raises(MindeeSourceError, match="redirects"):
source.save_to_file(
tmp_path, filename="file.pdf", max_redirects=max_redirects
)