diff options
| author | Dennis Fink | 2026-11-14 19:43:28 +0100 |
|---|---|---|
| committer | Dennis Fink | 2026-11-14 19:43:28 +0100 |
| commit | c74feda222745ab7cca8993df83d9ea5f9d07e5b (patch) | |
| tree | acc7bf9bd7223f9d685d6c2954c5c90d7a9e36f0 | |
| parent | e52e554e2d033dd5ef8397617644e90e354f9560 (diff) | |
| download | webmentions-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.py | 108 | ||||
| -rw-r--r-- | tests/tasks/test_receiver.py | 34 | ||||
| -rw-r--r-- | tests/tasks/test_sender.py | 39 | ||||
| -rw-r--r-- | tests/test_auth.py | 12 | ||||
| -rw-r--r-- | tests/test_models.py | 3 | ||||
| -rw-r--r-- | tests/test_net.py | 23 | ||||
| -rw-r--r-- | tests/views/helpers.py | 9 | ||||
| -rw-r--r-- | tests/views/test_admin.py | 41 | ||||
| -rw-r--r-- | tests/views/test_endpoint.py | 47 | ||||
| -rw-r--r-- | tests/views/test_session.py | 63 | ||||
| -rw-r--r-- | webmentions_ssg/views/admin.py | 11 | ||||
| -rw-r--r-- | webmentions_ssg/views/endpoint.py | 7 |
12 files changed, 232 insertions, 165 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 diff --git a/tests/test_auth.py b/tests/test_auth.py index bc951b9..3b05b6f 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -4,6 +4,8 @@ """Test the session user loader.""" +from http import HTTPStatus + import pytest from flask import Flask @@ -94,8 +96,8 @@ def test_password_change_invalidates_existing_session(app: Flask) -> None: response = client.post( "/login", data={"username": "account", "password": old_password} ) - assert response.status_code == 302 - assert client.get("/received").status_code == 200 + assert response.status_code == HTTPStatus.FOUND + assert client.get("/received").status_code == HTTPStatus.OK with client.session_transaction() as session: assert session["_user_id"] == old_identifier @@ -113,14 +115,14 @@ def test_password_change_invalidates_existing_session(app: Flask) -> None: assert load_user(user.get_id()) is user # A pre-existing, validly signed cookie no longer authenticates. - assert client.get("/received").status_code == 302 + assert client.get("/received").status_code == HTTPStatus.FOUND # Logging in with the newly chosen password still works. response = client.post( "/login", data={"username": "account", "password": new_password} ) - assert response.status_code == 302 - assert client.get("/received").status_code == 200 + assert response.status_code == HTTPStatus.FOUND + assert client.get("/received").status_code == HTTPStatus.OK @pytest.mark.parametrize( diff --git a/tests/test_models.py b/tests/test_models.py index 01e2cec..d2b667c 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -5,6 +5,7 @@ import uuid from collections.abc import Callable from datetime import UTC, datetime +from http import HTTPStatus from typing import get_type_hints import pytest @@ -318,7 +319,7 @@ def test_resend_requeues_current_revision_without_losing_send_history() -> None: status=SentWebmentionStatus.FAILED, failure_reason="Previous failure", endpoint="https://example.com/webmention", - response_status=503, + response_status=HTTPStatus.SERVICE_UNAVAILABLE, status_url="https://example.com/status", attempt_count=3, next_retry_at=sent_at, diff --git a/tests/test_net.py b/tests/test_net.py index b778310..3b754c0 100644 --- a/tests/test_net.py +++ b/tests/test_net.py @@ -6,6 +6,7 @@ import ipaddress import socket +from http import HTTPStatus from unittest.mock import Mock, PropertyMock, patch import httpcore @@ -113,9 +114,11 @@ def test_backend_closes_socket_on_failure( @pytest.mark.parametrize("mode", ["declared", "streamed"]) def test_read_limited_body_raises_specific_size_error(mode: str) -> None: response = ( - httpx.Response(200, headers={"Content-Length": "11"}, content=b"x" * 11) + httpx.Response( + HTTPStatus.OK, headers={"Content-Length": "11"}, content=b"x" * 11 + ) if mode == "declared" - else httpx.Response(200, stream=httpx.ByteStream(b"x" * 11)) + else httpx.Response(HTTPStatus.OK, stream=httpx.ByteStream(b"x" * 11)) ) with pytest.raises(ResponseTooLargeError, match="Source document is too large"): @@ -164,7 +167,7 @@ def test_transport_keeps_original_http_host_and_tls_sni( with httpx.Client(transport=PublicHTTPTransport(5.0), trust_env=False) as client: response = client.get(f"{scheme}://source.example/path") - assert response.status_code == 200 + assert response.status_code == HTTPStatus.OK assert response.text == "OK" assert b"Host: source.example\r\n" in stream.writes assert b"GET /path HTTP/1.1\r\n" in stream.writes @@ -321,12 +324,14 @@ def test_public_addresses_rejects_empty_dns_result() -> None: @pytest.mark.parametrize( ("status", "expected"), [ - pytest.param(200, False, id="success"), - pytest.param(400, False, id="client-error"), - pytest.param(408, True, id="request-timeout"), - pytest.param(425, True, id="too-early"), - pytest.param(429, True, id="too-many-requests"), - pytest.param(500, True, id="server-error-lower-bound"), + pytest.param(HTTPStatus.OK, False, id="success"), + pytest.param(HTTPStatus.BAD_REQUEST, False, id="client-error"), + pytest.param(HTTPStatus.REQUEST_TIMEOUT, True, id="request-timeout"), + pytest.param(HTTPStatus.TOO_EARLY, True, id="too-early"), + pytest.param(HTTPStatus.TOO_MANY_REQUESTS, True, id="too-many-requests"), + pytest.param( + HTTPStatus.INTERNAL_SERVER_ERROR, True, id="server-error-lower-bound" + ), pytest.param(599, True, id="server-error-upper-bound"), pytest.param(600, False, id="outside-server-error-range"), ], diff --git a/tests/views/helpers.py b/tests/views/helpers.py index da98aa6..1fe1ed2 100644 --- a/tests/views/helpers.py +++ b/tests/views/helpers.py @@ -4,6 +4,7 @@ import uuid from datetime import UTC, datetime +from http import HTTPStatus from types import ModuleType from unittest.mock import Mock @@ -80,7 +81,7 @@ def create_sent_source(app: Flask) -> uuid.UUID: sent_revision=2, status=SentWebmentionStatus.SENT, endpoint="https://example.com/webmention", - response_status=202, + response_status=HTTPStatus.ACCEPTED, ), SentWebmention( target="https://example.com/a", @@ -91,7 +92,7 @@ def create_sent_source(app: Flask) -> uuid.UUID: status=SentWebmentionStatus.FAILED, failure_reason="Webmention endpoint returned HTTP 400", endpoint="https://example.com/webmention", - response_status=400, + response_status=HTTPStatus.BAD_REQUEST, ), ] ) @@ -173,7 +174,7 @@ def create_resendable_sent_webmention(app: Flask) -> tuple[uuid.UUID, uuid.UUID] status=SentWebmentionStatus.FAILED, failure_reason="Previous failure", endpoint="https://example.com/webmention", - response_status=500, + response_status=HTTPStatus.INTERNAL_SERVER_ERROR, status_url="https://example.com/webmention/status/123", ) source.sent_webmentions.append(webmention) @@ -202,7 +203,7 @@ def create_outgoing( active=True, desired_revision=1, status_url=status_url, - response_status=201 if status_url is not None else None, + response_status=HTTPStatus.CREATED if status_url is not None else None, ) source.sent_webmentions.append(mention) db.session.add(source) diff --git a/tests/views/test_admin.py b/tests/views/test_admin.py index f166318..a88fbfa 100644 --- a/tests/views/test_admin.py +++ b/tests/views/test_admin.py @@ -4,6 +4,7 @@ import uuid from datetime import UTC, datetime, timedelta +from http import HTTPStatus from types import ModuleType from unittest.mock import Mock @@ -38,7 +39,7 @@ def views_module(app: Flask) -> ModuleType: def test_sent_views_require_login(client: FlaskClient, path: str) -> None: response = client.get(path) - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert "/login" in response.headers["Location"] @@ -48,7 +49,7 @@ def test_sent_lists_sources(app: Flask, client: FlaskClient) -> None: response = client.get("/sent") - assert response.status_code == 200 + assert response.status_code == HTTPStatus.OK html = response.get_data(as_text=True) @@ -63,7 +64,7 @@ def test_sent_source_lists_webmentions(app: Flask, client: FlaskClient) -> None: response = client.get(f"/sent/{identifier}") - assert response.status_code == 200 + assert response.status_code == HTTPStatus.OK html = response.get_data(as_text=True) @@ -86,13 +87,13 @@ def test_sent_source_returns_404_for_unknown_source( ) -> None: log_in(app, client) response = client.get(f"/sent/{uuid.uuid7()}") - assert response.status_code == 404 + assert response.status_code == HTTPStatus.NOT_FOUND def test_received_requires_login(client: FlaskClient) -> None: response = client.get("/received") - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert "/login" in response.headers["Location"] @@ -102,7 +103,7 @@ def test_received_lists_webmentions(app: Flask, client: FlaskClient) -> None: response = client.get("/received") - assert response.status_code == 200 + assert response.status_code == HTTPStatus.OK html = response.get_data(as_text=True) assert SOURCE_URL in html assert TARGET_URL in html @@ -112,7 +113,7 @@ def test_received_lists_webmentions(app: Flask, client: FlaskClient) -> None: def test_received_admin_actions_require_login(client: FlaskClient, action: str) -> None: response = client.post(f"/received/{uuid.uuid7()}/{action}") - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert "/login" in response.headers["Location"] @@ -130,7 +131,7 @@ def test_received_admin_actions_reject_invalid_form( response = client.post(f"/received/{identifier}/{action}") - assert response.status_code == 400 + assert response.status_code == HTTPStatus.BAD_REQUEST form.validate_on_submit.assert_called_once_with() @@ -147,7 +148,7 @@ def test_received_admin_actions_return_404_for_unknown_webmention( response = client.post(f"/received/{uuid.uuid7()}/{action}") - assert response.status_code == 404 + assert response.status_code == HTTPStatus.NOT_FOUND def test_delete_received_webmention( @@ -162,7 +163,7 @@ def test_delete_received_webmention( response = client.post(f"/received/{identifier}/delete?page=3") - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert response.headers["Location"].endswith("/received?page=3") with app.app_context(): @@ -190,7 +191,7 @@ def test_reverify_received_webmention( response = client.post(f"/received/{identifier}/reverify?page=2") - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert response.headers["Location"].endswith("/received?page=2") with app.app_context(): @@ -206,7 +207,7 @@ def test_reverify_received_webmention( def test_rescan_sent_sources_requires_login(client: FlaskClient) -> None: response = client.post("/sent/rescan") - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert "/login" in response.headers["Location"] @@ -225,7 +226,9 @@ def test_rescan_sent_sources( response = client.post("/sent/rescan") - assert response.status_code == (302 if valid else 400) + assert response.status_code == ( + HTTPStatus.FOUND if valid else HTTPStatus.BAD_REQUEST + ) form.validate_on_submit.assert_called_once_with() if valid: @@ -238,7 +241,7 @@ def test_rescan_sent_sources( def test_resend_sent_webmention_requires_login(client: FlaskClient) -> None: response = client.post(f"/sent/{uuid.uuid7()}/{uuid.uuid7()}/resend") - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert "/login" in response.headers["Location"] @@ -254,7 +257,7 @@ def test_resend_sent_webmention_rejects_invalid_form( response = client.post(f"/sent/{source_identifier}/{webmention_identifier}/resend") - assert response.status_code == 400 + assert response.status_code == HTTPStatus.BAD_REQUEST def test_resend_sent_webmention_returns_404_for_unknown_webmention( @@ -269,7 +272,7 @@ def test_resend_sent_webmention_returns_404_for_unknown_webmention( response = client.post(f"/sent/{source_identifier}/{uuid.uuid7()}/resend") - assert response.status_code == 404 + assert response.status_code == HTTPStatus.NOT_FOUND def test_resend_sent_webmention_rejects_wrong_source( @@ -287,7 +290,7 @@ def test_resend_sent_webmention_rejects_wrong_source( f"/sent/{wrong_source_identifier}/{webmention_identifier}/resend" ) - assert response.status_code == 404 + assert response.status_code == HTTPStatus.NOT_FOUND def test_resend_sent_webmention_reopens_current_revision( @@ -311,7 +314,7 @@ def test_resend_sent_webmention_reopens_current_revision( response = client.post(f"/sent/{source_identifier}/{webmention_identifier}/resend") - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert response.headers["Location"].endswith(f"/sent/{source_identifier}") with app.app_context(): @@ -356,7 +359,7 @@ def test_admin_only_links_safe_existing_status_urls( session["_fresh"] = True response = client.get(f"/sent/{source_identifier}") - assert response.status_code == 200 + assert response.status_code == HTTPStatus.OK html = response.get_data(as_text=True) assert (f'href="{status_url}"' in html) is safe assert status_url in html diff --git a/tests/views/test_endpoint.py b/tests/views/test_endpoint.py index 4b81d70..52ef77d 100644 --- a/tests/views/test_endpoint.py +++ b/tests/views/test_endpoint.py @@ -4,6 +4,7 @@ import uuid from datetime import UTC, datetime, timedelta +from http import HTTPStatus from types import ModuleType from unittest.mock import ANY, Mock @@ -34,7 +35,7 @@ def views_module(app: Flask) -> ModuleType: def test_endpoint_only_accepts_post(client: FlaskClient) -> None: response = client.get("/endpoint") - assert response.status_code == 405 + assert response.status_code == HTTPStatus.METHOD_NOT_ALLOWED def test_endpoint_returns_form_errors( @@ -45,7 +46,7 @@ def test_endpoint_returns_form_errors( response = client.post("/endpoint") - assert response.status_code == 400 + assert response.status_code == HTTPStatus.BAD_REQUEST assert response.get_json() == errors @@ -61,7 +62,7 @@ def test_endpoint_creates_webmention( response = client.post("/endpoint") - assert response.status_code == 201 + assert response.status_code == HTTPStatus.CREATED form.validate_on_submit.assert_called_once_with() with app.app_context(): @@ -92,8 +93,8 @@ def test_endpoint_is_idempotent( first_response = client.post("/endpoint") second_response = client.post("/endpoint") - assert first_response.status_code == 201 - assert second_response.status_code == 201 + assert first_response.status_code == HTTPStatus.CREATED + assert second_response.status_code == HTTPStatus.CREATED assert first_response.headers["Location"] == second_response.headers["Location"] with app.app_context(): @@ -140,7 +141,7 @@ def test_resending_resets_failure_state( response = client.post("/endpoint") - assert response.status_code == 201 + assert response.status_code == HTTPStatus.CREATED with app.app_context(): webmention = db.session.get(ReceivedWebmention, identifier) @@ -155,7 +156,7 @@ def test_resending_resets_failure_state( def test_status_returns_404_for_unknown_webmention(client: FlaskClient) -> None: response = client.get(f"/status/{uuid.uuid7()}") - assert response.status_code == 404 + assert response.status_code == HTTPStatus.NOT_FOUND def test_status_displays_webmention(app: Flask, client: FlaskClient) -> None: @@ -165,7 +166,7 @@ def test_status_displays_webmention(app: Flask, client: FlaskClient) -> None: response = client.get(f"/status/{identifier}") - assert response.status_code == 200 + assert response.status_code == HTTPStatus.OK html = response.get_data(as_text=True) assert SOURCE_URL in html assert TARGET_URL in html @@ -222,7 +223,7 @@ def test_endpoint_recovers_from_concurrent_insert( response = client.post("/endpoint") - assert response.status_code == 201 + assert response.status_code == HTTPStatus.CREATED assert response.headers["Location"].endswith(f"/status/{competing_identifier}") assert execute.call_count == 3 @@ -261,7 +262,7 @@ def test_endpoint_rejects_digest_collision( response = client.post("/endpoint") - assert response.status_code == 409 + assert response.status_code == HTTPStatus.CONFLICT assert response.get_json() == {"error": "Webmention URL fingerprint conflict"} verify.assert_not_called() with app.app_context(): @@ -288,7 +289,11 @@ def test_endpoint_rate_limits_requests_per_ip( client.post("/endpoint", environ_overrides={"REMOTE_ADDR": "192.0.2.10"}) ) - assert [r.status_code for r in responses] == [201, 201, 429] + assert [r.status_code for r in responses] == [ + HTTPStatus.CREATED, + HTTPStatus.CREATED, + HTTPStatus.TOO_MANY_REQUESTS, + ] assert verify.call_count == 2 @@ -320,9 +325,9 @@ def test_endpoint_rate_limit_distinguishes_clients_behind_trusted_proxy( headers={"X-Forwarded-For": client_ip}, ).status_code - assert attempt("198.51.100.11", 0) == 201 - assert attempt("198.51.100.11", 1) == 429 - assert attempt("198.51.100.12", 2) == 201 + assert attempt("198.51.100.11", 0) == HTTPStatus.CREATED + assert attempt("198.51.100.11", 1) == HTTPStatus.TOO_MANY_REQUESTS + assert attempt("198.51.100.12", 2) == HTTPStatus.CREATED def test_endpoint_global_rate_limit( @@ -348,7 +353,11 @@ def test_endpoint_global_rate_limit( ) ) - assert [r.status_code for r in responses] == [201, 201, 429] + assert [r.status_code for r in responses] == [ + HTTPStatus.CREATED, + HTTPStatus.CREATED, + HTTPStatus.TOO_MANY_REQUESTS, + ] assert verify.call_count == 2 @@ -377,7 +386,7 @@ def test_endpoint_recent_duplicate_does_not_reverify( response = client.post("/endpoint") - assert response.status_code == 201 + assert response.status_code == HTTPStatus.CREATED assert response.headers["Location"].endswith(str(identifier)) with app.app_context(): @@ -416,7 +425,7 @@ def test_endpoint_reverifies_after_cooldown( response = client.post("/endpoint") - assert response.status_code == 201 + assert response.status_code == HTTPStatus.CREATED with app.app_context(): stored = db.session.get(ReceivedWebmention, identifier) @@ -435,7 +444,7 @@ def test_endpoint_rejects_request_bodies_over_configured_maximum( response = client.post( "/endpoint", data={"source": SOURCE_URL + "x" * 150, "target": TARGET_URL} ) - assert response.status_code == 413 + assert response.status_code == HTTPStatus.CONTENT_TOO_LARGE def test_endpoint_rejects_bad_url_before_inserting_row( @@ -450,7 +459,7 @@ def test_endpoint_rejects_bad_url_before_inserting_row( "/endpoint", data={"source": "http://ex☃mple.test/", "target": TARGET_URL} ) - assert response.status_code == 400 + assert response.status_code == HTTPStatus.BAD_REQUEST assert "source" in response.get_json() verify_webmention.assert_not_called() with app.app_context(): diff --git a/tests/views/test_session.py b/tests/views/test_session.py index 1a58f52..a91a6b2 100644 --- a/tests/views/test_session.py +++ b/tests/views/test_session.py @@ -2,6 +2,7 @@ # # SPDX-License-Identifier: BSD-3-Clause +from http import HTTPStatus from types import ModuleType import pytest @@ -25,7 +26,7 @@ def views_module(app: Flask) -> ModuleType: def test_login_renders_form(client: FlaskClient) -> None: response = client.get("/login") - assert response.status_code == 200 + assert response.status_code == HTTPStatus.OK assert "login" in response.get_data(as_text=True).lower() @@ -47,7 +48,7 @@ def test_login_rejects_invalid_credentials( response = client.post("/login") - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert response.headers["Location"].endswith("/login") with client.session_transaction() as session: @@ -81,7 +82,7 @@ def test_login_redirects_to_local_next_page( response = client.post("/login", query_string={"next": next_url}) - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert response.headers["Location"] == next_url with client.session_transaction() as session: @@ -123,7 +124,7 @@ def test_login_rejects_unsafe_next_page( query_string = {} if next_url is None else {"next": next_url} response = client.post("/login", query_string=query_string) - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert response.headers["Location"] == "/" with client.session_transaction() as session: @@ -135,7 +136,7 @@ def test_login_redirects_authenticated_user(app: Flask, client: FlaskClient) -> response = client.get("/login") - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert response.headers["Location"].endswith("/") @@ -170,7 +171,7 @@ def test_login_always_checks_password( response = client.post("/login") - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert response.headers["Location"].endswith("/login") expected_hash = ( real_password_hash @@ -205,7 +206,7 @@ def test_login_rejects_unknown_user_even_if_password_matches( response = client.post("/login") - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert response.headers["Location"].endswith("/login") assert checked_passwords == [(views_module.dummy_password_hash(), "anything")] @@ -233,12 +234,12 @@ def test_login_rate_limit_is_independent_per_ip( response = client.post("/login", environ_overrides={"REMOTE_ADDR": ip}) return response.status_code - assert attempt("192.0.2.10") == 302 - assert attempt("192.0.2.10") == 429 + assert attempt("192.0.2.10") == HTTPStatus.FOUND + assert attempt("192.0.2.10") == HTTPStatus.TOO_MANY_REQUESTS # Another IP still has its own allowance. - assert attempt("192.0.2.11") == 302 - assert attempt("192.0.2.11") == 429 + assert attempt("192.0.2.11") == HTTPStatus.FOUND + assert attempt("192.0.2.11") == HTTPStatus.TOO_MANY_REQUESTS def test_login_rate_limit_uses_forwarded_client_ip_when_proxy_is_trusted( @@ -267,10 +268,10 @@ def test_login_rate_limit_uses_forwarded_client_ip_when_proxy_is_trusted( ) return response.status_code - assert attempt("198.51.100.11") == 302 + assert attempt("198.51.100.11") == HTTPStatus.FOUND # A forged earlier X-Forwarded-For entry cannot change the client bucket. - assert attempt("203.0.113.99, 198.51.100.11") == 429 - assert attempt("198.51.100.12") == 302 + assert attempt("203.0.113.99, 198.51.100.11") == HTTPStatus.TOO_MANY_REQUESTS + assert attempt("198.51.100.12") == HTTPStatus.FOUND def test_login_username_limit_throttles_across_ips( @@ -298,16 +299,16 @@ def test_login_username_limit_throttles_across_ips( environ_overrides={"REMOTE_ADDR": ip}, ).status_code - assert attempt("192.0.2.10", "Admin") == 302 - assert attempt("192.0.2.11", " admin ") == 302 - assert attempt("192.0.2.12", "ADMIN") == 429 + assert attempt("192.0.2.10", "Admin") == HTTPStatus.FOUND + assert attempt("192.0.2.11", " admin ") == HTTPStatus.FOUND + assert attempt("192.0.2.12", "ADMIN") == HTTPStatus.TOO_MANY_REQUESTS # An unrelated username is not locked by attempts against Admin. - assert attempt("192.0.2.12", "another-user") == 302 + assert attempt("192.0.2.12", "another-user") == HTTPStatus.FOUND # Restore the real form: the POST-only limits must not block a GET, # even from the client IP that submitted the throttled attempt. response = client.get("/login", environ_overrides={"REMOTE_ADDR": "192.0.2.12"}) - assert response.status_code == 200 + assert response.status_code == HTTPStatus.OK def test_login_missing_username_uses_per_ip_bucket( @@ -329,9 +330,9 @@ def test_login_missing_username_uses_per_ip_bucket( def attempt(ip: str) -> int: return client.post("/login", environ_overrides={"REMOTE_ADDR": ip}).status_code - assert attempt("192.0.2.10") == 302 - assert attempt("192.0.2.10") == 429 - assert attempt("192.0.2.11") == 302 + assert attempt("192.0.2.10") == HTTPStatus.FOUND + assert attempt("192.0.2.10") == HTTPStatus.TOO_MANY_REQUESTS + assert attempt("192.0.2.11") == HTTPStatus.FOUND def test_login_rate_limits_requests_per_ip( @@ -356,14 +357,18 @@ def test_login_rate_limits_requests_per_ip( for _ in range(3) ] - assert [response.status_code for response in responses] == [302, 302, 429] + assert [response.status_code for response in responses] == [ + HTTPStatus.FOUND, + HTTPStatus.FOUND, + HTTPStatus.TOO_MANY_REQUESTS, + ] assert form.validate_on_submit.call_count == 2 assert "Too many login attempts" in responses[-1].get_data(as_text=True) # The real LoginForm is restored here. # GET requests must remain accessible after throttling. response = client.get("/login", environ_overrides={"REMOTE_ADDR": "192.0.2.10"}) - assert response.status_code == 200 + assert response.status_code == HTTPStatus.OK with client.session_transaction() as session: assert "_user_id" not in session @@ -374,7 +379,7 @@ def test_logout_rejects_get(app: Flask, client: FlaskClient) -> None: response = client.get("/logout") - assert response.status_code == 405 + assert response.status_code == HTTPStatus.METHOD_NOT_ALLOWED with client.session_transaction() as session: assert "_user_id" in session @@ -395,7 +400,7 @@ def test_logout_rejects_invalid_csrf( response = client.post("/logout", data=data) - assert response.status_code == 400 + assert response.status_code == HTTPStatus.BAD_REQUEST with client.session_transaction() as session: assert "_user_id" in session @@ -408,7 +413,7 @@ def test_logout_ends_session(app: Flask, client: FlaskClient) -> None: log_in(app, client) page = client.get("/received") - assert page.status_code == 200 + assert page.status_code == HTTPStatus.OK html = page.get_data(as_text=True) @@ -420,12 +425,12 @@ def test_logout_ends_session(app: Flask, client: FlaskClient) -> None: response = client.post("/logout", data={"csrf_token": match.group(1)}) - assert response.status_code == 302 + assert response.status_code == HTTPStatus.FOUND assert response.headers["Location"].endswith("/") with client.session_transaction() as session: assert "_user_id" not in session protected_response = client.get("/received") - assert protected_response.status_code == 302 + assert protected_response.status_code == HTTPStatus.FOUND assert "/login" in protected_response.headers["Location"] diff --git a/webmentions_ssg/views/admin.py b/webmentions_ssg/views/admin.py index 1025e69..2ccd92a 100644 --- a/webmentions_ssg/views/admin.py +++ b/webmentions_ssg/views/admin.py @@ -5,6 +5,7 @@ """Authenticated incoming and outgoing Webmention management.""" import uuid +from http import HTTPStatus import sqlalchemy as sa from flask import abort, flash, redirect, render_template, request, url_for @@ -50,7 +51,7 @@ def delete_received_webmention(identifier: uuid.UUID) -> ResponseReturnValue: :returns: Redirect response to the received Webmentions view. """ if not forms.AdminActionForm().validate_on_submit(): - abort(400) + abort(HTTPStatus.BAD_REQUEST) webmention = db.get_or_404(ReceivedWebmention, identifier) @@ -75,7 +76,7 @@ def reverify_received_webmention(identifier: uuid.UUID) -> ResponseReturnValue: :returns: Redirect response to the received Webmentions view. """ if not forms.AdminActionForm().validate_on_submit(): - abort(400) + abort(HTTPStatus.BAD_REQUEST) webmention = db.get_or_404(ReceivedWebmention, identifier) @@ -121,7 +122,7 @@ def rescan_sent_sources() -> ResponseReturnValue: :returns: Redirect response to the sent Webmentions view. """ if not forms.AdminActionForm().validate_on_submit(): - abort(400) + abort(HTTPStatus.BAD_REQUEST) manual_scan_sources() flash("Source rescan queued.", "success") @@ -172,12 +173,12 @@ def resend_sent_webmention( :returns: Redirect response to the source details view. """ if not forms.AdminActionForm().validate_on_submit(): - abort(400) + abort(HTTPStatus.BAD_REQUEST) webmention = db.get_or_404(SentWebmention, webmention_identifier) if webmention.source_id != source_identifier: - abort(404) + abort(HTTPStatus.NOT_FOUND) # Requeue the existing desired revision instead of inventing a new source # revision. send_webmention() otherwise exits when this revision has already diff --git a/webmentions_ssg/views/endpoint.py b/webmentions_ssg/views/endpoint.py index 85ec398..06740e5 100644 --- a/webmentions_ssg/views/endpoint.py +++ b/webmentions_ssg/views/endpoint.py @@ -6,6 +6,7 @@ import uuid from datetime import UTC, datetime, timedelta +from http import HTTPStatus from typing import cast import sqlalchemy as sa @@ -141,7 +142,7 @@ def endpoint() -> ResponseReturnValue: form = forms.EndpointForm(meta={"csrf": False}) if not form.validate_on_submit(): - return form.errors, 400 + return form.errors, HTTPStatus.BAD_REQUEST source = cast(str, form.source.data) target = cast(str, form.target.data) @@ -149,7 +150,7 @@ def endpoint() -> ResponseReturnValue: result = submit_received(source, target) if result is None: - return {"error": "Webmention URL fingerprint conflict"}, 409 + return {"error": "Webmention URL fingerprint conflict"}, HTTPStatus.CONFLICT identifier, should_verify = result @@ -158,7 +159,7 @@ def endpoint() -> ResponseReturnValue: status_url = url_for("root.status", identifier=str(identifier), _external=True) - return Response(status=201, headers={"Location": status_url}) + return Response(status=HTTPStatus.CREATED, headers={"Location": status_url}) @root_page.route("/status/<uuid:identifier>") |
