| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import gzip |
| 4 |
import io |
| 5 |
import typing |
| 6 |
from test import LONG_TIMEOUT |
| 7 |
from unittest import mock |
| 8 |
|
| 9 |
import pytest |
| 10 |
|
| 11 |
from dummyserver.socketserver import HAS_IPV6 |
| 12 |
from dummyserver.testcase import ( |
| 13 |
HypercornDummyServerTestCase, |
| 14 |
IPv6HypercornDummyServerTestCase, |
| 15 |
) |
| 16 |
from urllib3 import HTTPHeaderDict, HTTPResponse, request |
| 17 |
from urllib3.connectionpool import port_by_scheme |
| 18 |
from urllib3.exceptions import MaxRetryError, URLSchemeUnknown |
| 19 |
from urllib3.poolmanager import PoolManager |
| 20 |
from urllib3.util.retry import Retry |
| 21 |
|
| 22 |
|
| 23 |
class TestPoolManager(HypercornDummyServerTestCase): |
| 24 |
@classmethod |
| 25 |
def setup_class(cls) -> None: |
| 26 |
super().setup_class() |
| 27 |
cls.base_url = f"http://{cls.host}:{cls.port}" |
| 28 |
cls.base_url_alt = f"http://{cls.host_alt}:{cls.port}" |
| 29 |
|
| 30 |
@pytest.mark.parametrize( |
| 31 |
"pool_manager_kwargs", |
| 32 |
({}, {"retries": None}, {"retries": 1}, {"retries": Retry(1)}), |
| 33 |
) |
| 34 |
def test_redirect(self, pool_manager_kwargs: dict[str, typing.Any]) -> None: |
| 35 |
with PoolManager(**pool_manager_kwargs) as http: |
| 36 |
r = http.request( |
| 37 |
"GET", |
| 38 |
f"{self.base_url}/redirect", |
| 39 |
fields={"target": f"{self.base_url}/"}, |
| 40 |
redirect=False, |
| 41 |
) |
| 42 |
|
| 43 |
assert r.status == 303 |
| 44 |
|
| 45 |
r = http.request( |
| 46 |
"GET", |
| 47 |
f"{self.base_url}/redirect", |
| 48 |
fields={"target": f"{self.base_url}/"}, |
| 49 |
) |
| 50 |
|
| 51 |
assert r.status == 200 |
| 52 |
assert r.data == b"Dummy server!" |
| 53 |
|
| 54 |
@pytest.mark.parametrize( |
| 55 |
"pool_manager_kwargs", |
| 56 |
({}, {"retries": None}, {"retries": 2}, {"retries": Retry(2)}), |
| 57 |
) |
| 58 |
def test_redirect_twice(self, pool_manager_kwargs: dict[str, typing.Any]) -> None: |
| 59 |
with PoolManager(**pool_manager_kwargs) as http: |
| 60 |
r = http.request( |
| 61 |
"GET", |
| 62 |
f"{self.base_url}/redirect", |
| 63 |
fields={"target": f"{self.base_url}/redirect"}, |
| 64 |
redirect=False, |
| 65 |
) |
| 66 |
|
| 67 |
assert r.status == 303 |
| 68 |
|
| 69 |
r = http.request( |
| 70 |
"GET", |
| 71 |
f"{self.base_url}/redirect", |
| 72 |
fields={"target": f"{self.base_url}/redirect?target={self.base_url}/"}, |
| 73 |
) |
| 74 |
|
| 75 |
assert r.status == 200 |
| 76 |
assert r.data == b"Dummy server!" |
| 77 |
|
| 78 |
def test_redirect_to_relative_url(self) -> None: |
| 79 |
with PoolManager() as http: |
| 80 |
r = http.request( |
| 81 |
"GET", |
| 82 |
f"{self.base_url}/redirect", |
| 83 |
fields={"target": "/redirect"}, |
| 84 |
redirect=False, |
| 85 |
) |
| 86 |
|
| 87 |
assert r.status == 303 |
| 88 |
|
| 89 |
r = http.request( |
| 90 |
"GET", f"{self.base_url}/redirect", fields={"target": "/redirect"} |
| 91 |
) |
| 92 |
|
| 93 |
assert r.status == 200 |
| 94 |
assert r.data == b"Dummy server!" |
| 95 |
|
| 96 |
@pytest.mark.parametrize( |
| 97 |
"retries", |
| 98 |
(0, Retry(total=0), Retry(redirect=0), Retry(total=0, redirect=0)), |
| 99 |
) |
| 100 |
def test_redirects_disabled_for_pool_manager_with_0( |
| 101 |
self, retries: typing.Literal[0] | Retry |
| 102 |
) -> None: |
| 103 |
""" |
| 104 |
Check handling redirects when retries is set to 0 on the pool |
| 105 |
manager. |
| 106 |
""" |
| 107 |
with PoolManager(retries=retries) as http: |
| 108 |
with pytest.raises(MaxRetryError): |
| 109 |
http.request("GET", f"{self.base_url}/redirect") |
| 110 |
|
| 111 |
# Setting redirect=True should not change the behavior. |
| 112 |
with pytest.raises(MaxRetryError): |
| 113 |
http.request("GET", f"{self.base_url}/redirect", redirect=True) |
| 114 |
|
| 115 |
# Setting redirect=False should not make it follow the redirect, |
| 116 |
# but MaxRetryError should not be raised. |
| 117 |
response = http.request("GET", f"{self.base_url}/redirect", redirect=False) |
| 118 |
assert response.status == 303 |
| 119 |
|
| 120 |
@pytest.mark.parametrize( |
| 121 |
"retries", |
| 122 |
( |
| 123 |
False, |
| 124 |
Retry(total=False), |
| 125 |
Retry(redirect=False), |
| 126 |
Retry(total=False, redirect=False), |
| 127 |
), |
| 128 |
) |
| 129 |
def test_redirects_disabled_for_pool_manager_with_false( |
| 130 |
self, retries: typing.Literal[False] | Retry |
| 131 |
) -> None: |
| 132 |
""" |
| 133 |
Check that setting retries set to False on the pool manager disables |
| 134 |
raising MaxRetryError and redirect=True does not change the |
| 135 |
behavior. |
| 136 |
""" |
| 137 |
with PoolManager(retries=retries) as http: |
| 138 |
response = http.request("GET", f"{self.base_url}/redirect") |
| 139 |
assert response.status == 303 |
| 140 |
|
| 141 |
response = http.request("GET", f"{self.base_url}/redirect", redirect=True) |
| 142 |
assert response.status == 303 |
| 143 |
|
| 144 |
response = http.request("GET", f"{self.base_url}/redirect", redirect=False) |
| 145 |
assert response.status == 303 |
| 146 |
|
| 147 |
def test_redirects_disabled_for_individual_request(self) -> None: |
| 148 |
""" |
| 149 |
Check handling redirects when they are meant to be disabled |
| 150 |
on the request level. |
| 151 |
""" |
| 152 |
with PoolManager() as http: |
| 153 |
# Check when redirect is not passed. |
| 154 |
with pytest.raises(MaxRetryError): |
| 155 |
http.request("GET", f"{self.base_url}/redirect", retries=0) |
| 156 |
response = http.request("GET", f"{self.base_url}/redirect", retries=False) |
| 157 |
assert response.status == 303 |
| 158 |
|
| 159 |
# Check when redirect=True. |
| 160 |
with pytest.raises(MaxRetryError): |
| 161 |
http.request( |
| 162 |
"GET", f"{self.base_url}/redirect", retries=0, redirect=True |
| 163 |
) |
| 164 |
response = http.request( |
| 165 |
"GET", f"{self.base_url}/redirect", retries=False, redirect=True |
| 166 |
) |
| 167 |
assert response.status == 303 |
| 168 |
|
| 169 |
# Check when redirect=False. |
| 170 |
response = http.request( |
| 171 |
"GET", f"{self.base_url}/redirect", retries=0, redirect=False |
| 172 |
) |
| 173 |
assert response.status == 303 |
| 174 |
response = http.request( |
| 175 |
"GET", f"{self.base_url}/redirect", retries=False, redirect=False |
| 176 |
) |
| 177 |
assert response.status == 303 |
| 178 |
|
| 179 |
def test_cross_host_redirect(self) -> None: |
| 180 |
with PoolManager() as http: |
| 181 |
cross_host_location = f"{self.base_url_alt}/echo?a=b" |
| 182 |
with pytest.raises(MaxRetryError): |
| 183 |
http.request( |
| 184 |
"GET", |
| 185 |
f"{self.base_url}/redirect", |
| 186 |
fields={"target": cross_host_location}, |
| 187 |
timeout=LONG_TIMEOUT, |
| 188 |
retries=0, |
| 189 |
) |
| 190 |
|
| 191 |
r = http.request( |
| 192 |
"GET", |
| 193 |
f"{self.base_url}/redirect", |
| 194 |
fields={"target": f"{self.base_url_alt}/echo?a=b"}, |
| 195 |
timeout=LONG_TIMEOUT, |
| 196 |
retries=1, |
| 197 |
) |
| 198 |
|
| 199 |
assert isinstance(r, HTTPResponse) |
| 200 |
assert r._pool is not None |
| 201 |
assert r._pool.host == self.host_alt |
| 202 |
|
| 203 |
def test_too_many_redirects(self) -> None: |
| 204 |
with PoolManager() as http: |
| 205 |
with pytest.raises(MaxRetryError): |
| 206 |
http.request( |
| 207 |
"GET", |
| 208 |
f"{self.base_url}/redirect", |
| 209 |
fields={ |
| 210 |
"target": f"{self.base_url}/redirect?target={self.base_url}/" |
| 211 |
}, |
| 212 |
retries=1, |
| 213 |
preload_content=False, |
| 214 |
) |
| 215 |
|
| 216 |
with pytest.raises(MaxRetryError): |
| 217 |
http.request( |
| 218 |
"GET", |
| 219 |
f"{self.base_url}/redirect", |
| 220 |
fields={ |
| 221 |
"target": f"{self.base_url}/redirect?target={self.base_url}/" |
| 222 |
}, |
| 223 |
retries=Retry(total=None, redirect=1), |
| 224 |
preload_content=False, |
| 225 |
) |
| 226 |
|
| 227 |
# Even with preload_content=False and raise on redirects, we reused the same |
| 228 |
# connection |
| 229 |
assert len(http.pools) == 1 |
| 230 |
pool = http.connection_from_host(self.host, self.port) |
| 231 |
assert pool.num_connections == 1 |
| 232 |
|
| 233 |
# Check when retries are configured for the pool manager. |
| 234 |
with PoolManager(retries=1) as http: |
| 235 |
with pytest.raises(MaxRetryError): |
| 236 |
http.request( |
| 237 |
"GET", |
| 238 |
f"{self.base_url}/redirect", |
| 239 |
fields={"target": f"/redirect?target={self.base_url}/"}, |
| 240 |
) |
| 241 |
|
| 242 |
# Here we allow more retries for the request. |
| 243 |
response = http.request( |
| 244 |
"GET", |
| 245 |
f"{self.base_url}/redirect", |
| 246 |
fields={"target": f"/redirect?target={self.base_url}/"}, |
| 247 |
retries=2, |
| 248 |
) |
| 249 |
assert response.status == 200 |
| 250 |
|
| 251 |
def test_redirect_cross_host_remove_headers(self) -> None: |
| 252 |
with PoolManager() as http: |
| 253 |
r = http.request( |
| 254 |
"GET", |
| 255 |
f"{self.base_url}/redirect", |
| 256 |
fields={"target": f"{self.base_url_alt}/headers"}, |
| 257 |
headers={ |
| 258 |
"Authorization": "foo", |
| 259 |
"Proxy-Authorization": "bar", |
| 260 |
"Cookie": "foo=bar", |
| 261 |
}, |
| 262 |
) |
| 263 |
|
| 264 |
assert r.status == 200 |
| 265 |
|
| 266 |
data = r.json() |
| 267 |
|
| 268 |
assert "Authorization" not in data |
| 269 |
assert "Proxy-Authorization" not in data |
| 270 |
assert "Cookie" not in data |
| 271 |
|
| 272 |
r = http.request( |
| 273 |
"GET", |
| 274 |
f"{self.base_url}/redirect", |
| 275 |
fields={"target": f"{self.base_url_alt}/headers"}, |
| 276 |
headers={ |
| 277 |
"authorization": "foo", |
| 278 |
"proxy-authorization": "baz", |
| 279 |
"cookie": "foo=bar", |
| 280 |
}, |
| 281 |
) |
| 282 |
|
| 283 |
assert r.status == 200 |
| 284 |
|
| 285 |
data = r.json() |
| 286 |
|
| 287 |
assert "authorization" not in data |
| 288 |
assert "Authorization" not in data |
| 289 |
assert "proxy-authorization" not in data |
| 290 |
assert "Proxy-Authorization" not in data |
| 291 |
assert "cookie" not in data |
| 292 |
assert "Cookie" not in data |
| 293 |
|
| 294 |
def test_redirect_cross_host_no_remove_headers(self) -> None: |
| 295 |
with PoolManager() as http: |
| 296 |
r = http.request( |
| 297 |
"GET", |
| 298 |
f"{self.base_url}/redirect", |
| 299 |
fields={"target": f"{self.base_url_alt}/headers"}, |
| 300 |
headers={ |
| 301 |
"Authorization": "foo", |
| 302 |
"Proxy-Authorization": "bar", |
| 303 |
"Cookie": "foo=bar", |
| 304 |
}, |
| 305 |
retries=Retry(remove_headers_on_redirect=[]), |
| 306 |
) |
| 307 |
|
| 308 |
assert r.status == 200 |
| 309 |
|
| 310 |
data = r.json() |
| 311 |
|
| 312 |
assert data["Authorization"] == "foo" |
| 313 |
assert data["Proxy-Authorization"] == "bar" |
| 314 |
assert data["Cookie"] == "foo=bar" |
| 315 |
|
| 316 |
def test_redirect_cross_host_set_removed_headers(self) -> None: |
| 317 |
with PoolManager() as http: |
| 318 |
r = http.request( |
| 319 |
"GET", |
| 320 |
f"{self.base_url}/redirect", |
| 321 |
fields={"target": f"{self.base_url_alt}/headers"}, |
| 322 |
headers={ |
| 323 |
"X-API-Secret": "foo", |
| 324 |
"Authorization": "bar", |
| 325 |
"Proxy-Authorization": "baz", |
| 326 |
"Cookie": "foo=bar", |
| 327 |
}, |
| 328 |
retries=Retry(remove_headers_on_redirect=["X-API-Secret"]), |
| 329 |
) |
| 330 |
|
| 331 |
assert r.status == 200 |
| 332 |
|
| 333 |
data = r.json() |
| 334 |
|
| 335 |
assert "X-API-Secret" not in data |
| 336 |
assert data["Authorization"] == "bar" |
| 337 |
assert data["Proxy-Authorization"] == "baz" |
| 338 |
assert data["Cookie"] == "foo=bar" |
| 339 |
|
| 340 |
headers = { |
| 341 |
"x-api-secret": "foo", |
| 342 |
"authorization": "bar", |
| 343 |
"proxy-authorization": "baz", |
| 344 |
"cookie": "foo=bar", |
| 345 |
} |
| 346 |
r = http.request( |
| 347 |
"GET", |
| 348 |
f"{self.base_url}/redirect", |
| 349 |
fields={"target": f"{self.base_url_alt}/headers"}, |
| 350 |
headers=headers, |
| 351 |
retries=Retry(remove_headers_on_redirect=["X-API-Secret"]), |
| 352 |
) |
| 353 |
|
| 354 |
assert r.status == 200 |
| 355 |
|
| 356 |
data = r.json() |
| 357 |
|
| 358 |
assert "x-api-secret" not in data |
| 359 |
assert "X-API-Secret" not in data |
| 360 |
assert data["Authorization"] == "bar" |
| 361 |
assert data["Proxy-Authorization"] == "baz" |
| 362 |
assert data["Cookie"] == "foo=bar" |
| 363 |
|
| 364 |
# Ensure the header argument itself is not modified in-place. |
| 365 |
assert headers == { |
| 366 |
"x-api-secret": "foo", |
| 367 |
"authorization": "bar", |
| 368 |
"proxy-authorization": "baz", |
| 369 |
"cookie": "foo=bar", |
| 370 |
} |
| 371 |
|
| 372 |
def test_redirect_without_preload_releases_connection(self) -> None: |
| 373 |
with PoolManager(block=True, maxsize=2) as http: |
| 374 |
r = http.request("GET", f"{self.base_url}/redirect", preload_content=False) |
| 375 |
assert isinstance(r, HTTPResponse) |
| 376 |
assert r._pool is not None |
| 377 |
assert r._pool.num_requests == 2 |
| 378 |
assert r._pool.num_connections == 1 |
| 379 |
assert len(http.pools) == 1 |
| 380 |
|
| 381 |
def test_303_redirect_makes_request_lose_body(self) -> None: |
| 382 |
with PoolManager() as http: |
| 383 |
response = http.request( |
| 384 |
"POST", |
| 385 |
f"{self.base_url}/redirect", |
| 386 |
fields={ |
| 387 |
"target": f"{self.base_url}/headers_and_params", |
| 388 |
"status": "303 See Other", |
| 389 |
}, |
| 390 |
) |
| 391 |
data = response.json() |
| 392 |
assert data["params"] == {} |
| 393 |
assert "Content-Type" not in HTTPHeaderDict(data["headers"]) |
| 394 |
|
| 395 |
@pytest.mark.parametrize("chunked_via", ["kwarg", "header"]) |
| 396 |
def test_303_redirect_makes_request_lose_body_framing( |
| 397 |
self, chunked_via: str |
| 398 |
) -> None: |
| 399 |
# The body is dropped, so the redirected GET must not keep announcing |
| 400 |
# a chunked body that it is never going to send. |
| 401 |
request_headers: dict[str, str] = {} |
| 402 |
kw: dict[str, typing.Any] = {} |
| 403 |
if chunked_via == "kwarg": |
| 404 |
kw["chunked"] = True |
| 405 |
else: |
| 406 |
request_headers["Transfer-Encoding"] = "chunked" |
| 407 |
with PoolManager() as http: |
| 408 |
response = http.request( |
| 409 |
"POST", |
| 410 |
f"{self.base_url}/redirect?target={self.base_url}/headers_and_params", |
| 411 |
body=iter([b"xxxxxxxx"]), |
| 412 |
headers=request_headers, |
| 413 |
**kw, |
| 414 |
) |
| 415 |
headers = HTTPHeaderDict(response.json()["headers"]) |
| 416 |
assert "Transfer-Encoding" not in headers |
| 417 |
assert "Content-Length" not in headers |
| 418 |
|
| 419 |
def test_303_redirect_with_body_pos(self) -> None: |
| 420 |
# The body is dropped, so the position recorded to rewind it has to go |
| 421 |
# as well, otherwise the redirect tries to rewind a body that is gone. |
| 422 |
with PoolManager() as http: |
| 423 |
response = http.urlopen( |
| 424 |
"POST", |
| 425 |
f"{self.base_url}/redirect?target={self.base_url}/echo", |
| 426 |
body=io.BytesIO(b"the data"), |
| 427 |
headers={"Content-Length": "8"}, |
| 428 |
body_pos=0, |
| 429 |
) |
| 430 |
assert response.status == 200 |
| 431 |
assert response.data == b"" |
| 432 |
|
| 433 |
def test_unknown_scheme(self) -> None: |
| 434 |
with PoolManager() as http: |
| 435 |
unknown_scheme = "unknown" |
| 436 |
unknown_scheme_url = f"{unknown_scheme}://host" |
| 437 |
with pytest.raises(URLSchemeUnknown) as e: |
| 438 |
r = http.request("GET", unknown_scheme_url) |
| 439 |
assert e.value.scheme == unknown_scheme |
| 440 |
r = http.request( |
| 441 |
"GET", |
| 442 |
f"{self.base_url}/redirect", |
| 443 |
fields={"target": unknown_scheme_url}, |
| 444 |
redirect=False, |
| 445 |
) |
| 446 |
assert r.status == 303 |
| 447 |
assert r.headers.get("Location") == unknown_scheme_url |
| 448 |
with pytest.raises(URLSchemeUnknown) as e: |
| 449 |
r = http.request( |
| 450 |
"GET", |
| 451 |
f"{self.base_url}/redirect", |
| 452 |
fields={"target": unknown_scheme_url}, |
| 453 |
) |
| 454 |
assert e.value.scheme == unknown_scheme |
| 455 |
|
| 456 |
def test_raise_on_redirect(self) -> None: |
| 457 |
with PoolManager() as http: |
| 458 |
r = http.request( |
| 459 |
"GET", |
| 460 |
f"{self.base_url}/redirect", |
| 461 |
fields={"target": f"{self.base_url}/redirect?target={self.base_url}/"}, |
| 462 |
retries=Retry(total=None, redirect=1, raise_on_redirect=False), |
| 463 |
) |
| 464 |
|
| 465 |
assert r.status == 303 |
| 466 |
|
| 467 |
def test_raise_on_status(self) -> None: |
| 468 |
with PoolManager() as http: |
| 469 |
with pytest.raises(MaxRetryError): |
| 470 |
# the default is to raise |
| 471 |
r = http.request( |
| 472 |
"GET", |
| 473 |
f"{self.base_url}/status", |
| 474 |
fields={"status": "500 Internal Server Error"}, |
| 475 |
retries=Retry(total=1, status_forcelist=range(500, 600)), |
| 476 |
) |
| 477 |
|
| 478 |
with pytest.raises(MaxRetryError): |
| 479 |
# raise explicitly |
| 480 |
r = http.request( |
| 481 |
"GET", |
| 482 |
f"{self.base_url}/status", |
| 483 |
fields={"status": "500 Internal Server Error"}, |
| 484 |
retries=Retry( |
| 485 |
total=1, status_forcelist=range(500, 600), raise_on_status=True |
| 486 |
), |
| 487 |
) |
| 488 |
|
| 489 |
# don't raise |
| 490 |
r = http.request( |
| 491 |
"GET", |
| 492 |
f"{self.base_url}/status", |
| 493 |
fields={"status": "500 Internal Server Error"}, |
| 494 |
retries=Retry( |
| 495 |
total=1, status_forcelist=range(500, 600), raise_on_status=False |
| 496 |
), |
| 497 |
) |
| 498 |
|
| 499 |
assert r.status == 500 |
| 500 |
|
| 501 |
def test_missing_port(self) -> None: |
| 502 |
# Can a URL that lacks an explicit port like ':80' succeed, or |
| 503 |
# will all such URLs fail with an error? |
| 504 |
|
| 505 |
with PoolManager() as http: |
| 506 |
# By globally adjusting `port_by_scheme` we pretend for a moment |
| 507 |
# that HTTP's default port is not 80, but is the port at which |
| 508 |
# our test server happens to be listening. |
| 509 |
port_by_scheme["http"] = self.port |
| 510 |
try: |
| 511 |
r = http.request("GET", f"http://{self.host}/", retries=0) |
| 512 |
finally: |
| 513 |
port_by_scheme["http"] = 80 |
| 514 |
|
| 515 |
assert r.status == 200 |
| 516 |
assert r.data == b"Dummy server!" |
| 517 |
|
| 518 |
def test_headers(self) -> None: |
| 519 |
with PoolManager(headers={"Foo": "bar"}) as http: |
| 520 |
r = http.request("GET", f"{self.base_url}/headers") |
| 521 |
returned_headers = r.json() |
| 522 |
assert returned_headers.get("Foo") == "bar" |
| 523 |
|
| 524 |
r = http.request("POST", f"{self.base_url}/headers") |
| 525 |
returned_headers = r.json() |
| 526 |
assert returned_headers.get("Foo") == "bar" |
| 527 |
|
| 528 |
r = http.request_encode_url("GET", f"{self.base_url}/headers") |
| 529 |
returned_headers = r.json() |
| 530 |
assert returned_headers.get("Foo") == "bar" |
| 531 |
|
| 532 |
r = http.request_encode_body("POST", f"{self.base_url}/headers") |
| 533 |
returned_headers = r.json() |
| 534 |
assert returned_headers.get("Foo") == "bar" |
| 535 |
|
| 536 |
r = http.request_encode_url( |
| 537 |
"GET", f"{self.base_url}/headers", headers={"Baz": "quux"} |
| 538 |
) |
| 539 |
returned_headers = r.json() |
| 540 |
assert returned_headers.get("Foo") is None |
| 541 |
assert returned_headers.get("Baz") == "quux" |
| 542 |
|
| 543 |
r = http.request_encode_body( |
| 544 |
"GET", f"{self.base_url}/headers", headers={"Baz": "quux"} |
| 545 |
) |
| 546 |
returned_headers = r.json() |
| 547 |
assert returned_headers.get("Foo") is None |
| 548 |
assert returned_headers.get("Baz") == "quux" |
| 549 |
|
| 550 |
def test_headers_http_header_dict(self) -> None: |
| 551 |
# Test uses a list of headers to assert the order |
| 552 |
# that headers are sent in the request too. |
| 553 |
|
| 554 |
headers = HTTPHeaderDict() |
| 555 |
headers.add("Foo", "bar") |
| 556 |
headers.add("Multi", "1") |
| 557 |
headers.add("Baz", "quux") |
| 558 |
headers.add("Multi", "2") |
| 559 |
|
| 560 |
with PoolManager(headers=headers) as http: |
| 561 |
r = http.request("GET", f"{self.base_url}/multi_headers") |
| 562 |
returned_headers = r.json()["headers"] |
| 563 |
assert returned_headers[-4:] == [ |
| 564 |
["Foo", "bar"], |
| 565 |
["Multi", "1"], |
| 566 |
["Multi", "2"], |
| 567 |
["Baz", "quux"], |
| 568 |
] |
| 569 |
|
| 570 |
r = http.request( |
| 571 |
"GET", |
| 572 |
f"{self.base_url}/multi_headers", |
| 573 |
headers={ |
| 574 |
**headers, |
| 575 |
"Extra": "extra", |
| 576 |
"Foo": "new", |
| 577 |
}, |
| 578 |
) |
| 579 |
returned_headers = r.json()["headers"] |
| 580 |
assert returned_headers[-4:] == [ |
| 581 |
["Foo", "new"], |
| 582 |
["Multi", "1, 2"], |
| 583 |
["Baz", "quux"], |
| 584 |
["Extra", "extra"], |
| 585 |
] |
| 586 |
|
| 587 |
def test_merge_headers_with_pool_manager_headers(self) -> None: |
| 588 |
headers = HTTPHeaderDict() |
| 589 |
headers.add("Cookie", "choc-chip") |
| 590 |
headers.add("Cookie", "oatmeal-raisin") |
| 591 |
orig = headers.copy() |
| 592 |
added_headers = {"Cookie": "tim-tam"} |
| 593 |
|
| 594 |
with PoolManager(headers=headers) as http: |
| 595 |
r = http.request( |
| 596 |
"GET", |
| 597 |
f"{self.base_url}/multi_headers", |
| 598 |
headers=typing.cast(HTTPHeaderDict, http.headers) | added_headers, |
| 599 |
) |
| 600 |
returned_headers = r.json()["headers"] |
| 601 |
assert returned_headers[-3:] == [ |
| 602 |
["Cookie", "choc-chip"], |
| 603 |
["Cookie", "oatmeal-raisin"], |
| 604 |
["Cookie", "tim-tam"], |
| 605 |
] |
| 606 |
# make sure the pool headers weren't modified |
| 607 |
assert http.headers == orig |
| 608 |
|
| 609 |
def test_headers_http_multi_header_multipart(self) -> None: |
| 610 |
headers = HTTPHeaderDict() |
| 611 |
headers.add("Multi", "1") |
| 612 |
headers.add("Multi", "2") |
| 613 |
old_headers = headers.copy() |
| 614 |
|
| 615 |
with PoolManager(headers=headers) as http: |
| 616 |
r = http.request( |
| 617 |
"POST", |
| 618 |
f"{self.base_url}/multi_headers", |
| 619 |
fields={"k": "v"}, |
| 620 |
multipart_boundary="b", |
| 621 |
encode_multipart=True, |
| 622 |
) |
| 623 |
returned_headers = r.json()["headers"] |
| 624 |
assert returned_headers[5:] == [ |
| 625 |
["Multi", "1"], |
| 626 |
["Multi", "2"], |
| 627 |
["Content-Type", "multipart/form-data; boundary=b"], |
| 628 |
] |
| 629 |
# Assert that the previous headers weren't modified. |
| 630 |
assert headers == old_headers |
| 631 |
|
| 632 |
# Set a default value for the Content-Type |
| 633 |
headers["Content-Type"] = "multipart/form-data; boundary=b; field=value" |
| 634 |
r = http.request( |
| 635 |
"POST", |
| 636 |
f"{self.base_url}/multi_headers", |
| 637 |
fields={"k": "v"}, |
| 638 |
multipart_boundary="b", |
| 639 |
encode_multipart=True, |
| 640 |
) |
| 641 |
returned_headers = r.json()["headers"] |
| 642 |
assert returned_headers[5:] == [ |
| 643 |
["Multi", "1"], |
| 644 |
["Multi", "2"], |
| 645 |
# Uses the set value, not the one that would be generated. |
| 646 |
["Content-Type", "multipart/form-data; boundary=b; field=value"], |
| 647 |
] |
| 648 |
|
| 649 |
def test_body(self) -> None: |
| 650 |
with PoolManager() as http: |
| 651 |
r = http.request("POST", f"{self.base_url}/echo", body=b"test") |
| 652 |
assert r.data == b"test" |
| 653 |
|
| 654 |
def test_http_with_ssl_keywords(self) -> None: |
| 655 |
with PoolManager(ca_certs="REQUIRED") as http: |
| 656 |
r = http.request("GET", f"http://{self.host}:{self.port}/") |
| 657 |
assert r.status == 200 |
| 658 |
|
| 659 |
def test_http_with_server_hostname(self) -> None: |
| 660 |
with PoolManager(server_hostname="example.com") as http: |
| 661 |
r = http.request("GET", f"http://{self.host}:{self.port}/") |
| 662 |
assert r.status == 200 |
| 663 |
|
| 664 |
def test_http_with_ca_cert_dir(self) -> None: |
| 665 |
with PoolManager(ca_certs="REQUIRED", ca_cert_dir="/nosuchdir") as http: |
| 666 |
r = http.request("GET", f"http://{self.host}:{self.port}/") |
| 667 |
assert r.status == 200 |
| 668 |
|
| 669 |
@pytest.mark.parametrize( |
| 670 |
["target", "expected_target"], |
| 671 |
[ |
| 672 |
# annoyingly quart.request.full_path adds a stray `?` |
| 673 |
("/echo_uri", b"/echo_uri?"), |
| 674 |
("/echo_uri?q=1#fragment", b"/echo_uri?q=1"), |
| 675 |
("/echo_uri?#", b"/echo_uri?"), |
| 676 |
("/echo_uri#!", b"/echo_uri?"), |
| 677 |
("/echo_uri#!#", b"/echo_uri?"), |
| 678 |
("/echo_uri??#", b"/echo_uri??"), |
| 679 |
("/echo_uri?%3f#", b"/echo_uri?%3F"), |
| 680 |
("/echo_uri?%3F#", b"/echo_uri?%3F"), |
| 681 |
("/echo_uri?[]", b"/echo_uri?%5B%5D"), |
| 682 |
], |
| 683 |
) |
| 684 |
def test_encode_http_target(self, target: str, expected_target: bytes) -> None: |
| 685 |
with PoolManager() as http: |
| 686 |
url = f"http://{self.host}:{self.port}{target}" |
| 687 |
r = http.request("GET", url) |
| 688 |
assert r.data == expected_target |
| 689 |
|
| 690 |
def test_top_level_request(self) -> None: |
| 691 |
r = request("GET", f"{self.base_url}/") |
| 692 |
assert r.status == 200 |
| 693 |
assert r.data == b"Dummy server!" |
| 694 |
|
| 695 |
def test_top_level_request_without_keyword_args(self) -> None: |
| 696 |
body = "" |
| 697 |
with pytest.raises(TypeError): |
| 698 |
request("GET", f"{self.base_url}/", body) # type: ignore[misc] |
| 699 |
|
| 700 |
def test_top_level_request_with_body(self) -> None: |
| 701 |
r = request("POST", f"{self.base_url}/echo", body=b"test") |
| 702 |
assert r.status == 200 |
| 703 |
assert r.data == b"test" |
| 704 |
|
| 705 |
def test_top_level_request_with_preload_content(self) -> None: |
| 706 |
r = request("GET", f"{self.base_url}/echo", preload_content=False) |
| 707 |
assert r.status == 200 |
| 708 |
assert r.connection is not None |
| 709 |
r.data |
| 710 |
assert r.connection is None |
| 711 |
|
| 712 |
def test_top_level_request_with_decode_content(self) -> None: |
| 713 |
r = request( |
| 714 |
"GET", |
| 715 |
f"{self.base_url}/encodingrequest", |
| 716 |
headers={"accept-encoding": "gzip"}, |
| 717 |
decode_content=False, |
| 718 |
) |
| 719 |
assert r.status == 200 |
| 720 |
assert gzip.decompress(r.data) == b"hello, world!" |
| 721 |
|
| 722 |
r = request( |
| 723 |
"GET", |
| 724 |
f"{self.base_url}/encodingrequest", |
| 725 |
headers={"accept-encoding": "gzip"}, |
| 726 |
decode_content=True, |
| 727 |
) |
| 728 |
assert r.status == 200 |
| 729 |
assert r.data == b"hello, world!" |
| 730 |
|
| 731 |
def test_top_level_request_with_redirect(self) -> None: |
| 732 |
r = request( |
| 733 |
"GET", |
| 734 |
f"{self.base_url}/redirect", |
| 735 |
fields={"target": f"{self.base_url}/"}, |
| 736 |
redirect=False, |
| 737 |
) |
| 738 |
|
| 739 |
assert r.status == 303 |
| 740 |
|
| 741 |
r = request( |
| 742 |
"GET", |
| 743 |
f"{self.base_url}/redirect", |
| 744 |
fields={"target": f"{self.base_url}/"}, |
| 745 |
redirect=True, |
| 746 |
) |
| 747 |
|
| 748 |
assert r.status == 200 |
| 749 |
assert r.data == b"Dummy server!" |
| 750 |
|
| 751 |
def test_top_level_request_with_retries(self) -> None: |
| 752 |
r = request("GET", f"{self.base_url}/redirect", retries=False) |
| 753 |
assert r.status == 303 |
| 754 |
|
| 755 |
r = request("GET", f"{self.base_url}/redirect", retries=3) |
| 756 |
assert r.status == 200 |
| 757 |
|
| 758 |
def test_top_level_request_with_timeout(self) -> None: |
| 759 |
with mock.patch("urllib3.poolmanager.RequestMethods.request") as mockRequest: |
| 760 |
mockRequest.return_value = HTTPResponse(status=200) |
| 761 |
|
| 762 |
r = request("GET", f"{self.base_url}/redirect", timeout=2.5) |
| 763 |
|
| 764 |
assert r.status == 200 |
| 765 |
|
| 766 |
mockRequest.assert_called_with( |
| 767 |
"GET", |
| 768 |
f"{self.base_url}/redirect", |
| 769 |
body=None, |
| 770 |
fields=None, |
| 771 |
headers=None, |
| 772 |
preload_content=True, |
| 773 |
decode_content=True, |
| 774 |
redirect=True, |
| 775 |
retries=None, |
| 776 |
timeout=2.5, |
| 777 |
json=None, |
| 778 |
) |
| 779 |
|
| 780 |
@pytest.mark.parametrize( |
| 781 |
"headers", |
| 782 |
[ |
| 783 |
None, |
| 784 |
{"content-Type": "application/json"}, |
| 785 |
{"content-Type": "text/plain"}, |
| 786 |
{"attribute": "value", "CONTENT-TYPE": "application/json"}, |
| 787 |
HTTPHeaderDict(cookie="foo, bar"), |
| 788 |
], |
| 789 |
) |
| 790 |
def test_request_with_json(self, headers: HTTPHeaderDict) -> None: |
| 791 |
old_headers = None if headers is None else headers.copy() |
| 792 |
body = {"attribute": "value"} |
| 793 |
r = request( |
| 794 |
method="POST", url=f"{self.base_url}/echo_json", headers=headers, json=body |
| 795 |
) |
| 796 |
assert r.status == 200 |
| 797 |
assert r.json() == body |
| 798 |
content_type = HTTPHeaderDict(old_headers).get( |
| 799 |
"Content-Type", "application/json" |
| 800 |
) |
| 801 |
assert content_type in r.headers["Content-Type"].replace(" ", "").split(",") |
| 802 |
|
| 803 |
# Ensure the header argument itself is not modified in-place. |
| 804 |
assert headers == old_headers |
| 805 |
|
| 806 |
def test_top_level_request_with_json_with_httpheaderdict(self) -> None: |
| 807 |
body = {"attribute": "value"} |
| 808 |
header = HTTPHeaderDict(cookie="foo, bar") |
| 809 |
with PoolManager(headers=header) as http: |
| 810 |
r = http.request(method="POST", url=f"{self.base_url}/echo_json", json=body) |
| 811 |
assert r.status == 200 |
| 812 |
assert r.json() == body |
| 813 |
assert "application/json" in r.headers["Content-Type"].replace( |
| 814 |
" ", "" |
| 815 |
).split(",") |
| 816 |
|
| 817 |
def test_top_level_request_with_body_and_json(self) -> None: |
| 818 |
match = "request got values for both 'body' and 'json' parameters which are mutually exclusive" |
| 819 |
with pytest.raises(TypeError, match=match): |
| 820 |
body = {"attribute": "value"} |
| 821 |
request(method="POST", url=f"{self.base_url}/echo", body="", json=body) |
| 822 |
|
| 823 |
def test_top_level_request_with_invalid_body(self) -> None: |
| 824 |
class BadBody: |
| 825 |
def __repr__(self) -> str: |
| 826 |
return "<BadBody>" |
| 827 |
|
| 828 |
with pytest.raises(TypeError) as e: |
| 829 |
request( |
| 830 |
method="POST", |
| 831 |
url=f"{self.base_url}/echo", |
| 832 |
body=BadBody(), # type: ignore[arg-type] |
| 833 |
) |
| 834 |
assert str(e.value) == ( |
| 835 |
"'body' must be a bytes-like object, file-like " |
| 836 |
"object, or iterable. Instead was <BadBody>" |
| 837 |
) |
| 838 |
|
| 839 |
|
| 840 |
@pytest.mark.skipif(not HAS_IPV6, reason="IPv6 is not supported on this system") |
| 841 |
class TestIPv6PoolManager(IPv6HypercornDummyServerTestCase): |
| 842 |
@classmethod |
| 843 |
def setup_class(cls) -> None: |
| 844 |
super().setup_class() |
| 845 |
cls.base_url = f"http://[{cls.host}]:{cls.port}" |
| 846 |
|
| 847 |
def test_ipv6(self) -> None: |
| 848 |
with PoolManager() as http: |
| 849 |
http.request("GET", self.base_url) |