| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import io |
| 4 |
import socket |
| 5 |
import typing |
| 6 |
|
| 7 |
import pytest |
| 8 |
|
| 9 |
from dummyserver.testcase import ( |
| 10 |
ConnectionMarker, |
| 11 |
SocketDummyServerTestCase, |
| 12 |
consume_socket, |
| 13 |
) |
| 14 |
from urllib3 import HTTPConnectionPool |
| 15 |
from urllib3.util import SKIP_HEADER |
| 16 |
from urllib3.util.retry import Retry |
| 17 |
|
| 18 |
|
| 19 |
class TestChunkedTransfer(SocketDummyServerTestCase): |
| 20 |
def start_chunked_handler(self) -> None: |
| 21 |
self.buffer = b"" |
| 22 |
|
| 23 |
def socket_handler(listener: socket.socket) -> None: |
| 24 |
sock = listener.accept()[0] |
| 25 |
|
| 26 |
while not self.buffer.endswith(b"\r\n0\r\n\r\n"): |
| 27 |
self.buffer += sock.recv(65536) |
| 28 |
|
| 29 |
sock.send( |
| 30 |
b"HTTP/1.1 200 OK\r\n" |
| 31 |
b"Content-type: text/plain\r\n" |
| 32 |
b"Content-Length: 0\r\n" |
| 33 |
b"\r\n" |
| 34 |
) |
| 35 |
sock.close() |
| 36 |
|
| 37 |
self._start_server(socket_handler) |
| 38 |
|
| 39 |
@pytest.mark.parametrize( |
| 40 |
"chunks", |
| 41 |
[ |
| 42 |
["foo", "bar", "", "bazzzzzzzzzzzzzzzzzzzzzz"], |
| 43 |
[b"foo", b"bar", b"", b"bazzzzzzzzzzzzzzzzzzzzzz"], |
| 44 |
], |
| 45 |
) |
| 46 |
def test_chunks(self, chunks: list[bytes | str]) -> None: |
| 47 |
self.start_chunked_handler() |
| 48 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 49 |
pool.urlopen("GET", "/", body=chunks, headers=dict(DNT="1"), chunked=True) |
| 50 |
|
| 51 |
assert b"Transfer-Encoding" in self.buffer |
| 52 |
body = self.buffer.split(b"\r\n\r\n", 1)[1] |
| 53 |
lines = body.split(b"\r\n") |
| 54 |
# Empty chunks should have been skipped, as this could not be distinguished |
| 55 |
# from terminating the transmission |
| 56 |
for i, chunk in enumerate( |
| 57 |
[c.decode() if isinstance(c, bytes) else c for c in chunks if c] |
| 58 |
): |
| 59 |
assert lines[i * 2] == hex(len(chunk))[2:].encode("utf-8") |
| 60 |
assert lines[i * 2 + 1] == chunk.encode("utf-8") |
| 61 |
|
| 62 |
def _test_body( |
| 63 |
self, |
| 64 |
data: ( |
| 65 |
bytes |
| 66 |
| str |
| 67 |
| io.BytesIO |
| 68 |
| io.StringIO |
| 69 |
| typing.Iterable[bytes] |
| 70 |
| typing.Iterable[str] |
| 71 |
| None |
| 72 |
), |
| 73 |
expected_data: bytes | None = None, |
| 74 |
) -> None: |
| 75 |
self.start_chunked_handler() |
| 76 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 77 |
pool.urlopen("GET", "/", body=data, chunked=True) |
| 78 |
header, body = self.buffer.split(b"\r\n\r\n", 1) |
| 79 |
|
| 80 |
assert b"Transfer-Encoding: chunked" in header.split(b"\r\n") |
| 81 |
if data: |
| 82 |
if expected_data is not None: |
| 83 |
bdata = expected_data |
| 84 |
else: |
| 85 |
assert isinstance(data, (bytes, str)) |
| 86 |
bdata = data if isinstance(data, bytes) else data.encode("utf-8") |
| 87 |
assert b"\r\n" + bdata + b"\r\n" in body |
| 88 |
assert body.endswith(b"\r\n0\r\n\r\n") |
| 89 |
|
| 90 |
len_str = body.split(b"\r\n", 1)[0] |
| 91 |
stated_len = int(len_str, 16) |
| 92 |
assert stated_len == len(bdata) |
| 93 |
else: |
| 94 |
assert body == b"0\r\n\r\n" |
| 95 |
|
| 96 |
def test_bytestring_body(self) -> None: |
| 97 |
self._test_body(b"thisshouldbeonechunk\r\nasdf") |
| 98 |
|
| 99 |
def test_unicode_body(self) -> None: |
| 100 |
self._test_body( |
| 101 |
"thisshouldbeonechunk\r\näöüß\xff", |
| 102 |
expected_data=b"thisshouldbeonechunk\r\n\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\xc3\xbf", |
| 103 |
) |
| 104 |
|
| 105 |
@pytest.mark.parametrize( |
| 106 |
"bytes_data", |
| 107 |
[ |
| 108 |
b"thisshouldbeonechunk\r\n\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\xc3\xbf", # utf-8 |
| 109 |
b"thisshouldbeonechunk\r\n\xe4\xf6\xfc\xdf\xff", # latin-1 |
| 110 |
], |
| 111 |
) |
| 112 |
def test_bytes_body_fileio(self, bytes_data: bytes) -> None: |
| 113 |
self._test_body(io.BytesIO(bytes_data), expected_data=bytes_data) |
| 114 |
|
| 115 |
def test_unicode_body_fileio(self) -> None: |
| 116 |
self._test_body( |
| 117 |
io.StringIO("thisshouldbeonechunk\r\näöüß\xff"), |
| 118 |
expected_data=b"thisshouldbeonechunk\r\n\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\xc3\xbf", |
| 119 |
) |
| 120 |
|
| 121 |
@pytest.mark.parametrize( |
| 122 |
"bytes_data", |
| 123 |
[ |
| 124 |
b"thisshouldbeonechunk\r\n\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\xc3\xbf", # utf-8 |
| 125 |
b"thisshouldbeonechunk\r\n\xe4\xf6\xfc\xdf\xff", # latin-1 |
| 126 |
], |
| 127 |
) |
| 128 |
def test_bytes_body_iterable(self, bytes_data: bytes) -> None: |
| 129 |
def send_body() -> typing.Iterable[bytes]: |
| 130 |
yield bytes_data |
| 131 |
|
| 132 |
self._test_body(send_body(), expected_data=bytes_data) |
| 133 |
|
| 134 |
def test_unicode_body_iterable(self) -> None: |
| 135 |
def send_body() -> typing.Iterable[str]: |
| 136 |
yield "thisshouldbeonechunk\r\näöüß\xff" |
| 137 |
|
| 138 |
self._test_body( |
| 139 |
send_body(), |
| 140 |
expected_data=b"thisshouldbeonechunk\r\n\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\xc3\xbf", |
| 141 |
) |
| 142 |
|
| 143 |
def test_empty_body(self) -> None: |
| 144 |
self._test_body(None) |
| 145 |
|
| 146 |
def test_empty_string_body(self) -> None: |
| 147 |
self._test_body("") |
| 148 |
|
| 149 |
def test_empty_iterable_body(self) -> None: |
| 150 |
self._test_body(None) |
| 151 |
|
| 152 |
def _get_header_lines(self, prefix: bytes) -> list[bytes]: |
| 153 |
header_block = self.buffer.split(b"\r\n\r\n", 1)[0].lower() |
| 154 |
header_lines = header_block.split(b"\r\n")[1:] |
| 155 |
return [x for x in header_lines if x.startswith(prefix)] |
| 156 |
|
| 157 |
def test_removes_duplicate_host_header(self) -> None: |
| 158 |
self.start_chunked_handler() |
| 159 |
chunks = [b"foo", b"bar", b"", b"bazzzzzzzzzzzzzzzzzzzzzz"] |
| 160 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 161 |
pool.urlopen( |
| 162 |
"GET", "/", body=chunks, headers={"Host": "test.org"}, chunked=True |
| 163 |
) |
| 164 |
|
| 165 |
host_headers = self._get_header_lines(b"host") |
| 166 |
assert len(host_headers) == 1 |
| 167 |
|
| 168 |
def test_provides_default_host_header(self) -> None: |
| 169 |
self.start_chunked_handler() |
| 170 |
chunks = [b"foo", b"bar", b"", b"bazzzzzzzzzzzzzzzzzzzzzz"] |
| 171 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 172 |
pool.urlopen("GET", "/", body=chunks, chunked=True) |
| 173 |
|
| 174 |
host_headers = self._get_header_lines(b"host") |
| 175 |
assert len(host_headers) == 1 |
| 176 |
|
| 177 |
def test_provides_default_user_agent_header(self) -> None: |
| 178 |
self.start_chunked_handler() |
| 179 |
chunks = [b"foo", b"bar", b"", b"bazzzzzzzzzzzzzzzzzzzzzz"] |
| 180 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 181 |
pool.urlopen("GET", "/", body=chunks, chunked=True) |
| 182 |
|
| 183 |
ua_headers = self._get_header_lines(b"user-agent") |
| 184 |
assert len(ua_headers) == 1 |
| 185 |
|
| 186 |
def test_preserve_user_agent_header(self) -> None: |
| 187 |
self.start_chunked_handler() |
| 188 |
chunks = [b"foo", b"bar", b"", b"bazzzzzzzzzzzzzzzzzzzzzz"] |
| 189 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 190 |
pool.urlopen( |
| 191 |
"GET", |
| 192 |
"/", |
| 193 |
body=chunks, |
| 194 |
headers={"user-Agent": "test-agent"}, |
| 195 |
chunked=True, |
| 196 |
) |
| 197 |
|
| 198 |
ua_headers = self._get_header_lines(b"user-agent") |
| 199 |
# Validate that there is only one User-Agent header. |
| 200 |
assert len(ua_headers) == 1 |
| 201 |
# Validate that the existing User-Agent header is the one that was |
| 202 |
# provided. |
| 203 |
assert ua_headers[0] == b"user-agent: test-agent" |
| 204 |
|
| 205 |
def test_remove_user_agent_header(self) -> None: |
| 206 |
self.start_chunked_handler() |
| 207 |
chunks = [b"foo", b"bar", b"", b"bazzzzzzzzzzzzzzzzzzzzzz"] |
| 208 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 209 |
pool.urlopen( |
| 210 |
"GET", |
| 211 |
"/", |
| 212 |
body=chunks, |
| 213 |
headers={"User-Agent": SKIP_HEADER}, |
| 214 |
chunked=True, |
| 215 |
) |
| 216 |
|
| 217 |
ua_headers = self._get_header_lines(b"user-agent") |
| 218 |
assert len(ua_headers) == 0 |
| 219 |
|
| 220 |
def test_provides_default_transfer_encoding_header(self) -> None: |
| 221 |
self.start_chunked_handler() |
| 222 |
chunks = [b"foo", b"bar", b"", b"bazzzzzzzzzzzzzzzzzzzzzz"] |
| 223 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 224 |
pool.urlopen("GET", "/", body=chunks, chunked=True) |
| 225 |
|
| 226 |
te_headers = self._get_header_lines(b"transfer-encoding") |
| 227 |
assert len(te_headers) == 1 |
| 228 |
|
| 229 |
def test_preserve_transfer_encoding_header(self) -> None: |
| 230 |
self.start_chunked_handler() |
| 231 |
chunks = [b"foo", b"bar", b"", b"bazzzzzzzzzzzzzzzzzzzzzz"] |
| 232 |
with HTTPConnectionPool(self.host, self.port, retries=False) as pool: |
| 233 |
pool.urlopen( |
| 234 |
"GET", |
| 235 |
"/", |
| 236 |
body=chunks, |
| 237 |
headers={"transfer-Encoding": "test-transfer-encoding"}, |
| 238 |
chunked=True, |
| 239 |
) |
| 240 |
|
| 241 |
te_headers = self._get_header_lines(b"transfer-encoding") |
| 242 |
# Validate that there is only one Transfer-Encoding header. |
| 243 |
assert len(te_headers) == 1 |
| 244 |
# Validate that the existing Transfer-Encoding header is the one that |
| 245 |
# was provided. |
| 246 |
assert te_headers[0] == b"transfer-encoding: test-transfer-encoding" |
| 247 |
|
| 248 |
def test_preserve_chunked_on_retry_after(self) -> None: |
| 249 |
self.chunked_requests = 0 |
| 250 |
self.socks: list[socket.socket] = [] |
| 251 |
|
| 252 |
def socket_handler(listener: socket.socket) -> None: |
| 253 |
for _ in range(2): |
| 254 |
sock = listener.accept()[0] |
| 255 |
self.socks.append(sock) |
| 256 |
request = consume_socket(sock) |
| 257 |
if b"Transfer-Encoding: chunked" in request.split(b"\r\n"): |
| 258 |
self.chunked_requests += 1 |
| 259 |
|
| 260 |
sock.send( |
| 261 |
b"HTTP/1.1 429 Too Many Requests\r\n" |
| 262 |
b"Content-Type: text/plain\r\n" |
| 263 |
b"Retry-After: 1\r\n" |
| 264 |
b"Content-Length: 0\r\n" |
| 265 |
b"Connection: close\r\n" |
| 266 |
b"\r\n" |
| 267 |
) |
| 268 |
|
| 269 |
self._start_server(socket_handler) |
| 270 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 271 |
retries = Retry(total=1) |
| 272 |
pool.urlopen("GET", "/", chunked=True, retries=retries) |
| 273 |
for sock in self.socks: |
| 274 |
sock.close() |
| 275 |
assert self.chunked_requests == 2 |
| 276 |
|
| 277 |
def test_preserve_chunked_on_redirect( |
| 278 |
self, monkeypatch: pytest.MonkeyPatch |
| 279 |
) -> None: |
| 280 |
self.chunked_requests = 0 |
| 281 |
|
| 282 |
def socket_handler(listener: socket.socket) -> None: |
| 283 |
for i in range(2): |
| 284 |
sock = listener.accept()[0] |
| 285 |
request = ConnectionMarker.consume_request(sock) |
| 286 |
if b"Transfer-Encoding: chunked" in request.split(b"\r\n"): |
| 287 |
self.chunked_requests += 1 |
| 288 |
|
| 289 |
if i == 0: |
| 290 |
sock.sendall( |
| 291 |
b"HTTP/1.1 301 Moved Permanently\r\n" |
| 292 |
b"Location: /redirect\r\n\r\n" |
| 293 |
) |
| 294 |
else: |
| 295 |
sock.sendall(b"HTTP/1.1 200 OK\r\n\r\n") |
| 296 |
sock.close() |
| 297 |
|
| 298 |
self._start_server(socket_handler) |
| 299 |
with ConnectionMarker.mark(monkeypatch): |
| 300 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 301 |
retries = Retry(redirect=1) |
| 302 |
pool.urlopen( |
| 303 |
"GET", "/", chunked=True, preload_content=False, retries=retries |
| 304 |
) |
| 305 |
assert self.chunked_requests == 2 |
| 306 |
|
| 307 |
def test_preserve_chunked_on_broken_connection( |
| 308 |
self, monkeypatch: pytest.MonkeyPatch |
| 309 |
) -> None: |
| 310 |
self.chunked_requests = 0 |
| 311 |
|
| 312 |
def socket_handler(listener: socket.socket) -> None: |
| 313 |
for i in range(2): |
| 314 |
sock = listener.accept()[0] |
| 315 |
request = ConnectionMarker.consume_request(sock) |
| 316 |
if b"Transfer-Encoding: chunked" in request.split(b"\r\n"): |
| 317 |
self.chunked_requests += 1 |
| 318 |
|
| 319 |
if i == 0: |
| 320 |
# Bad HTTP version will trigger a connection close |
| 321 |
sock.sendall(b"HTTP/0.5 200 OK\r\n\r\n") |
| 322 |
else: |
| 323 |
sock.sendall(b"HTTP/1.1 200 OK\r\n\r\n") |
| 324 |
sock.close() |
| 325 |
|
| 326 |
self._start_server(socket_handler) |
| 327 |
with ConnectionMarker.mark(monkeypatch): |
| 328 |
with HTTPConnectionPool(self.host, self.port) as pool: |
| 329 |
retries = Retry(read=1) |
| 330 |
pool.urlopen( |
| 331 |
"GET", "/", chunked=True, preload_content=False, retries=retries |
| 332 |
) |
| 333 |
assert self.chunked_requests == 2 |