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
21 changes: 21 additions & 0 deletions tests/downloads_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,27 @@ def test_urllib_request_releases_conn_on_oversize():
resp.release_conn.assert_called_once()


@pytest.mark.parametrize(
"geturl_result, expected",
[
# request URI passed down to the connection pool, no redirect involved
("/news/news", "https://example.org/news/news"),
# raw Location header after a redirect, relative form is legal
("/section/", "https://example.org/section/"),
("https://example.com/elsewhere", "https://example.com/elsewhere"),
],
)
def test_urllib_request_resolves_relative_url(geturl_result, expected):
"regression: a relative geturl() must not reach Response.url."
resp = MagicMock(status=200)
resp.stream.return_value = iter([b"<html><body><p>ABC</p></body></html>"])
resp.geturl.return_value = geturl_result
pool = MagicMock(request=MagicMock(return_value=resp))
with patch.object(dl, "_initiate_pool", return_value=pool):
result = _send_urllib_request("https://example.org/news/news", False, False, DEFAULT_CONFIG)
assert result.url == expected


def test_response_object():
"Test if the Response class is functioning as expected."
my_html = b"<html><body><p>ABC</p></body></html>"
Expand Down
5 changes: 4 additions & 1 deletion trafilatura/downloads.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from typing import (
Any,
)
from urllib.parse import urljoin

import certifi
import urllib3
Expand Down Expand Up @@ -190,7 +191,9 @@ def _send_urllib_request(url: str, no_ssl: bool, with_headers: bool, config: Con
response.release_conn()

# necessary for standardization
resp = Response(bytes(data), response.status, response.geturl() or url)
# geturl() returns the raw Location header after a redirect and the request
# URI otherwise, both of which can be relative
resp = Response(bytes(data), response.status, urljoin(url, response.geturl() or url))
if with_headers:
resp.store_headers(response.headers)
return resp
Expand Down
Loading