Scrapy, a fast high-level web crawling & scraping framework for Python.
Add tests for how handlers change the header capitalization. (#8381)
Andrey Rakhmatullin33ac758244e0
diff --git a/tests/mockserver/raw_http.py b/tests/mockserver/raw_http.pynew file mode 100644index 000000000..122356889--- /dev/null+++ b/tests/mockserver/raw_http.py@@ -0,0 +1,71 @@+from __future__ import annotations++import socketserver+import threading+from typing import TYPE_CHECKING, Self++if TYPE_CHECKING:+ from collections.abc import Iterable+++class _RawHttpHandler(socketserver.BaseRequestHandler):+ server: RawHttpServer++ def handle(self) -> None:+ data = b""+ while b"\r\n\r\n" not in data:+ chunk = self.request.recv(65536)+ if not chunk:+ return+ data += chunk+ self.server.request_heads.append(data.partition(b"\r\n\r\n")[0])+ header_lines = b"".join(+ name + b": " + value + b"\r\n"+ for name, value in self.server.response_headers+ )+ self.request.sendall(+ b"HTTP/1.1 200 OK\r\n"+ + header_lines+ + b"Content-Length: 0\r\nConnection: close\r\n\r\n"+ )+++class RawHttpServer(socketserver.ThreadingTCPServer):+ """An HTTP/1.1 server that keeps the bytes of the request heads it+ receives and answers every request with *response_headers* as they are.++ Unlike the Twisted-based mock servers, it does not change the case of+ header names, so tests can check them as they are on the wire.++ It runs on a separate thread, so it works with and without a reactor.+ """++ daemon_threads = True+ allow_reuse_address = True++ def __init__(self, response_headers: Iterable[tuple[bytes, bytes]] = ()) -> None:+ super().__init__(("127.0.0.1", 0), _RawHttpHandler)+ self.response_headers: list[tuple[bytes, bytes]] = list(response_headers)+ #: Request lines and header lines of the received requests.+ self.request_heads: list[bytes] = []+ self._thread = threading.Thread(target=self.serve_forever, daemon=True)++ def __enter__(self) -> Self:+ self._thread.start()+ return self++ def __exit__(self, *args: object) -> None:+ self.shutdown()+ self.server_close()+ self._thread.join()++ @property+ def url(self) -> str:+ return f"http://127.0.0.1:{self.server_address[1]}"++ def request_header_names(self) -> list[bytes]:+ """Return the header names of the last received request, as sent."""+ return [+ line.partition(b":")[0]+ for line in self.request_heads[-1].split(b"\r\n")[1:]+ ]diff --git a/tests/test_downloader_handler_twisted_http11.py b/tests/test_downloader_handler_twisted_http11.pyindex 97f84ac1f..00598e642 100644--- a/tests/test_downloader_handler_twisted_http11.py+++ b/tests/test_downloader_handler_twisted_http11.py@@ -77,6 +77,7 @@ if TYPE_CHECKING:from twisted.web.iweb import IPolicyForHTTPSfrom scrapy.core.downloader.handlers import DownloadHandlerProtocol+ from tests.utils.bases.download_handlers_http import HeaderNameCasepytestmark = pytest.mark.requires_reactor # HTTP11DownloadHandler requires a reactor@@ -99,6 +100,8 @@ class HTTP11DownloadHandlerMixin:}handler_supports_custom_content_length = False+ handler_request_header_name_case: HeaderNameCase = "canonical"+ handler_response_header_name_case: HeaderNameCase = "canonical"def test_not_configured_without_reactor() -> None:diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.pyindex afff60aea..9d1a3dbbc 100644--- a/tests/utils/bases/download_handlers_http.py+++ b/tests/utils/bases/download_handlers_http.py@@ -53,6 +53,7 @@ from tests import IDNA_REJECTED_HOSTNAMES, NON_EXISTING_RESOLVABLEfrom tests.mockserver.mitm_proxy import wrong_credentialsfrom tests.mockserver.proxy_echo import ProxyEchoMockServerfrom tests.mockserver.proxy_stalling import StallingProxy+from tests.mockserver.raw_http import RawHttpServerfrom tests.mockserver.simple_https import SimpleMockServerfrom tests.spiders import (BytesReceivedCallbackSpider,@@ -75,6 +76,7 @@ if TYPE_CHECKING:BadHeaderHandling = Literal["skip-bad", "skip-rest", "fail"]NonUtf8RequestHeaderHandling = Literal["send", "replace"]+HeaderNameCase = Literal["as-is", "canonical"]class TestHttpBase(ABC):@@ -105,6 +107,15 @@ class TestHttpBase(ABC):# follow it;# "fail": the response cannot be downloaded at all.handler_bad_header_handling: BadHeaderHandling = "skip-bad"+ # How the handler writes request header names over HTTP/1.1, compared to+ # their spelling in Request.headers:+ # "as-is": unchanged;+ # "canonical": in the canonical form of Twisted's Headers, e.g. "X-Api-Key"+ # for "x-API-key" and "DNT" for "dnt".+ handler_request_header_name_case: HeaderNameCase = "as-is"+ # How the handler spells response header names in Response.headers,+ # compared to their spelling on the wire, with the same options as above.+ handler_response_header_name_case: HeaderNameCase = "as-is"# default headers added by the underlying library that cannot be suppressedalways_present_req_headers: ClassVar[frozenset[str]] = frozenset()default_handler_settings: ClassVar[dict[str, Any]] = {}@@ -397,6 +408,50 @@ class TestHttpBase(ABC):assert received == [b"caf\xef\xbf\xbd" if replaced else b"caf\xe9"]assert ("is not valid UTF-8" in caplog.text) == replaced+ @coroutine_test+ async def test_request_header_name_case(self) -> None:+ if self.is_secure:+ pytest.skip("RawHttpServer only supports plain HTTP")+ with RawHttpServer() as server:+ request = Request(server.url, headers={"x-API-key": "a", "dnt": "1"})+ async with self.get_dh() as download_handler:+ await download_handler.download_request(request)+ sent = sorted(+ name+ for name in server.request_header_names()+ if name.lower() in {b"x-api-key", b"dnt"}+ )+ expected = {+ "as-is": [b"dnt", b"x-API-key"],+ "canonical": [b"DNT", b"X-Api-Key"],+ }+ assert sent == expected[self.handler_request_header_name_case]++ @coroutine_test+ async def test_response_header_name_case(self) -> None:+ if self.is_secure:+ pytest.skip("RawHttpServer only supports plain HTTP")+ response_headers = [+ (b"x-custom-HEADER", b"a"),+ (b"etag", b'"b"'),+ (b"X-Custom-Header", b"c"),+ ]+ with RawHttpServer(response_headers) as server:+ async with self.get_dh() as download_handler:+ response = await download_handler.download_request(Request(server.url))+ received = sorted(+ name+ for name in response.headers+ if name.lower() in {b"x-custom-header", b"etag"}+ )+ expected = {+ # differently-cased names are stored with the first spelling+ "as-is": [b"etag", b"x-custom-HEADER"],+ "canonical": [b"ETag", b"X-Custom-Header"],+ }+ assert received == expected[self.handler_response_header_name_case]+ assert response.headers.getlist("X-Custom-Header") == [b"a", b"c"]+@coroutine_testasync def test_server_receives_no_extra_headers(self, mockserver: MockServer