Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Correctly count newlines in header sizes. (#8271)

Andrey Rakhmatullin949a61727978
diff --git a/scrapy/downloadermiddlewares/stats.py b/scrapy/downloadermiddlewares/stats.py
index 267f9ca77..93a619a95 100644
--- a/scrapy/downloadermiddlewares/stats.py
+++ b/scrapy/downloadermiddlewares/stats.py
@@ -23,8 +23,8 @@ def get_header_size(
for key, value in headers.items():
if isinstance(value, (list, tuple)):
for v in value:
- size += len(b": ") + len(key) + len(v)
- return size + len(b"\r\n") * (len(headers.keys()) - 1)
+ size += len(b": ") + len(key) + len(v) + len(b"\r\n")
+ return size
def get_status_size(response_status: int) -> int:
@@ -62,9 +62,8 @@ class DownloaderStats:
len(response.body)
+ get_header_size(response.headers)
+ get_status_size(response.status)
- + 4
+ + len(b"\r\n") # the empty line after the headers
)
- # response.body + b"\r\n"+ response.header + b"\r\n" + response.status
self.stats.inc_value("downloader/response_bytes", reslen)
return response
diff --git a/tests/test_downloadermiddleware_stats.py b/tests/test_downloadermiddleware_stats.py
index cd7a61301..918f6b28b 100644
--- a/tests/test_downloadermiddleware_stats.py
+++ b/tests/test_downloadermiddleware_stats.py
@@ -40,6 +40,27 @@ class TestDownloaderStats:
self.mw.process_response(self.req, self.res)
self.assertStatsEqual("downloader/response_count", 1)
+ @pytest.mark.parametrize(
+ ("headers", "raw_response"),
+ [
+ ({}, b"HTTP/1.1 200 OK\r\n\r\nbody"),
+ ({"A": "1"}, b"HTTP/1.1 200 OK\r\nA: 1\r\n\r\nbody"),
+ (
+ [("Set-Cookie", "a=1"), ("Set-Cookie", "b=2")],
+ b"HTTP/1.1 200 OK\r\nSet-Cookie: a=1\r\nSet-Cookie: b=2\r\n\r\nbody",
+ ),
+ ({"A": "1", "B": None}, b"HTTP/1.1 200 OK\r\nA: 1\r\n\r\nbody"),
+ ],
+ )
+ def test_response_bytes(
+ self,
+ headers: dict[str, str | None] | list[tuple[str, str]],
+ raw_response: bytes,
+ ) -> None:
+ res = Response("http://scrapytest.org", headers=headers, body=b"body")
+ self.mw.process_response(self.req, res)
+ self.assertStatsEqual("downloader/response_bytes", len(raw_response))
+
def test_process_exception(self) -> None:
self.mw.process_exception(self.req, MyException())
self.assertStatsEqual("downloader/exception_count", 1)