aboutsummaryrefslogtreecommitdiff
path: root/tests/tasks
diff options
context:
space:
mode:
authorDennis Fink2026-11-14 19:43:28 +0100
committerDennis Fink2026-11-14 19:43:28 +0100
commitc74feda222745ab7cca8993df83d9ea5f9d07e5b (patch)
treeacc7bf9bd7223f9d685d6c2954c5c90d7a9e36f0 /tests/tasks
parente52e554e2d033dd5ef8397617644e90e354f9560 (diff)
downloadwebmentions-ssg-c74feda222745ab7cca8993df83d9ea5f9d07e5b.tar.gz
webmentions-ssg-c74feda222745ab7cca8993df83d9ea5f9d07e5b.zip
refactor(core): use HTTPStatus consistently
Replace numeric HTTP response and assertion codes in views and tests with `HTTPStatus` members so status handling is more descriptive and consistent.
Diffstat (limited to '')
-rw-r--r--tests/tasks/test_discovery.py108
-rw-r--r--tests/tasks/test_receiver.py34
-rw-r--r--tests/tasks/test_sender.py39
3 files changed, 110 insertions, 71 deletions
diff --git a/tests/tasks/test_discovery.py b/tests/tasks/test_discovery.py
index 7c28108..ab621e7 100644
--- a/tests/tasks/test_discovery.py
+++ b/tests/tasks/test_discovery.py
@@ -2,6 +2,7 @@
#
# SPDX-License-Identifier: BSD-3-Clause
+from http import HTTPStatus
from types import ModuleType
from unittest.mock import Mock
@@ -425,9 +426,11 @@ def test_discovery(
) -> None:
def handler(request: httpx.Request) -> httpx.Response:
if request.method == "HEAD":
- return httpx.Response(200, headers=headers)
+ return httpx.Response(HTTPStatus.OK, headers=headers)
- return httpx.Response(200, headers={"Content-Type": "text/html"}, text=html)
+ return httpx.Response(
+ HTTPStatus.OK, headers={"Content-Type": "text/html"}, text=html
+ )
with (
app.app_context(),
@@ -446,9 +449,9 @@ def test_discovery(
pytest.param(
"https://example.com/test/23/page",
{
- "/test/23/page": (302, {"Location": "page/redirect-key"}),
+ "/test/23/page": (HTTPStatus.FOUND, {"Location": "page/redirect-key"}),
"/test/23/page/redirect-key": (
- 200,
+ HTTPStatus.OK,
{"Link": ("<webmention-endpoint/endpoint-key>; rel=webmention")},
),
},
@@ -489,7 +492,9 @@ def test_discovery_stops_after_head(app: Flask, sender_module: ModuleType) -> No
def handler(request: httpx.Request) -> httpx.Response:
requests.append(request)
- return httpx.Response(200, headers={"Link": "</webmention>; rel=webmention"})
+ return httpx.Response(
+ HTTPStatus.OK, headers={"Link": "</webmention>; rel=webmention"}
+ )
with (
app.app_context(),
@@ -512,10 +517,10 @@ def test_discovery_falls_back_to_get(app: Flask, sender_module: ModuleType) -> N
requests.append(request)
if request.method == "HEAD":
- return httpx.Response(200)
+ return httpx.Response(HTTPStatus.OK)
return httpx.Response(
- 200,
+ HTTPStatus.OK,
headers={"Content-Type": "text/html"},
text="""
<link
@@ -557,7 +562,9 @@ def test_discovery_falls_back_to_get_after_head_request_error(
if request.method == "HEAD":
raise failure
- return httpx.Response(200, headers={"Link": "</webmention>; rel=webmention"})
+ return httpx.Response(
+ HTTPStatus.OK, headers={"Link": "</webmention>; rel=webmention"}
+ )
with (
app.app_context(),
@@ -580,7 +587,9 @@ def test_discovery_does_not_suppress_unexpected_head_error(
def handler(request: httpx.Request) -> httpx.Response:
methods.append(request.method)
- return httpx.Response(200, headers={"Link": "</webmention>; rel=webmention"})
+ return httpx.Response(
+ HTTPStatus.OK, headers={"Link": "</webmention>; rel=webmention"}
+ )
with (
app.app_context(),
@@ -628,10 +637,10 @@ def test_discovery_skips_invalid_html_candidate(
) -> None:
def handler(request: httpx.Request) -> httpx.Response:
if request.method == "HEAD":
- return httpx.Response(200)
+ return httpx.Response(HTTPStatus.OK)
return httpx.Response(
- 200,
+ HTTPStatus.OK,
headers={"Content-Type": "text/html"},
text=(
f'<link rel="webmention" href="{invalid_href}">'
@@ -653,7 +662,7 @@ def test_discovery_skips_invalid_link_header_candidate(
) -> None:
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
- 200,
+ HTTPStatus.OK,
headers=[
("Link", "<mailto:invalid@example.com>; rel=webmention"),
("Link", "<http://[invalid>; rel=webmention"),
@@ -675,10 +684,12 @@ def test_discovery_returns_none_when_all_html_candidates_are_invalid(
) -> None:
def handler(request: httpx.Request) -> httpx.Response:
if request.method == "HEAD":
- return httpx.Response(200, headers={"Link": "<mailto:bad>; rel=webmention"})
+ return httpx.Response(
+ HTTPStatus.OK, headers={"Link": "<mailto:bad>; rel=webmention"}
+ )
return httpx.Response(
- 200,
+ HTTPStatus.OK,
headers={"Content-Type": "text/html"},
text='<link rel="webmention" href="javascript:void(0)">',
)
@@ -697,7 +708,7 @@ def test_resolve_endpoint_rejects_invalid_url(
) -> None:
is_http_url = Mock(return_value=False)
monkeypatch.setattr(discovery, "is_http_url", is_http_url)
- response = httpx.Response(200, request=httpx.Request("GET", TARGET_URL))
+ response = httpx.Response(HTTPStatus.OK, request=httpx.Request("GET", TARGET_URL))
with pytest.raises(
sender_module.PermanentSenderError, match="Invalid Webmention endpoint"
):
@@ -709,7 +720,7 @@ def test_endpoint_from_headers_ignores_malformed_link(
sender_module: ModuleType,
) -> None:
response = httpx.Response(
- 200,
+ HTTPStatus.OK,
headers=[("Link", "not-a-link"), ("Link", "</webmention>; rel=webmention")],
request=httpx.Request("GET", TARGET_URL),
)
@@ -717,14 +728,14 @@ def test_endpoint_from_headers_ignores_malformed_link(
def test_endpoint_from_html_accepts_string_rel(sender_module: ModuleType) -> None:
- response = httpx.Response(200, request=httpx.Request("GET", TARGET_URL))
+ response = httpx.Response(HTTPStatus.OK, request=httpx.Request("GET", TARGET_URL))
body = b'<link rel="webmention alternate" href="/webmention">'
assert sender_module.endpoint_from_html(response, body) == ENDPOINT_URL
def test_endpoint_from_html_accepts_uppercase_rel(sender_module: ModuleType) -> None:
- response = httpx.Response(200, request=httpx.Request("GET", TARGET_URL))
+ response = httpx.Response(HTTPStatus.OK, request=httpx.Request("GET", TARGET_URL))
body = b'<LINK REL="ALTERNATE WEBMENTION" HREF="/webmention">'
assert sender_module.endpoint_from_html(response, body) == ENDPOINT_URL
@@ -733,7 +744,7 @@ def test_endpoint_from_html_accepts_uppercase_rel(sender_module: ModuleType) ->
def test_endpoint_from_html_ignores_elements_without_matching_rel_or_href(
sender_module: ModuleType,
) -> None:
- response = httpx.Response(200, request=httpx.Request("GET", TARGET_URL))
+ response = httpx.Response(HTTPStatus.OK, request=httpx.Request("GET", TARGET_URL))
body = b'<link href="/ignored"><a rel="webmention">No endpoint</a>'
assert sender_module.endpoint_from_html(response, body) is None
@@ -744,7 +755,9 @@ def test_read_target_body_rejects_declared_oversized_body(
) -> None:
app.config["MAX_TARGET_BYTES"] = 10
- response = httpx.Response(200, headers={"Content-Length": "11"}, content=b"x" * 11)
+ response = httpx.Response(
+ HTTPStatus.OK, headers={"Content-Length": "11"}, content=b"x" * 11
+ )
with (
app.app_context(),
@@ -768,14 +781,14 @@ def test_read_target_body_does_not_mask_unexpected_value_error(
app.app_context(),
pytest.raises(ValueError, match="unrelated processing error"),
):
- sender_module.read_target_body(httpx.Response(200))
+ sender_module.read_target_body(httpx.Response(HTTPStatus.OK))
def test_read_target_body_ignores_invalid_content_length(
app: Flask, sender_module: ModuleType
) -> None:
response = httpx.Response(
- 200, headers={"Content-Length": "invalid"}, content=b"Document"
+ HTTPStatus.OK, headers={"Content-Length": "invalid"}, content=b"Document"
)
with app.app_context():
@@ -794,7 +807,7 @@ def test_read_target_body_rejects_streamed_oversized_body(
yield b"x" * 6
yield b"x" * 6
- response = httpx.Response(200, stream=BodyStream())
+ response = httpx.Response(HTTPStatus.OK, stream=BodyStream())
with (
app.app_context(),
@@ -814,9 +827,11 @@ def test_discovery_uses_link_header_from_get(
requests.append(request)
if request.method == "HEAD":
- return httpx.Response(200)
+ return httpx.Response(HTTPStatus.OK)
- return httpx.Response(200, headers={"Link": "</webmention>; rel=webmention"})
+ return httpx.Response(
+ HTTPStatus.OK, headers={"Link": "</webmention>; rel=webmention"}
+ )
with (
app.app_context(),
@@ -833,8 +848,10 @@ def test_discovery_uses_link_header_from_get(
@pytest.mark.parametrize(
("status_code", "exception_name"),
[
- pytest.param(503, "TemporarySenderError", id="temporary"),
- pytest.param(404, "PermanentSenderError", id="permanent"),
+ pytest.param(
+ HTTPStatus.SERVICE_UNAVAILABLE, "TemporarySenderError", id="temporary"
+ ),
+ pytest.param(HTTPStatus.NOT_FOUND, "PermanentSenderError", id="permanent"),
],
)
def test_discovery_maps_get_status_to_exception(
@@ -842,7 +859,7 @@ def test_discovery_maps_get_status_to_exception(
) -> None:
def handler(request: httpx.Request) -> httpx.Response:
if request.method == "HEAD":
- return httpx.Response(200)
+ return httpx.Response(HTTPStatus.OK)
return httpx.Response(status_code)
@@ -861,10 +878,10 @@ def test_discovery_returns_none_for_unsupported_media_type(
) -> None:
def handler(request: httpx.Request) -> httpx.Response:
if request.method == "HEAD":
- return httpx.Response(200)
+ return httpx.Response(HTTPStatus.OK)
return httpx.Response(
- 200, headers={"Content-Type": "application/json"}, content=b"{}"
+ HTTPStatus.OK, headers={"Content-Type": "application/json"}, content=b"{}"
)
with (
@@ -880,9 +897,12 @@ def test_discovery_returns_none_for_unsupported_media_type(
("status_code", "location", "expected_status_url"),
[
pytest.param(
- 201, "/webmention/status/123", STATUS_URL, id="created-with-location"
+ HTTPStatus.CREATED,
+ "/webmention/status/123",
+ STATUS_URL,
+ id="created-with-location",
),
- pytest.param(202, None, None, id="accepted"),
+ pytest.param(HTTPStatus.ACCEPTED, None, None, id="accepted"),
],
)
def test_post_webmention(
@@ -925,14 +945,22 @@ def test_post_webmention(
@pytest.mark.parametrize(
("code", "location", "expected"),
[
- (201, "/webmention/status/123", "https://example.com/webmention/status/123"),
- (201, "https://status.example.org/123", "https://status.example.org/123"),
- (201, "status/123", "https://example.com/status/123"),
- (201, "javascript:alert(1)", None),
- (201, "data:text/html,evil", None),
- (201, "ftp://example.com/status", None),
- (201, "http://[invalid", None),
- (202, "https://example.com/status", None),
+ (
+ HTTPStatus.CREATED,
+ "/webmention/status/123",
+ "https://example.com/webmention/status/123",
+ ),
+ (
+ HTTPStatus.CREATED,
+ "https://status.example.org/123",
+ "https://status.example.org/123",
+ ),
+ (HTTPStatus.CREATED, "status/123", "https://example.com/status/123"),
+ (HTTPStatus.CREATED, "javascript:alert(1)", None),
+ (HTTPStatus.CREATED, "data:text/html,evil", None),
+ (HTTPStatus.CREATED, "ftp://example.com/status", None),
+ (HTTPStatus.CREATED, "http://[invalid", None),
+ (HTTPStatus.ACCEPTED, "https://example.com/status", None),
],
)
def test_post_webmention_validates_location(
diff --git a/tests/tasks/test_receiver.py b/tests/tasks/test_receiver.py
index b817162..feb7d7d 100644
--- a/tests/tasks/test_receiver.py
+++ b/tests/tasks/test_receiver.py
@@ -5,6 +5,7 @@
import logging
import uuid
from datetime import UTC, datetime, timedelta
+from http import HTTPStatus
from types import ModuleType
from unittest.mock import Mock, patch
@@ -73,7 +74,7 @@ def test_fetch_source_returns_response_and_body(
httpx_client: Mock, app: Flask, receiver: ModuleType
) -> None:
response = httpx.Response(
- 200,
+ HTTPStatus.OK,
headers={"Content-Type": "text/html"},
content=b"<p>Document</p>",
request=httpx.Request("GET", SOURCE_URL),
@@ -103,14 +104,14 @@ def test_fetch_source_returns_response_and_body(
@pytest.mark.parametrize(
("status_code", "exception_name"),
[
- (400, "VerificationError"),
- (404, "VerificationError"),
- (410, "SourceGoneError"),
- (408, "TemporaryFetchError"),
- (425, "TemporaryFetchError"),
- (429, "TemporaryFetchError"),
- (500, "TemporaryFetchError"),
- (503, "TemporaryFetchError"),
+ (HTTPStatus.BAD_REQUEST, "VerificationError"),
+ (HTTPStatus.NOT_FOUND, "VerificationError"),
+ (HTTPStatus.GONE, "SourceGoneError"),
+ (HTTPStatus.REQUEST_TIMEOUT, "TemporaryFetchError"),
+ (HTTPStatus.TOO_EARLY, "TemporaryFetchError"),
+ (HTTPStatus.TOO_MANY_REQUESTS, "TemporaryFetchError"),
+ (HTTPStatus.INTERNAL_SERVER_ERROR, "TemporaryFetchError"),
+ (HTTPStatus.SERVICE_UNAVAILABLE, "TemporaryFetchError"),
],
)
def test_fetch_source_maps_http_status_to_exception(
@@ -156,7 +157,7 @@ def test_fetch_source_rejects_declared_oversized_body(
set_stream_response(
httpx_client,
httpx.Response(
- 200,
+ HTTPStatus.OK,
headers={"Content-Type": "text/html", "Content-Length": "11"},
content=b"x" * 11,
request=httpx.Request("GET", SOURCE_URL),
@@ -184,7 +185,7 @@ def test_fetch_source_rejects_streamed_oversized_body(
set_stream_response(
httpx_client,
httpx.Response(
- 200,
+ HTTPStatus.OK,
headers={"Content-Type": "text/html"},
stream=BodyStream(),
request=httpx.Request("GET", SOURCE_URL),
@@ -206,7 +207,8 @@ def test_fetch_source_does_not_mask_unexpected_value_error(
monkeypatch: pytest.MonkeyPatch,
) -> None:
set_stream_response(
- httpx_client, httpx.Response(200, request=httpx.Request("GET", SOURCE_URL))
+ httpx_client,
+ httpx.Response(HTTPStatus.OK, request=httpx.Request("GET", SOURCE_URL)),
)
monkeypatch.setattr(
receiver, "read_limited_body", Mock(side_effect=ValueError("unexpected bug"))
@@ -275,7 +277,7 @@ def test_source_mentions_target_by_media_type(
expected: bool,
) -> None:
response = httpx.Response(
- 200,
+ HTTPStatus.OK,
headers={"Content-Type": content_type},
content=body,
request=httpx.Request("GET", SOURCE_URL),
@@ -307,7 +309,7 @@ def test_source_mentions_target_rejects_unsupported_media_type(
headers["Content-Type"] = content_type
response = httpx.Response(
- 200,
+ HTTPStatus.OK,
headers=headers,
content=b"Document",
request=httpx.Request("GET", SOURCE_URL),
@@ -710,7 +712,7 @@ def test_fetch_source_ignores_invalid_content_length(
httpx_client: Mock, app: Flask, receiver: ModuleType
) -> None:
response = httpx.Response(
- 200,
+ HTTPStatus.OK,
headers={"Content-Type": "text/html", "Content-Length": "invalid"},
content=b"<p>Document</p>",
request=httpx.Request("GET", SOURCE_URL),
@@ -731,7 +733,7 @@ def test_source_mentions_target_falls_back_for_unknown_encoding(
body = f"Reply to {TARGET_URL}".encode()
response = httpx.Response(
- 200,
+ HTTPStatus.OK,
headers={"Content-Type": "text/plain"},
content=body,
request=httpx.Request("GET", SOURCE_URL),
diff --git a/tests/tasks/test_sender.py b/tests/tasks/test_sender.py
index 7f453c1..3a22769 100644
--- a/tests/tasks/test_sender.py
+++ b/tests/tasks/test_sender.py
@@ -5,6 +5,7 @@
import logging
import uuid
from datetime import UTC, datetime, timedelta
+from http import HTTPStatus
from types import ModuleType
from unittest.mock import MagicMock, Mock
@@ -76,7 +77,7 @@ def mock_sender_requests(
monkeypatch: pytest.MonkeyPatch,
*,
endpoint: str | None = ENDPOINT_URL,
- result: tuple[int, str | None] = (202, None),
+ result: tuple[int, str | None] = (HTTPStatus.ACCEPTED, None),
) -> tuple[Mock, Mock, Mock, Mock]:
httpx_client = MagicMock()
client = httpx_client.return_value.__enter__.return_value
@@ -130,7 +131,9 @@ def test_attempt_is_current(
def test_deliver_webmention_returns_retryable_outcome(
app: Flask, sender_module: ModuleType, monkeypatch: pytest.MonkeyPatch
) -> None:
- mock_sender_requests(sender_module, monkeypatch, result=(503, None))
+ mock_sender_requests(
+ sender_module, monkeypatch, result=(HTTPStatus.SERVICE_UNAVAILABLE, None)
+ )
with app.app_context():
result = sender_module.deliver_webmention(
@@ -141,7 +144,7 @@ def test_deliver_webmention_returns_retryable_outcome(
status=SentWebmentionStatus.FAILED,
reason="Webmention endpoint returned HTTP 503",
endpoint=ENDPOINT_URL,
- response_status=503,
+ response_status=HTTPStatus.SERVICE_UNAVAILABLE,
terminal=False,
temporary_failure=True,
)
@@ -153,7 +156,7 @@ def test_send_webmention_persists_success(
identifier = create_sent_webmention(app)
_, client, discover, post = mock_sender_requests(
- sender_module, monkeypatch, result=(201, STATUS_URL)
+ sender_module, monkeypatch, result=(HTTPStatus.CREATED, STATUS_URL)
)
sender_module.send_webmention.call_local(identifier)
@@ -172,7 +175,7 @@ def test_send_webmention_persists_success(
assert webmention.status == SentWebmentionStatus.SENT
assert webmention.failure_reason is None
assert webmention.endpoint == ENDPOINT_URL
- assert webmention.response_status == 201
+ assert webmention.response_status == HTTPStatus.CREATED
assert webmention.status_url == STATUS_URL
assert webmention.last_attempted_at is not None
assert webmention.last_sent_at is not None
@@ -190,7 +193,7 @@ def test_send_webmention_marks_unsupported_target_processed(
sent_revision=1,
status=SentWebmentionStatus.SENT,
endpoint="https://old.example/webmention",
- response_status=201,
+ response_status=HTTPStatus.CREATED,
status_url="https://old.example/status/123",
)
@@ -229,7 +232,9 @@ def test_send_webmention_persists_permanent_failure(
status_url="https://old.example/status/123",
)
- mock_sender_requests(sender_module, monkeypatch, result=(400, None))
+ mock_sender_requests(
+ sender_module, monkeypatch, result=(HTTPStatus.BAD_REQUEST, None)
+ )
sender_module.send_webmention.call_local(identifier)
@@ -242,7 +247,7 @@ def test_send_webmention_persists_permanent_failure(
assert webmention.status == SentWebmentionStatus.FAILED
assert webmention.failure_reason == "Webmention endpoint returned HTTP 400"
assert webmention.endpoint == ENDPOINT_URL
- assert webmention.response_status == 400
+ assert webmention.response_status == HTTPStatus.BAD_REQUEST
assert webmention.status_url is None
@@ -258,7 +263,9 @@ def test_send_webmention_persists_temporary_failure_with_backoff(
status_url="https://old.example/status/123",
)
- mock_sender_requests(sender_module, monkeypatch, result=(503, None))
+ mock_sender_requests(
+ sender_module, monkeypatch, result=(HTTPStatus.SERVICE_UNAVAILABLE, None)
+ )
sender_module.send_webmention.call_local(identifier)
@@ -271,7 +278,7 @@ def test_send_webmention_persists_temporary_failure_with_backoff(
assert webmention.status == SentWebmentionStatus.FAILED
assert webmention.failure_reason == "Webmention endpoint returned HTTP 503"
assert webmention.endpoint == ENDPOINT_URL
- assert webmention.response_status == 503
+ assert webmention.response_status == HTTPStatus.SERVICE_UNAVAILABLE
assert webmention.status_url is None
assert webmention.attempt_count == 1
assert webmention.next_retry_at is not None
@@ -304,7 +311,7 @@ def test_temporary_failure_backoff_suppresses_duplicate_tasks_and_caps_attempts(
app.config["SEND_MAX_ATTEMPTS"] = 3
identifier = create_sent_webmention(app)
_, _, discover, post = mock_sender_requests(
- sender_module, monkeypatch, result=(503, None)
+ sender_module, monkeypatch, result=(HTTPStatus.SERVICE_UNAVAILABLE, None)
)
for attempt in range(1, 4):
@@ -622,7 +629,7 @@ def test_send_webmention_ignores_superseded_attempt(
def post_success(*args, **kwargs) -> tuple[int, None]:
supersede_revision()
- return (202, None)
+ return (HTTPStatus.ACCEPTED, None)
post.side_effect = post_success
@@ -645,7 +652,7 @@ def test_send_webmention_ignores_superseded_attempt(
def post_permanent_failure(*args, **kwargs) -> tuple[int, None]:
supersede_revision()
- return (400, None)
+ return (HTTPStatus.BAD_REQUEST, None)
post.side_effect = post_permanent_failure
@@ -696,7 +703,9 @@ def test_send_does_not_persist_unsafe_status_url(
sender_module, "discover_webmention_endpoint", Mock(return_value=ENDPOINT_URL)
)
monkeypatch.setattr(
- sender_module, "post_webmention", Mock(return_value=(201, status_url))
+ sender_module,
+ "post_webmention",
+ Mock(return_value=(HTTPStatus.CREATED, status_url)),
)
sender_module.send_webmention.call_local(identifier)
@@ -705,5 +714,5 @@ def test_send_does_not_persist_unsafe_status_url(
mention = db.session.get(SentWebmention, identifier)
assert mention is not None
assert mention.status == SentWebmentionStatus.SENT
- assert mention.response_status == 201
+ assert mention.response_status == HTTPStatus.CREATED
assert mention.status_url == expected