Debian Codegraph @

tests/test_requests.py

raw ◀ ▶
1 Debian patch touch this file
1 """Tests for Requests."""
2
3 import collections
4 import contextlib
5 import io
6 import json
7 import os
8 import pickle
9 import re
10 import tempfile
11 import threading
12 import warnings
13 from unittest import mock
14
15 import pytest
16 import urllib3
17 from urllib3.util import Timeout as Urllib3Timeout
18
19 import requests
20 from requests.adapters import HTTPAdapter
21 from requests.auth import HTTPDigestAuth, _basic_auth_str
22 from requests.compat import (
23 JSONDecodeError,
24 Morsel,
25 MutableMapping,
26 builtin_str,
27 cookielib,
28 getproxies,
29 is_urllib3_1,
30 urlparse,
31 )
32 from requests.cookies import cookiejar_from_dict, morsel_to_cookie
33 from requests.exceptions import (
34 ChunkedEncodingError,
35 ConnectionError,
36 ConnectTimeout,
37 ContentDecodingError,
38 InvalidHeader,
39 InvalidProxyURL,
40 InvalidSchema,
41 InvalidURL,
42 MissingSchema,
43 ProxyError,
44 ReadTimeout,
45 RequestException,
46 RetryError,
47 Timeout,
48 TooManyRedirects,
49 UnrewindableBodyError,
50 )
51 from requests.exceptions import SSLError as RequestsSSLError
52 from requests.hooks import default_hooks
53 from requests.models import PreparedRequest, urlencode
54 from requests.sessions import SessionRedirectMixin
55 from requests.structures import CaseInsensitiveDict
56
57 from . import SNIMissingWarning
58 from .compat import StringIO
59 from .testserver.server import TLSServer, consume_socket_content
60 from .utils import override_environ
61
62 # Requests to this URL should always fail with a connection timeout (nothing
63 # listening on that port)
64 TARPIT = "http://10.255.255.1"
65
66 # This is to avoid waiting the timeout of using TARPIT
67 INVALID_PROXY = "http://localhost:1"
68
69 try:
70 from ssl import SSLContext
71
72 del SSLContext
73 HAS_MODERN_SSL = True
74 except ImportError:
75 HAS_MODERN_SSL = False
76
77 try:
78 requests.pyopenssl
79 HAS_PYOPENSSL = True
80 except AttributeError:
81 HAS_PYOPENSSL = False
82
83
84 class TestRequests:
85 digest_auth_algo = ("MD5", "SHA-256", "SHA-512")
86
87 def test_entry_points(self):
88 requests.session
89 requests.session().get
90 requests.session().head
91 requests.get
92 requests.head
93 requests.put
94 requests.patch
95 requests.post
96 # Not really an entry point, but people rely on it.
97 from requests.packages.urllib3.poolmanager import PoolManager # noqa:F401
98
99 @pytest.mark.parametrize(
100 "exception, url",
101 (
102 (MissingSchema, "hiwpefhipowhefopw"),
103 (InvalidSchema, "localhost:3128"),
104 (InvalidSchema, "localhost.localdomain:3128/"),
105 (InvalidSchema, "10.122.1.1:3128/"),
106 (InvalidURL, "http://"),
107 (InvalidURL, "http://*example.com"),
108 (InvalidURL, "http://.example.com"),
109 ),
110 )
111 def test_invalid_url(self, exception, url):
112 with pytest.raises(exception):
113 requests.get(url)
114
115 def test_basic_building(self):
116 req = requests.Request()
117 req.url = "http://kennethreitz.org/"
118 req.data = {"life": "42"}
119
120 pr = req.prepare()
121 assert pr.url == req.url
122 assert pr.body == "life=42"
123
124 @pytest.mark.parametrize("method", ("GET", "HEAD"))
125 def test_no_content_length(self, httpbin, method):
126 req = requests.Request(method, httpbin(method.lower())).prepare()
127 assert "Content-Length" not in req.headers
128
129 @pytest.mark.parametrize("method", ("POST", "PUT", "PATCH", "OPTIONS"))
130 def test_no_body_content_length(self, httpbin, method):
131 req = requests.Request(method, httpbin(method.lower())).prepare()
132 assert req.headers["Content-Length"] == "0"
133
134 @pytest.mark.parametrize("method", ("POST", "PUT", "PATCH", "OPTIONS"))
135 def test_empty_content_length(self, httpbin, method):
136 req = requests.Request(method, httpbin(method.lower()), data="").prepare()
137 assert req.headers["Content-Length"] == "0"
138
139 def test_override_content_length(self, httpbin):
140 headers = {"Content-Length": "not zero"}
141 r = requests.Request("POST", httpbin("post"), headers=headers).prepare()
142 assert "Content-Length" in r.headers
143 assert r.headers["Content-Length"] == "not zero"
144
145 def test_path_is_not_double_encoded(self):
146 request = requests.Request("GET", "http://0.0.0.0/get/test case").prepare()
147
148 assert request.path_url == "/get/test%20case"
149
150 @pytest.mark.parametrize(
151 "url, expected",
152 (
153 (
154 "http://example.com/path#fragment",
155 "http://example.com/path?a=b#fragment",
156 ),
157 (
158 "http://example.com/path?key=value#fragment",
159 "http://example.com/path?key=value&a=b#fragment",
160 ),
161 ),
162 )
163 def test_params_are_added_before_fragment(self, url, expected):
164 request = requests.Request("GET", url, params={"a": "b"}).prepare()
165 assert request.url == expected
166
167 def test_params_original_order_is_preserved_by_default(self):
168 param_ordered_dict = collections.OrderedDict(
169 (("z", 1), ("a", 1), ("k", 1), ("d", 1))
170 )
171 session = requests.Session()
172 request = requests.Request(
173 "GET", "http://example.com/", params=param_ordered_dict
174 )
175 prep = session.prepare_request(request)
176 assert prep.url == "http://example.com/?z=1&a=1&k=1&d=1"
177
178 def test_params_bytes_are_encoded(self):
179 request = requests.Request(
180 "GET", "http://example.com", params=b"test=foo"
181 ).prepare()
182 assert request.url == "http://example.com/?test=foo"
183
184 def test_binary_put(self):
185 request = requests.Request(
186 "PUT", "http://example.com", data="ööö".encode()
187 ).prepare()
188 assert isinstance(request.body, bytes)
189
190 def test_whitespaces_are_removed_from_url(self):
191 # Test for issue #3696
192 request = requests.Request("GET", " http://example.com").prepare()
193 assert request.url == "http://example.com/"
194
195 @pytest.mark.parametrize("scheme", ("http://", "HTTP://", "hTTp://", "HttP://"))
196 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):
197 s = requests.Session()
198 s.proxies = getproxies()
199 parts = urlparse(httpbin("get"))
200 url = scheme + parts.netloc + parts.path
201 r = requests.Request("GET", url)
202 r = s.send(r.prepare())
203 assert r.status_code == 200, f"failed for scheme {scheme}"
204
205 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):
206 r = requests.Request("GET", httpbin("get"))
207 s = requests.Session()
208 s.proxies = getproxies()
209
210 r = s.send(r.prepare())
211
212 assert r.status_code == 200
213
214 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):
215 r = requests.get(httpbin("redirect", "1"))
216 assert r.status_code == 200
217 assert r.history[0].status_code == 302
218 assert r.history[0].is_redirect
219
220 def test_redirect_history_no_self_reference(self, httpbin):
221 r = requests.get(httpbin("redirect", "3"))
222 assert r.status_code == 200
223 assert len(r.history) == 3
224 for i, resp in enumerate(r.history):
225 assert resp not in resp.history
226 assert resp.history == r.history[:i]
227
228 def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):
229 r = requests.post(
230 httpbin("redirect-to"),
231 data="test",
232 params={"url": "post", "status_code": 307},
233 )
234 assert r.status_code == 200
235 assert r.history[0].status_code == 307
236 assert r.history[0].is_redirect
237 assert r.json()["data"] == "test"
238
239 def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):
240 byte_str = b"test"
241 r = requests.post(
242 httpbin("redirect-to"),
243 data=io.BytesIO(byte_str),
244 params={"url": "post", "status_code": 307},
245 )
246 assert r.status_code == 200
247 assert r.history[0].status_code == 307
248 assert r.history[0].is_redirect
249 assert r.json()["data"] == byte_str.decode("utf-8")
250
251 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):
252 try:
253 requests.get(httpbin("relative-redirect", "50"))
254 except TooManyRedirects as e:
255 url = httpbin("relative-redirect", "20")
256 assert e.request.url == url
257 assert e.response.url == url
258 assert len(e.response.history) == 30
259 else:
260 pytest.fail("Expected redirect to raise TooManyRedirects but it did not")
261
262 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):
263 s = requests.session()
264 s.max_redirects = 5
265 try:
266 s.get(httpbin("relative-redirect", "50"))
267 except TooManyRedirects as e:
268 url = httpbin("relative-redirect", "45")
269 assert e.request.url == url
270 assert e.response.url == url
271 assert len(e.response.history) == 5
272 else:
273 pytest.fail(
274 "Expected custom max number of redirects to be respected but was not"
275 )
276
277 def test_http_301_changes_post_to_get(self, httpbin):
278 r = requests.post(httpbin("status", "301"))
279 assert r.status_code == 200
280 assert r.request.method == "GET"
281 assert r.history[0].status_code == 301
282 assert r.history[0].is_redirect
283
284 def test_http_301_doesnt_change_head_to_get(self, httpbin):
285 r = requests.head(httpbin("status", "301"), allow_redirects=True)
286 print(r.content)
287 assert r.status_code == 200
288 assert r.request.method == "HEAD"
289 assert r.history[0].status_code == 301
290 assert r.history[0].is_redirect
291
292 def test_http_302_changes_post_to_get(self, httpbin):
293 r = requests.post(httpbin("status", "302"))
294 assert r.status_code == 200
295 assert r.request.method == "GET"
296 assert r.history[0].status_code == 302
297 assert r.history[0].is_redirect
298
299 def test_http_302_doesnt_change_head_to_get(self, httpbin):
300 r = requests.head(httpbin("status", "302"), allow_redirects=True)
301 assert r.status_code == 200
302 assert r.request.method == "HEAD"
303 assert r.history[0].status_code == 302
304 assert r.history[0].is_redirect
305
306 def test_http_303_changes_post_to_get(self, httpbin):
307 r = requests.post(httpbin("status", "303"))
308 assert r.status_code == 200
309 assert r.request.method == "GET"
310 assert r.history[0].status_code == 303
311 assert r.history[0].is_redirect
312
313 def test_http_303_doesnt_change_head_to_get(self, httpbin):
314 r = requests.head(httpbin("status", "303"), allow_redirects=True)
315 assert r.status_code == 200
316 assert r.request.method == "HEAD"
317 assert r.history[0].status_code == 303
318 assert r.history[0].is_redirect
319
320 def test_header_and_body_removal_on_redirect(self, httpbin):
321 purged_headers = ("Content-Length", "Content-Type")
322 ses = requests.Session()
323 req = requests.Request("POST", httpbin("post"), data={"test": "data"})
324 prep = ses.prepare_request(req)
325 resp = ses.send(prep)
326
327 # Mimic a redirect response
328 resp.status_code = 302
329 resp.headers["location"] = "get"
330
331 # Run request through resolve_redirects
332 next_resp = next(ses.resolve_redirects(resp, prep))
333 assert next_resp.request.body is None
334 for header in purged_headers:
335 assert header not in next_resp.request.headers
336
337 def test_transfer_enc_removal_on_redirect(self, httpbin):
338 purged_headers = ("Transfer-Encoding", "Content-Type")
339 ses = requests.Session()
340 req = requests.Request("POST", httpbin("post"), data=(b"x" for x in range(1)))
341 prep = ses.prepare_request(req)
342 assert "Transfer-Encoding" in prep.headers
343
344 # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33
345 resp = requests.Response()
346 resp.raw = io.BytesIO(b"the content")
347 resp.request = prep
348 setattr(resp.raw, "release_conn", lambda *args: args)
349
350 # Mimic a redirect response
351 resp.status_code = 302
352 resp.headers["location"] = httpbin("get")
353
354 # Run request through resolve_redirect
355 next_resp = next(ses.resolve_redirects(resp, prep))
356 assert next_resp.request.body is None
357 for header in purged_headers:
358 assert header not in next_resp.request.headers
359
360 def test_fragment_maintained_on_redirect(self, httpbin):
361 fragment = "#view=edit&token=hunter2"
362 r = requests.get(httpbin("redirect-to?url=get") + fragment)
363
364 assert len(r.history) > 0
365 assert r.history[0].request.url == httpbin("redirect-to?url=get") + fragment
366 assert r.url == httpbin("get") + fragment
367
368 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):
369 heads = {"User-agent": "Mozilla/5.0"}
370
371 r = requests.get(httpbin("user-agent"), headers=heads)
372
373 assert heads["User-agent"] in r.text
374 assert r.status_code == 200
375
376 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):
377 heads = {"User-agent": "Mozilla/5.0"}
378
379 r = requests.get(
380 httpbin("get") + "?test=true", params={"q": "test"}, headers=heads
381 )
382 assert r.status_code == 200
383
384 def test_set_cookie_on_301(self, httpbin):
385 s = requests.session()
386 url = httpbin("cookies/set?foo=bar")
387 s.get(url)
388 assert s.cookies["foo"] == "bar"
389
390 def test_cookie_sent_on_redirect(self, httpbin):
391 s = requests.session()
392 s.get(httpbin("cookies/set?foo=bar"))
393 r = s.get(httpbin("redirect/1")) # redirects to httpbin('get')
394 assert "Cookie" in r.json()["headers"]
395
396 def test_cookie_removed_on_expire(self, httpbin):
397 s = requests.session()
398 s.get(httpbin("cookies/set?foo=bar"))
399 assert s.cookies["foo"] == "bar"
400 s.get(
401 httpbin("response-headers"),
402 params={"Set-Cookie": "foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT"},
403 )
404 assert "foo" not in s.cookies
405
406 def test_cookie_quote_wrapped(self, httpbin):
407 s = requests.session()
408 s.get(httpbin('cookies/set?foo="bar:baz"'))
409 assert s.cookies["foo"] == '"bar:baz"'
410
411 def test_cookie_persists_via_api(self, httpbin):
412 s = requests.session()
413 r = s.get(httpbin("redirect/1"), cookies={"foo": "bar"})
414 assert "foo" in r.request.headers["Cookie"]
415 assert "foo" in r.history[0].request.headers["Cookie"]
416
417 def test_request_cookie_overrides_session_cookie(self, httpbin):
418 s = requests.session()
419 s.cookies["foo"] = "bar"
420 r = s.get(httpbin("cookies"), cookies={"foo": "baz"})
421 assert r.json()["cookies"]["foo"] == "baz"
422 # Session cookie should not be modified
423 assert s.cookies["foo"] == "bar"
424
425 def test_request_cookies_not_persisted(self, httpbin):
426 s = requests.session()
427 s.get(httpbin("cookies"), cookies={"foo": "baz"})
428 # Sending a request with cookies should not add cookies to the session
429 assert not s.cookies
430
431 def test_generic_cookiejar_works(self, httpbin):
432 cj = cookielib.CookieJar()
433 cookiejar_from_dict({"foo": "bar"}, cj)
434 s = requests.session()
435 s.cookies = cj
436 r = s.get(httpbin("cookies"))
437 # Make sure the cookie was sent
438 assert r.json()["cookies"]["foo"] == "bar"
439 # Make sure the session cj is still the custom one
440 assert s.cookies is cj
441
442 def test_param_cookiejar_works(self, httpbin):
443 cj = cookielib.CookieJar()
444 cookiejar_from_dict({"foo": "bar"}, cj)
445 s = requests.session()
446 r = s.get(httpbin("cookies"), cookies=cj)
447 # Make sure the cookie was sent
448 assert r.json()["cookies"]["foo"] == "bar"
449
450 def test_cookielib_cookiejar_on_redirect(self, httpbin):
451 """Tests resolve_redirect doesn't fail when merging cookies
452 with non-RequestsCookieJar cookiejar.
453
454 See GH #3579
455 """
456 cj = cookiejar_from_dict({"foo": "bar"}, cookielib.CookieJar())
457 s = requests.Session()
458 s.cookies = cookiejar_from_dict({"cookie": "tasty"})
459
460 # Prepare request without using Session
461 req = requests.Request("GET", httpbin("headers"), cookies=cj)
462 prep_req = req.prepare()
463
464 # Send request and simulate redirect
465 resp = s.send(prep_req)
466 resp.status_code = 302
467 resp.headers["location"] = httpbin("get")
468 redirects = s.resolve_redirects(resp, prep_req)
469 resp = next(redirects)
470
471 # Verify CookieJar isn't being converted to RequestsCookieJar
472 assert isinstance(prep_req._cookies, cookielib.CookieJar)
473 assert isinstance(resp.request._cookies, cookielib.CookieJar)
474 assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)
475
476 cookies = {}
477 for c in resp.request._cookies:
478 cookies[c.name] = c.value
479 assert cookies["foo"] == "bar"
480 assert cookies["cookie"] == "tasty"
481
482 def test_requests_in_history_are_not_overridden(self, httpbin):
483 resp = requests.get(httpbin("redirect/3"))
484 urls = [r.url for r in resp.history]
485 req_urls = [r.request.url for r in resp.history]
486 assert urls == req_urls
487
488 def test_history_is_always_a_list(self, httpbin):
489 """Show that even with redirects, Response.history is always a list."""
490 resp = requests.get(httpbin("get"))
491 assert isinstance(resp.history, list)
492 resp = requests.get(httpbin("redirect/1"))
493 assert isinstance(resp.history, list)
494 assert not isinstance(resp.history, tuple)
495
496 def test_headers_on_session_with_None_are_not_sent(self, httpbin):
497 """Do not send headers in Session.headers with None values."""
498 ses = requests.Session()
499 ses.headers["Accept-Encoding"] = None
500 req = requests.Request("GET", httpbin("get"))
501 prep = ses.prepare_request(req)
502 assert "Accept-Encoding" not in prep.headers
503
504 def test_headers_preserve_order(self, httpbin):
505 """Preserve order when headers provided as OrderedDict."""
506 ses = requests.Session()
507 ses.headers = collections.OrderedDict()
508 ses.headers["Accept-Encoding"] = "identity"
509 ses.headers["First"] = "1"
510 ses.headers["Second"] = "2"
511 headers = collections.OrderedDict([("Third", "3"), ("Fourth", "4")])
512 headers["Fifth"] = "5"
513 headers["Second"] = "222"
514 req = requests.Request("GET", httpbin("get"), headers=headers)
515 prep = ses.prepare_request(req)
516 items = list(prep.headers.items())
517 assert items[0] == ("Accept-Encoding", "identity")
518 assert items[1] == ("First", "1")
519 assert items[2] == ("Second", "222")
520 assert items[3] == ("Third", "3")
521 assert items[4] == ("Fourth", "4")
522 assert items[5] == ("Fifth", "5")
523
524 @pytest.mark.parametrize("key", ("User-agent", "user-agent"))
525 def test_user_agent_transfers(self, httpbin, key):
526 heads = {key: "Mozilla/5.0 (github.com/psf/requests)"}
527
528 r = requests.get(httpbin("user-agent"), headers=heads)
529 assert heads[key] in r.text
530
531 def test_HTTP_200_OK_HEAD(self, httpbin):
532 r = requests.head(httpbin("get"))
533 assert r.status_code == 200
534
535 def test_HTTP_200_OK_PUT(self, httpbin):
536 r = requests.put(httpbin("put"))
537 assert r.status_code == 200
538
539 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):
540 auth = ("user", "pass")
541 url = httpbin("basic-auth", "user", "pass")
542
543 r = requests.get(url, auth=auth)
544 assert r.status_code == 200
545
546 r = requests.get(url)
547 assert r.status_code == 401
548
549 s = requests.session()
550 s.auth = auth
551 r = s.get(url)
552 assert r.status_code == 200
553
554 @pytest.mark.parametrize(
555 "username, password",
556 (
557 ("user", "pass"),
558 ("имя".encode(), "пароль".encode()),
559 (42, 42),
560 (None, None),
561 ),
562 )
563 def test_set_basicauth(self, httpbin, username, password):
564 auth = (username, password)
565 url = httpbin("get")
566
567 r = requests.Request("GET", url, auth=auth)
568 p = r.prepare()
569
570 assert p.headers["Authorization"] == _basic_auth_str(username, password)
571
572 def test_basicauth_encodes_byte_strings(self):
573 """Ensure b'test' formats as the byte string "test" rather
574 than the unicode string "b'test'" in Python 3.
575 """
576 auth = (b"\xc5\xafsername", b"test\xc6\xb6")
577 r = requests.Request("GET", "http://localhost", auth=auth)
578 p = r.prepare()
579
580 assert p.headers["Authorization"] == "Basic xa9zZXJuYW1lOnRlc3TGtg=="
581
582 @pytest.mark.parametrize(
583 "url, exception",
584 (
585 # Connecting to an unknown domain should raise a ConnectionError
586 ("http://doesnotexist.google.com", ConnectionError),
587 # Connecting to an invalid port should raise a ConnectionError
588 ("http://localhost:1", ConnectionError),
589 # Inputting a URL that cannot be parsed should raise an InvalidURL error
590 ("http://fe80::5054:ff:fe5a:fc0", InvalidURL),
591 ),
592 )
593 def test_errors(self, url, exception):
•594 with override_environ(http_proxy=None, https_proxy=None):
595 with pytest.raises(exception):
596 requests.get(url, timeout=1)
597
598 def test_proxy_error(self):
599 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError
600 with pytest.raises(ProxyError):
601 requests.get(
602 "http://localhost:1", proxies={"http": "non-resolvable-address"}
603 )
604
605 def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):
606 with pytest.raises(InvalidProxyURL):
607 requests.get(httpbin_secure(), proxies={"https": "http:/badproxyurl:3128"})
608
609 with pytest.raises(InvalidProxyURL):
610 requests.get(httpbin(), proxies={"http": "http://:8080"})
611
612 with pytest.raises(InvalidProxyURL):
613 requests.get(httpbin_secure(), proxies={"https": "https://"})
614
615 with pytest.raises(InvalidProxyURL):
616 requests.get(httpbin(), proxies={"http": "http:///example.com:8080"})
617
618 def test_respect_proxy_env_on_send_self_prepared_request(self, httpbin):
•619 with override_environ(no_proxy=None, http_proxy=INVALID_PROXY):
620 with pytest.raises(ProxyError):
621 session = requests.Session()
622 request = requests.Request("GET", httpbin())
623 session.send(request.prepare())
624
625 def test_respect_proxy_env_on_send_session_prepared_request(self, httpbin):
•626 with override_environ(no_proxy=None, http_proxy=INVALID_PROXY):
627 with pytest.raises(ProxyError):
628 session = requests.Session()
629 request = requests.Request("GET", httpbin())
630 prepared = session.prepare_request(request)
631 session.send(prepared)
632
633 def test_respect_proxy_env_on_send_with_redirects(self, httpbin):
•634 with override_environ(no_proxy=None, http_proxy=INVALID_PROXY):
635 with pytest.raises(ProxyError):
636 session = requests.Session()
637 url = httpbin("redirect/1")
638 print(url)
639 request = requests.Request("GET", url)
640 session.send(request.prepare())
641
642 def test_respect_proxy_env_on_get(self, httpbin):
•643 with override_environ(no_proxy=None, http_proxy=INVALID_PROXY):
644 with pytest.raises(ProxyError):
645 session = requests.Session()
646 session.get(httpbin())
647
648 def test_respect_proxy_env_on_request(self, httpbin):
•649 with override_environ(no_proxy=None, http_proxy=INVALID_PROXY):
650 with pytest.raises(ProxyError):
651 session = requests.Session()
652 session.request(method="GET", url=httpbin())
653
654 def test_proxy_authorization_preserved_on_request(self, httpbin):
655 proxy_auth_value = "Bearer XXX"
656 session = requests.Session()
657 session.headers.update({"Proxy-Authorization": proxy_auth_value})
658 resp = session.request(method="GET", url=httpbin("get"))
659 sent_headers = resp.json().get("headers", {})
660
661 assert sent_headers.get("Proxy-Authorization") == proxy_auth_value
662
663 @pytest.mark.parametrize(
664 "url,has_proxy_auth",
665 (
666 ("http://example.com", True),
667 ("https://example.com", False),
668 ),
669 )
670 def test_proxy_authorization_not_appended_to_https_request(
671 self, url, has_proxy_auth
672 ):
673 session = requests.Session()
674 proxies = {
675 "http": "http://test:pass@localhost:8080",
676 "https": "http://test:pass@localhost:8090",
677 }
678 req = requests.Request("GET", url)
679 prep = req.prepare()
680 session.rebuild_proxies(prep, proxies)
681
682 assert ("Proxy-Authorization" in prep.headers) is has_proxy_auth
683
684 def test_basicauth_with_netrc(self, httpbin):
685 auth = ("user", "pass")
686 wrong_auth = ("wronguser", "wrongpass")
687 url = httpbin("basic-auth", "user", "pass")
688
689 old_auth = requests.sessions.get_netrc_auth
690
691 try:
692
693 def get_netrc_auth_mock(url):
694 return auth
695
696 requests.sessions.get_netrc_auth = get_netrc_auth_mock
697
698 # Should use netrc and work.
699 r = requests.get(url)
700 assert r.status_code == 200
701
702 # Given auth should override and fail.
703 r = requests.get(url, auth=wrong_auth)
704 assert r.status_code == 401
705
706 s = requests.session()
707
708 # Should use netrc and work.
709 r = s.get(url)
710 assert r.status_code == 200
711
712 # Given auth should override and fail.
713 s.auth = wrong_auth
714 r = s.get(url)
715 assert r.status_code == 401
716 finally:
717 requests.sessions.get_netrc_auth = old_auth
718
719 def test_basicauth_with_netrc_leak(self, httpbin):
720 url1 = httpbin("basic-auth", "user", "pass")
721 url = url1[len("http://") :]
722 domain = url.split(":")[0]
723 url = f"http://example.com:@{url}"
724
725 netrc_file = ""
726 with tempfile.NamedTemporaryFile(mode="w", delete=False) as fp:
727 fp.write("machine example.com\n")
728 fp.write("login wronguser\n")
729 fp.write("password wrongpass\n")
730 fp.write(f"machine {domain}\n")
731 fp.write("login user\n")
732 fp.write("password pass\n")
733 fp.close()
734 netrc_file = fp.name
735
736 old_netrc = os.environ.get("NETRC", "")
737 os.environ["NETRC"] = netrc_file
738
739 try:
740 # Should use netrc
741 # Make sure that we don't use the example.com credentials
742 # for the request
743 r = requests.get(url)
744 assert r.status_code == 200
745 finally:
746 os.environ["NETRC"] = old_netrc
747 os.unlink(netrc_file)
748
749 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):
750 for authtype in self.digest_auth_algo:
751 auth = HTTPDigestAuth("user", "pass")
752 url = httpbin("digest-auth", "auth", "user", "pass", authtype, "never")
753
754 r = requests.get(url, auth=auth)
755 assert r.status_code == 200
756
757 r = requests.get(url)
758 assert r.status_code == 401
759 print(r.headers["WWW-Authenticate"])
760
761 s = requests.session()
762 s.auth = HTTPDigestAuth("user", "pass")
763 r = s.get(url)
764 assert r.status_code == 200
765
766 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):
767 for authtype in self.digest_auth_algo:
768 url = httpbin("digest-auth", "auth", "user", "pass", authtype)
769 auth = HTTPDigestAuth("user", "pass")
770 r = requests.get(url)
771 assert r.cookies["fake"] == "fake_value"
772
773 r = requests.get(url, auth=auth)
774 assert r.status_code == 200
775
776 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):
777 for authtype in self.digest_auth_algo:
778 url = httpbin("digest-auth", "auth", "user", "pass", authtype)
779 auth = HTTPDigestAuth("user", "pass")
780 s = requests.Session()
781 s.get(url, auth=auth)
782 assert s.cookies["fake"] == "fake_value"
783
784 def test_DIGEST_STREAM(self, httpbin):
785 for authtype in self.digest_auth_algo:
786 auth = HTTPDigestAuth("user", "pass")
787 url = httpbin("digest-auth", "auth", "user", "pass", authtype)
788
789 r = requests.get(url, auth=auth, stream=True)
790 assert r.raw.read() != b""
791
792 r = requests.get(url, auth=auth, stream=False)
793 assert r.raw.read() == b""
794
795 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):
796 for authtype in self.digest_auth_algo:
797 auth = HTTPDigestAuth("user", "wrongpass")
798 url = httpbin("digest-auth", "auth", "user", "pass", authtype)
799
800 r = requests.get(url, auth=auth)
801 assert r.status_code == 401
802
803 r = requests.get(url)
804 assert r.status_code == 401
805
806 s = requests.session()
807 s.auth = auth
808 r = s.get(url)
809 assert r.status_code == 401
810
811 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):
812 for authtype in self.digest_auth_algo:
813 auth = HTTPDigestAuth("user", "pass")
814 url = httpbin("digest-auth", "auth", "user", "pass", authtype)
815
816 r = requests.get(url, auth=auth)
817 assert '"auth"' in r.request.headers["Authorization"]
818
819 def test_POSTBIN_GET_POST_FILES(self, httpbin):
820 url = httpbin("post")
821 requests.post(url).raise_for_status()
822
823 post1 = requests.post(url, data={"some": "data"})
824 assert post1.status_code == 200
825
826 with open("requirements-dev.txt") as f:
827 post2 = requests.post(url, files={"some": f})
828 assert post2.status_code == 200
829
830 post4 = requests.post(url, data='[{"some": "json"}]')
831 assert post4.status_code == 200
832
833 with pytest.raises(ValueError):
834 requests.post(url, files=["bad file data"])
835
836 def test_invalid_files_input(self, httpbin):
837 url = httpbin("post")
838 post = requests.post(url, files={"random-file-1": None, "random-file-2": 1})
839 assert b'name="random-file-1"' not in post.request.body
840 assert b'name="random-file-2"' in post.request.body
841
842 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):
843 class TestStream:
844 def __init__(self, data):
845 self.data = data.encode()
846 self.length = len(self.data)
847 self.index = 0
848
849 def __len__(self):
850 return self.length
851
852 def read(self, size=None):
853 if size:
854 ret = self.data[self.index : self.index + size]
855 self.index += size
856 else:
857 ret = self.data[self.index :]
858 self.index = self.length
859 return ret
860
861 def tell(self):
862 return self.index
863
864 def seek(self, offset, where=0):
865 if where == 0:
866 self.index = offset
867 elif where == 1:
868 self.index += offset
869 elif where == 2:
870 self.index = self.length + offset
871
872 test = TestStream("test")
873 post1 = requests.post(httpbin("post"), data=test)
874 assert post1.status_code == 200
875 assert post1.json()["data"] == "test"
876
877 test = TestStream("test")
878 test.seek(2)
879 post2 = requests.post(httpbin("post"), data=test)
880 assert post2.status_code == 200
881 assert post2.json()["data"] == "st"
882
883 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):
884 url = httpbin("post")
885 requests.post(url).raise_for_status()
886
887 post1 = requests.post(url, data={"some": "data"})
888 assert post1.status_code == 200
889
890 with open("requirements-dev.txt") as f:
891 post2 = requests.post(url, data={"some": "data"}, files={"some": f})
892 assert post2.status_code == 200
893
894 post4 = requests.post(url, data='[{"some": "json"}]')
895 assert post4.status_code == 200
896
897 with pytest.raises(ValueError):
898 requests.post(url, files=["bad file data"])
899
900 def test_post_with_custom_mapping(self, httpbin):
901 class CustomMapping(MutableMapping):
902 def __init__(self, *args, **kwargs):
903 self.data = dict(*args, **kwargs)
904
905 def __delitem__(self, key):
906 del self.data[key]
907
908 def __getitem__(self, key):
909 return self.data[key]
910
911 def __setitem__(self, key, value):
912 self.data[key] = value
913
914 def __iter__(self):
915 return iter(self.data)
916
917 def __len__(self):
918 return len(self.data)
919
920 data = CustomMapping({"some": "data"})
921 url = httpbin("post")
922 found_json = requests.post(url, data=data).json().get("form")
923 assert found_json == {"some": "data"}
924
925 def test_conflicting_post_params(self, httpbin):
926 url = httpbin("post")
927 with open("requirements-dev.txt") as f:
928 with pytest.raises(ValueError):
929 requests.post(url, data='[{"some": "data"}]', files={"some": f})
930
931 def test_request_ok_set(self, httpbin):
932 r = requests.get(httpbin("status", "404"))
933 assert not r.ok
934
935 def test_status_raising(self, httpbin):
936 r = requests.get(httpbin("status", "404"))
937 with pytest.raises(requests.exceptions.HTTPError):
938 r.raise_for_status()
939
940 r = requests.get(httpbin("status", "500"))
941 assert not r.ok
942
943 def test_decompress_gzip(self, httpbin):
944 r = requests.get(httpbin("gzip"))
945 r.content.decode("ascii")
946
947 @pytest.mark.parametrize(
948 "url, params",
949 (
950 ("/get", {"foo": "føø"}),
951 ("/get", {"føø": "føø"}),
952 ("/get", {"føø": "føø"}),
953 ("/get", {"foo": "foo"}),
954 ("ø", {"foo": "foo"}),
955 ),
956 )
957 def test_unicode_get(self, httpbin, url, params):
958 requests.get(httpbin(url), params=params)
959
960 def test_unicode_header_name(self, httpbin):
961 requests.put(
962 httpbin("put"),
963 headers={"Content-Type": "application/octet-stream"},
964 data="\xff",
965 ) # compat.str is unicode.
966
967 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):
968 requests.get(httpbin_secure("status", "301"), verify=httpbin_ca_bundle)
969
970 def test_invalid_ca_certificate_path(self, httpbin_secure):
971 INVALID_PATH = "/garbage"
972 with pytest.raises(IOError) as e:
973 requests.get(httpbin_secure(), verify=INVALID_PATH)
974 assert (
975 str(e.value)
976 == f"Could not find a suitable TLS CA certificate bundle, invalid path: {INVALID_PATH}"
977 )
978
979 def test_invalid_ssl_certificate_files(self, httpbin_secure):
980 INVALID_PATH = "/garbage"
981 with pytest.raises(IOError) as e:
982 requests.get(httpbin_secure(), cert=INVALID_PATH)
983 assert (
984 str(e.value)
985 == f"Could not find the TLS certificate file, invalid path: {INVALID_PATH}"
986 )
987
988 with pytest.raises(IOError) as e:
989 requests.get(httpbin_secure(), cert=(".", INVALID_PATH))
990 assert str(e.value) == (
991 f"Could not find the TLS key file, invalid path: {INVALID_PATH}"
992 )
993
994 @pytest.mark.parametrize(
995 "env, expected",
996 (
997 ({}, True),
998 ({"REQUESTS_CA_BUNDLE": "/some/path"}, "/some/path"),
999 ({"REQUESTS_CA_BUNDLE": ""}, True),
1000 ({"CURL_CA_BUNDLE": "/some/path"}, "/some/path"),
1001 ({"CURL_CA_BUNDLE": ""}, True),
1002 ({"REQUESTS_CA_BUNDLE": "", "CURL_CA_BUNDLE": ""}, True),
1003 (
1004 {
1005 "REQUESTS_CA_BUNDLE": "/some/path",
1006 "CURL_CA_BUNDLE": "/curl/path",
1007 },
1008 "/some/path",
1009 ),
1010 (
1011 {
1012 "REQUESTS_CA_BUNDLE": "",
1013 "CURL_CA_BUNDLE": "/curl/path",
1014 },
1015 "/curl/path",
1016 ),
1017 ),
1018 )
1019 def test_env_cert_bundles(self, httpbin, env, expected):
1020 s = requests.Session()
1021 with mock.patch("os.environ", env):
1022 settings = s.merge_environment_settings(
1023 url=httpbin("get"), proxies={}, stream=False, verify=True, cert=None
1024 )
1025 assert settings["verify"] == expected
1026
1027 def test_http_with_certificate(self, httpbin):
1028 r = requests.get(httpbin(), cert=".")
1029 assert r.status_code == 200
1030
1031 @pytest.mark.skipif(
1032 SNIMissingWarning is None,
1033 reason="urllib3 2.0 removed that warning and errors out instead",
1034 )
1035 def test_https_warnings(self, nosan_server):
1036 """warnings are emitted with requests.get"""
1037 host, port, ca_bundle = nosan_server
1038 if HAS_MODERN_SSL or HAS_PYOPENSSL:
1039 warnings_expected = ("SubjectAltNameWarning",)
1040 else:
1041 warnings_expected = (
1042 "SNIMissingWarning",
1043 "InsecurePlatformWarning",
1044 "SubjectAltNameWarning",
1045 )
1046
1047 with pytest.warns() as warning_records:
1048 warnings.simplefilter("always")
1049 requests.get(f"https://localhost:{port}/", verify=ca_bundle)
1050
1051 warning_records = [
1052 item
1053 for item in warning_records
1054 if item.category.__name__ != "ResourceWarning"
1055 ]
1056
1057 warnings_category = tuple(item.category.__name__ for item in warning_records)
1058 assert warnings_category == warnings_expected
1059
1060 def test_certificate_failure(self, httpbin_secure):
1061 """
1062 When underlying SSL problems occur, an SSLError is raised.
1063 """
1064 with pytest.raises(RequestsSSLError):
1065 # Our local httpbin does not have a trusted CA, so this call will
1066 # fail if we use our default trust bundle.
1067 requests.get(httpbin_secure("status", "200"))
1068
1069 def test_urlencoded_get_query_multivalued_param(self, httpbin):
1070 r = requests.get(httpbin("get"), params={"test": ["foo", "baz"]})
1071 assert r.status_code == 200
1072 assert r.url == httpbin("get?test=foo&test=baz")
1073
1074 def test_form_encoded_post_query_multivalued_element(self, httpbin):
1075 r = requests.Request(
1076 method="POST", url=httpbin("post"), data=dict(test=["foo", "baz"])
1077 )
1078 prep = r.prepare()
1079 assert prep.body == "test=foo&test=baz"
1080
1081 def test_different_encodings_dont_break_post(self, httpbin):
1082 with open(__file__, "rb") as f:
1083 r = requests.post(
1084 httpbin("post"),
1085 data={"stuff": json.dumps({"a": 123})},
1086 params={"blah": "asdf1234"},
1087 files={"file": ("test_requests.py", f)},
1088 )
1089 assert r.status_code == 200
1090
1091 @pytest.mark.parametrize(
1092 "data",
1093 (
1094 {"stuff": "ëlïxr"},
1095 {"stuff": "ëlïxr".encode()},
1096 {"stuff": "elixr"},
1097 {"stuff": b"elixr"},
1098 ),
1099 )
1100 def test_unicode_multipart_post(self, httpbin, data):
1101 with open(__file__, "rb") as f:
1102 r = requests.post(
1103 httpbin("post"),
1104 data=data,
1105 files={"file": ("test_requests.py", f)},
1106 )
1107 assert r.status_code == 200
1108
1109 def test_unicode_multipart_post_fieldnames(self, httpbin):
1110 filename = os.path.splitext(__file__)[0] + ".py"
1111 with open(filename, "rb") as f:
1112 r = requests.Request(
1113 method="POST",
1114 url=httpbin("post"),
1115 data={b"stuff": "elixr"},
1116 files={"file": ("test_requests.py", f)},
1117 )
1118 prep = r.prepare()
1119
1120 assert b'name="stuff"' in prep.body
1121 assert b"name=\"b'stuff'\"" not in prep.body
1122
1123 def test_unicode_method_name(self, httpbin):
1124 with open(__file__, "rb") as f:
1125 files = {"file": f}
1126 r = requests.request(
1127 method="POST",
1128 url=httpbin("post"),
1129 files=files,
1130 )
1131 assert r.status_code == 200
1132
1133 def test_unicode_method_name_with_request_object(self, httpbin):
1134 s = requests.Session()
1135 with open(__file__, "rb") as f:
1136 files = {"file": f}
1137 req = requests.Request("POST", httpbin("post"), files=files)
1138 prep = s.prepare_request(req)
1139 assert isinstance(prep.method, builtin_str)
1140 assert prep.method == "POST"
1141
1142 resp = s.send(prep)
1143 assert resp.status_code == 200
1144
1145 def test_non_prepared_request_error(self):
1146 s = requests.Session()
1147 req = requests.Request("POST", "/")
1148
1149 with pytest.raises(ValueError) as e:
1150 s.send(req)
1151 assert str(e.value) == "You can only send PreparedRequests."
1152
1153 def test_custom_content_type(self, httpbin):
1154 with open(__file__, "rb") as f1:
1155 with open(__file__, "rb") as f2:
1156 data = {"stuff": json.dumps({"a": 123})}
1157 files = {
1158 "file1": ("test_requests.py", f1),
1159 "file2": ("test_requests", f2, "text/py-content-type"),
1160 }
1161 r = requests.post(httpbin("post"), data=data, files=files)
1162 assert r.status_code == 200
1163 assert b"text/py-content-type" in r.request.body
1164
1165 def test_hook_receives_request_arguments(self, httpbin):
1166 def hook(resp, **kwargs):
1167 assert resp is not None
1168 assert kwargs != {}
1169
1170 s = requests.Session()
1171 r = requests.Request("GET", httpbin(), hooks={"response": hook})
1172 prep = s.prepare_request(r)
1173 s.send(prep)
1174
1175 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):
1176 def hook(*args, **kwargs):
1177 pass
1178
1179 s = requests.Session()
1180 s.hooks["response"].append(hook)
1181 r = requests.Request("GET", httpbin())
1182 prep = s.prepare_request(r)
1183 assert prep.hooks["response"] != []
1184 assert prep.hooks["response"] == [hook]
1185
1186 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):
1187 def hook1(*args, **kwargs):
1188 pass
1189
1190 def hook2(*args, **kwargs):
1191 pass
1192
1193 assert hook1 is not hook2
1194 s = requests.Session()
1195 s.hooks["response"].append(hook2)
1196 r = requests.Request("GET", httpbin(), hooks={"response": [hook1]})
1197 prep = s.prepare_request(r)
1198 assert prep.hooks["response"] == [hook1]
1199
1200 def test_prepared_request_hook(self, httpbin):
1201 def hook(resp, **kwargs):
1202 resp.hook_working = True
1203 return resp
1204
1205 req = requests.Request("GET", httpbin(), hooks={"response": hook})
1206 prep = req.prepare()
1207
1208 s = requests.Session()
1209 s.proxies = getproxies()
1210 resp = s.send(prep)
1211
1212 assert hasattr(resp, "hook_working")
1213
1214 def test_prepared_from_session(self, httpbin):
1215 class DummyAuth(requests.auth.AuthBase):
1216 def __call__(self, r):
1217 r.headers["Dummy-Auth-Test"] = "dummy-auth-test-ok"
1218 return r
1219
1220 req = requests.Request("GET", httpbin("headers"))
1221 assert not req.auth
1222
1223 s = requests.Session()
1224 s.auth = DummyAuth()
1225
1226 prep = s.prepare_request(req)
1227 resp = s.send(prep)
1228
1229 assert resp.json()["headers"]["Dummy-Auth-Test"] == "dummy-auth-test-ok"
1230
1231 def test_prepare_request_with_bytestring_url(self):
1232 req = requests.Request("GET", b"https://httpbin.org/")
1233 s = requests.Session()
1234 prep = s.prepare_request(req)
1235 assert prep.url == "https://httpbin.org/"
1236
1237 def test_request_with_bytestring_host(self, httpbin):
1238 s = requests.Session()
1239 resp = s.request(
1240 "GET",
1241 httpbin("cookies/set?cookie=value"),
1242 allow_redirects=False,
1243 headers={"Host": b"httpbin.org"},
1244 )
1245 assert resp.cookies.get("cookie") == "value"
1246
1247 def test_links(self):
1248 r = requests.Response()
1249 r.headers = {
1250 "cache-control": "public, max-age=60, s-maxage=60",
1251 "connection": "keep-alive",
1252 "content-encoding": "gzip",
1253 "content-type": "application/json; charset=utf-8",
1254 "date": "Sat, 26 Jan 2013 16:47:56 GMT",
1255 "etag": '"6ff6a73c0e446c1f61614769e3ceb778"',
1256 "last-modified": "Sat, 26 Jan 2013 16:22:39 GMT",
1257 "link": (
1258 "<https://api.github.com/users/kennethreitz/repos?"
1259 'page=2&per_page=10>; rel="next", <https://api.github.'
1260 "com/users/kennethreitz/repos?page=7&per_page=10>; "
1261 ' rel="last"'
1262 ),
1263 "server": "GitHub.com",
1264 "status": "200 OK",
1265 "vary": "Accept",
1266 "x-content-type-options": "nosniff",
1267 "x-github-media-type": "github.beta",
1268 "x-ratelimit-limit": "60",
1269 "x-ratelimit-remaining": "57",
1270 }
1271 assert r.links["next"]["rel"] == "next"
1272
1273 def test_cookie_parameters(self):
1274 key = "some_cookie"
1275 value = "some_value"
1276 secure = True
1277 domain = "test.com"
1278 rest = {"HttpOnly": True}
1279
1280 jar = requests.cookies.RequestsCookieJar()
1281 jar.set(key, value, secure=secure, domain=domain, rest=rest)
1282
1283 assert len(jar) == 1
1284 assert "some_cookie" in jar
1285
1286 cookie = list(jar)[0]
1287 assert cookie.secure == secure
1288 assert cookie.domain == domain
1289 assert cookie._rest["HttpOnly"] == rest["HttpOnly"]
1290
1291 def test_cookie_as_dict_keeps_len(self):
1292 key = "some_cookie"
1293 value = "some_value"
1294
1295 key1 = "some_cookie1"
1296 value1 = "some_value1"
1297
1298 jar = requests.cookies.RequestsCookieJar()
1299 jar.set(key, value)
1300 jar.set(key1, value1)
1301
1302 d1 = dict(jar)
1303 d2 = dict(jar.iteritems())
1304 d3 = dict(jar.items())
1305
1306 assert len(jar) == 2
1307 assert len(d1) == 2
1308 assert len(d2) == 2
1309 assert len(d3) == 2
1310
1311 def test_cookie_as_dict_keeps_items(self):
1312 key = "some_cookie"
1313 value = "some_value"
1314
1315 key1 = "some_cookie1"
1316 value1 = "some_value1"
1317
1318 jar = requests.cookies.RequestsCookieJar()
1319 jar.set(key, value)
1320 jar.set(key1, value1)
1321
1322 d1 = dict(jar)
1323 d2 = dict(jar.iteritems())
1324 d3 = dict(jar.items())
1325
1326 assert d1["some_cookie"] == "some_value"
1327 assert d2["some_cookie"] == "some_value"
1328 assert d3["some_cookie1"] == "some_value1"
1329
1330 def test_cookie_as_dict_keys(self):
1331 key = "some_cookie"
1332 value = "some_value"
1333
1334 key1 = "some_cookie1"
1335 value1 = "some_value1"
1336
1337 jar = requests.cookies.RequestsCookieJar()
1338 jar.set(key, value)
1339 jar.set(key1, value1)
1340
1341 keys = jar.keys()
1342 assert keys == list(keys)
1343 # make sure one can use keys multiple times
1344 assert list(keys) == list(keys)
1345
1346 def test_cookie_as_dict_values(self):
1347 key = "some_cookie"
1348 value = "some_value"
1349
1350 key1 = "some_cookie1"
1351 value1 = "some_value1"
1352
1353 jar = requests.cookies.RequestsCookieJar()
1354 jar.set(key, value)
1355 jar.set(key1, value1)
1356
1357 values = jar.values()
1358 assert values == list(values)
1359 # make sure one can use values multiple times
1360 assert list(values) == list(values)
1361
1362 def test_cookie_as_dict_items(self):
1363 key = "some_cookie"
1364 value = "some_value"
1365
1366 key1 = "some_cookie1"
1367 value1 = "some_value1"
1368
1369 jar = requests.cookies.RequestsCookieJar()
1370 jar.set(key, value)
1371 jar.set(key1, value1)
1372
1373 items = jar.items()
1374 assert items == list(items)
1375 # make sure one can use items multiple times
1376 assert list(items) == list(items)
1377
1378 def test_cookie_duplicate_names_different_domains(self):
1379 key = "some_cookie"
1380 value = "some_value"
1381 domain1 = "test1.com"
1382 domain2 = "test2.com"
1383
1384 jar = requests.cookies.RequestsCookieJar()
1385 jar.set(key, value, domain=domain1)
1386 jar.set(key, value, domain=domain2)
1387 assert key in jar
1388 items = jar.items()
1389 assert len(items) == 2
1390
1391 # Verify that CookieConflictError is raised if domain is not specified
1392 with pytest.raises(requests.cookies.CookieConflictError):
1393 jar.get(key)
1394
1395 # Verify that CookieConflictError is not raised if domain is specified
1396 cookie = jar.get(key, domain=domain1)
1397 assert cookie == value
1398
1399 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):
1400 key = "some_cookie"
1401 value = "some_value"
1402 path = "some_path"
1403
1404 jar = requests.cookies.RequestsCookieJar()
1405 jar.set(key, value, path=path)
1406 jar.set(key, value)
1407 with pytest.raises(requests.cookies.CookieConflictError):
1408 jar.get(key)
1409
1410 def test_cookie_policy_copy(self):
1411 class MyCookiePolicy(cookielib.DefaultCookiePolicy):
1412 pass
1413
1414 jar = requests.cookies.RequestsCookieJar()
1415 jar.set_policy(MyCookiePolicy())
1416 assert isinstance(jar.copy().get_policy(), MyCookiePolicy)
1417
1418 def test_time_elapsed_blank(self, httpbin):
1419 r = requests.get(httpbin("get"))
1420 td = r.elapsed
1421 total_seconds = (
1422 td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6
1423 ) / 10**6
1424 assert total_seconds > 0.0
1425
1426 def test_empty_response_has_content_none(self):
1427 r = requests.Response()
1428 assert r.content is None
1429
1430 def test_response_is_iterable(self):
1431 r = requests.Response()
1432 io = StringIO.StringIO("abc")
1433 read_ = io.read
1434
1435 def read_mock(amt, decode_content=None):
1436 return read_(amt)
1437
1438 setattr(io, "read", read_mock)
1439 r.raw = io
1440 assert next(iter(r))
1441 io.close()
1442
1443 def test_response_decode_unicode(self):
1444 """When called with decode_unicode, Response.iter_content should always
1445 return unicode.
1446 """
1447 r = requests.Response()
1448 r._content_consumed = True
1449 r._content = b"the content"
1450 r.encoding = "ascii"
1451
1452 chunks = r.iter_content(decode_unicode=True)
1453 assert all(isinstance(chunk, str) for chunk in chunks)
1454
1455 # also for streaming
1456 r = requests.Response()
1457 r.raw = io.BytesIO(b"the content")
1458 r.encoding = "ascii"
1459 chunks = r.iter_content(decode_unicode=True)
1460 assert all(isinstance(chunk, str) for chunk in chunks)
1461
1462 def test_response_reason_unicode(self):
1463 # check for unicode HTTP status
1464 r = requests.Response()
1465 r.url = "unicode URL"
1466 r.reason = "Komponenttia ei löydy".encode()
1467 r.status_code = 404
1468 r.encoding = None
1469 assert not r.ok # old behaviour - crashes here
1470
1471 def test_response_reason_unicode_fallback(self):
1472 # check raise_status falls back to ISO-8859-1
1473 r = requests.Response()
1474 r.url = "some url"
1475 reason = "Komponenttia ei löydy"
1476 r.reason = reason.encode("latin-1")
1477 r.status_code = 500
1478 r.encoding = None
1479 with pytest.raises(requests.exceptions.HTTPError) as e:
1480 r.raise_for_status()
1481 assert reason in e.value.args[0]
1482
1483 def test_response_chunk_size_type(self):
1484 """Ensure that chunk_size is passed as None or an integer, otherwise
1485 raise a TypeError.
1486 """
1487 r = requests.Response()
1488 r.raw = io.BytesIO(b"the content")
1489 chunks = r.iter_content(1)
1490 assert all(len(chunk) == 1 for chunk in chunks)
1491
1492 r = requests.Response()
1493 r.raw = io.BytesIO(b"the content")
1494 chunks = r.iter_content(None)
1495 assert list(chunks) == [b"the content"]
1496
1497 r = requests.Response()
1498 r.raw = io.BytesIO(b"the content")
1499 with pytest.raises(TypeError):
1500 chunks = r.iter_content("1024")
1501
1502 @pytest.mark.parametrize(
1503 "exception, args, expected",
1504 (
1505 (urllib3.exceptions.ProtocolError, tuple(), ChunkedEncodingError),
1506 (urllib3.exceptions.DecodeError, tuple(), ContentDecodingError),
1507 (urllib3.exceptions.ReadTimeoutError, (None, "", ""), ConnectionError),
1508 (urllib3.exceptions.SSLError, tuple(), RequestsSSLError),
1509 ),
1510 )
1511 def test_iter_content_wraps_exceptions(self, httpbin, exception, args, expected):
1512 r = requests.Response()
1513 r.raw = mock.Mock()
1514 # ReadTimeoutError can't be initialized by mock
1515 # so we'll manually create the instance with args
1516 r.raw.stream.side_effect = exception(*args)
1517
1518 with pytest.raises(expected):
1519 next(r.iter_content(1024))
1520
1521 def test_request_and_response_are_pickleable(self, httpbin):
1522 r = requests.get(httpbin("get"))
1523
1524 # verify we can pickle the original request
1525 assert pickle.loads(pickle.dumps(r.request))
1526
1527 # verify we can pickle the response and that we have access to
1528 # the original request.
1529 pr = pickle.loads(pickle.dumps(r))
1530 assert r.request.url == pr.request.url
1531 assert r.request.headers == pr.request.headers
1532
1533 def test_prepared_request_is_pickleable(self, httpbin):
1534 p = requests.Request("GET", httpbin("get")).prepare()
1535
1536 # Verify PreparedRequest can be pickled and unpickled
1537 r = pickle.loads(pickle.dumps(p))
1538 assert r.url == p.url
1539 assert r.headers == p.headers
1540 assert r.body == p.body
1541
1542 # Verify unpickled PreparedRequest sends properly
1543 s = requests.Session()
1544 resp = s.send(r)
1545 assert resp.status_code == 200
1546
1547 def test_prepared_request_with_file_is_pickleable(self, httpbin):
1548 with open(__file__, "rb") as f:
1549 r = requests.Request("POST", httpbin("post"), files={"file": f})
1550 p = r.prepare()
1551
1552 # Verify PreparedRequest can be pickled and unpickled
1553 r = pickle.loads(pickle.dumps(p))
1554 assert r.url == p.url
1555 assert r.headers == p.headers
1556 assert r.body == p.body
1557
1558 # Verify unpickled PreparedRequest sends properly
1559 s = requests.Session()
1560 resp = s.send(r)
1561 assert resp.status_code == 200
1562
1563 def test_prepared_request_with_hook_is_pickleable(self, httpbin):
1564 r = requests.Request("GET", httpbin("get"), hooks=default_hooks())
1565 p = r.prepare()
1566
1567 # Verify PreparedRequest can be pickled
1568 r = pickle.loads(pickle.dumps(p))
1569 assert r.url == p.url
1570 assert r.headers == p.headers
1571 assert r.body == p.body
1572 assert r.hooks == p.hooks
1573
1574 # Verify unpickled PreparedRequest sends properly
1575 s = requests.Session()
1576 resp = s.send(r)
1577 assert resp.status_code == 200
1578
1579 def test_cannot_send_unprepared_requests(self, httpbin):
1580 r = requests.Request(url=httpbin())
1581 with pytest.raises(ValueError):
1582 requests.Session().send(r)
1583
1584 def test_http_error(self):
1585 error = requests.exceptions.HTTPError()
1586 assert not error.response
1587 response = requests.Response()
1588 error = requests.exceptions.HTTPError(response=response)
1589 assert error.response == response
1590 error = requests.exceptions.HTTPError("message", response=response)
1591 assert str(error) == "message"
1592 assert error.response == response
1593
1594 def test_session_pickling(self, httpbin):
1595 r = requests.Request("GET", httpbin("get"))
1596 s = requests.Session()
1597
1598 s = pickle.loads(pickle.dumps(s))
1599 s.proxies = getproxies()
1600
1601 r = s.send(r.prepare())
1602 assert r.status_code == 200
1603
1604 def test_fixes_1329(self, httpbin):
1605 """Ensure that header updates are done case-insensitively."""
1606 s = requests.Session()
1607 s.headers.update({"ACCEPT": "BOGUS"})
1608 s.headers.update({"accept": "application/json"})
1609 r = s.get(httpbin("get"))
1610 headers = r.request.headers
1611 assert headers["accept"] == "application/json"
1612 assert headers["Accept"] == "application/json"
1613 assert headers["ACCEPT"] == "application/json"
1614
1615 def test_uppercase_scheme_redirect(self, httpbin):
1616 parts = urlparse(httpbin("html"))
1617 url = "HTTP://" + parts.netloc + parts.path
1618 r = requests.get(httpbin("redirect-to"), params={"url": url})
1619 assert r.status_code == 200
1620 assert r.url.lower() == url.lower()
1621
1622 def test_transport_adapter_ordering(self):
1623 s = requests.Session()
1624 order = ["https://", "http://"]
1625 assert order == list(s.adapters)
1626 s.mount("http://git", HTTPAdapter())
1627 s.mount("http://github", HTTPAdapter())
1628 s.mount("http://github.com", HTTPAdapter())
1629 s.mount("http://github.com/about/", HTTPAdapter())
1630 order = [
1631 "http://github.com/about/",
1632 "http://github.com",
1633 "http://github",
1634 "http://git",
1635 "https://",
1636 "http://",
1637 ]
1638 assert order == list(s.adapters)
1639 s.mount("http://gittip", HTTPAdapter())
1640 s.mount("http://gittip.com", HTTPAdapter())
1641 s.mount("http://gittip.com/about/", HTTPAdapter())
1642 order = [
1643 "http://github.com/about/",
1644 "http://gittip.com/about/",
1645 "http://github.com",
1646 "http://gittip.com",
1647 "http://github",
1648 "http://gittip",
1649 "http://git",
1650 "https://",
1651 "http://",
1652 ]
1653 assert order == list(s.adapters)
1654 s2 = requests.Session()
1655 s2.adapters = {"http://": HTTPAdapter()}
1656 s2.mount("https://", HTTPAdapter())
1657 assert "http://" in s2.adapters
1658 assert "https://" in s2.adapters
1659
1660 def test_session_get_adapter_prefix_matching(self):
1661 prefix = "https://example.com"
1662 more_specific_prefix = prefix + "/some/path"
1663
1664 url_matching_only_prefix = prefix + "/another/path"
1665 url_matching_more_specific_prefix = more_specific_prefix + "/longer/path"
1666 url_not_matching_prefix = "https://another.example.com/"
1667
1668 s = requests.Session()
1669 prefix_adapter = HTTPAdapter()
1670 more_specific_prefix_adapter = HTTPAdapter()
1671 s.mount(prefix, prefix_adapter)
1672 s.mount(more_specific_prefix, more_specific_prefix_adapter)
1673
1674 assert s.get_adapter(url_matching_only_prefix) is prefix_adapter
1675 assert (
1676 s.get_adapter(url_matching_more_specific_prefix)
1677 is more_specific_prefix_adapter
1678 )
1679 assert s.get_adapter(url_not_matching_prefix) not in (
1680 prefix_adapter,
1681 more_specific_prefix_adapter,
1682 )
1683
1684 def test_session_get_adapter_prefix_matching_mixed_case(self):
1685 mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"
1686 url_matching_prefix = mixed_case_prefix + "/full_url"
1687
1688 s = requests.Session()
1689 my_adapter = HTTPAdapter()
1690 s.mount(mixed_case_prefix, my_adapter)
1691
1692 assert s.get_adapter(url_matching_prefix) is my_adapter
1693
1694 def test_session_get_adapter_prefix_matching_is_case_insensitive(self):
1695 mixed_case_prefix = "hTtPs://eXamPle.CoM/MixEd_CAse_PREfix"
1696 url_matching_prefix_with_different_case = (
1697 "HtTpS://exaMPLe.cOm/MiXeD_caSE_preFIX/another_url"
1698 )
1699
1700 s = requests.Session()
1701 my_adapter = HTTPAdapter()
1702 s.mount(mixed_case_prefix, my_adapter)
1703
1704 assert s.get_adapter(url_matching_prefix_with_different_case) is my_adapter
1705
1706 def test_session_get_adapter_prefix_with_trailing_slash(self):
1707 # from issue #6935
1708 prefix = "https://example.com/" # trailing slash
1709 url_matching_prefix = "https://example.com/some/path"
1710 url_not_matching_prefix = "https://example.com.other.com/some/path"
1711
1712 s = requests.Session()
1713 adapter = HTTPAdapter()
1714 s.mount(prefix, adapter)
1715
1716 assert s.get_adapter(url_matching_prefix) is adapter
1717 assert s.get_adapter(url_not_matching_prefix) is not adapter
1718
1719 def test_session_get_adapter_prefix_without_trailing_slash(self):
1720 # from issue #6935
1721 prefix = "https://example.com" # no trailing slash
1722 url_matching_prefix = "https://example.com/some/path"
1723 url_extended_hostname = "https://example.com.other.com/some/path"
1724
1725 s = requests.Session()
1726 adapter = HTTPAdapter()
1727 s.mount(prefix, adapter)
1728
1729 assert s.get_adapter(url_matching_prefix) is adapter
1730 assert s.get_adapter(url_extended_hostname) is adapter
1731
1732 def test_header_remove_is_case_insensitive(self, httpbin):
1733 # From issue #1321
1734 s = requests.Session()
1735 s.headers["foo"] = "bar"
1736 r = s.get(httpbin("get"), headers={"FOO": None})
1737 assert "foo" not in r.request.headers
1738
1739 def test_params_are_merged_case_sensitive(self, httpbin):
1740 s = requests.Session()
1741 s.params["foo"] = "bar"
1742 r = s.get(httpbin("get"), params={"FOO": "bar"})
1743 assert r.json()["args"] == {"foo": "bar", "FOO": "bar"}
1744
1745 def test_long_authinfo_in_url(self):
1746 url = "http://{}:{}@{}:9000/path?query#frag".format(
1747 "E8A3BE87-9E3F-4620-8858-95478E385B5B",
1748 "EA770032-DA4D-4D84-8CE9-29C6D910BF1E",
1749 "exactly-------------sixty-----------three------------characters",
1750 )
1751 r = requests.Request("GET", url).prepare()
1752 assert r.url == url
1753
1754 def test_header_keys_are_native(self, httpbin):
1755 headers = {"unicode": "blah", b"byte": "blah"}
1756 r = requests.Request("GET", httpbin("get"), headers=headers)
1757 p = r.prepare()
1758
1759 # This is testing that they are builtin strings. A bit weird, but there
1760 # we go.
1761 assert "unicode" in p.headers.keys()
1762 assert "byte" in p.headers.keys()
1763
1764 def test_header_validation(self, httpbin):
1765 """Ensure prepare_headers regex isn't flagging valid header contents."""
1766 valid_headers = {
1767 "foo": "bar baz qux",
1768 "bar": b"fbbq",
1769 "baz": "",
1770 "qux": "1",
1771 }
1772 r = requests.get(httpbin("get"), headers=valid_headers)
1773 for key in valid_headers.keys():
1774 assert valid_headers[key] == r.request.headers[key]
1775
1776 @pytest.mark.parametrize(
1777 "invalid_header, key",
1778 (
1779 ({"foo": 3}, "foo"),
1780 ({"bar": {"foo": "bar"}}, "bar"),
1781 ({"baz": ["foo", "bar"]}, "baz"),
1782 ),
1783 )
1784 def test_header_value_not_str(self, httpbin, invalid_header, key):
1785 """Ensure the header value is of type string or bytes as
1786 per discussion in GH issue #3386
1787 """
1788 with pytest.raises(InvalidHeader) as excinfo:
1789 requests.get(httpbin("get"), headers=invalid_header)
1790 assert key in str(excinfo.value)
1791
1792 @pytest.mark.parametrize(
1793 "invalid_header",
1794 (
1795 {"foo": "bar\r\nbaz: qux"},
1796 {"foo": "bar\n\rbaz: qux"},
1797 {"foo": "bar\nbaz: qux"},
1798 {"foo": "bar\rbaz: qux"},
1799 {"fo\ro": "bar"},
1800 {"fo\r\no": "bar"},
1801 {"fo\n\ro": "bar"},
1802 {"fo\no": "bar"},
1803 {"foo": "bar\n"},
1804 {"foo\n": "bar"},
1805 {"foo": "bar\r\n"},
1806 {"foo": "\n"},
1807 {"foo": "\r\n"},
1808 ),
1809 )
1810 def test_header_no_return_chars(self, httpbin, invalid_header):
1811 """Ensure that a header containing return character sequences raise an
1812 exception. Otherwise, multiple headers are created from single string.
1813 """
1814 with pytest.raises(InvalidHeader):
1815 requests.get(httpbin("get"), headers=invalid_header)
1816
1817 @pytest.mark.parametrize(
1818 "invalid_header",
1819 (
1820 {" foo": "bar"},
1821 {"\tfoo": "bar"},
1822 {" foo": "bar"},
1823 {"foo": " bar"},
1824 {"foo": " bar"},
1825 {"foo": "\tbar"},
1826 {" ": "bar"},
1827 ),
1828 )
1829 def test_header_no_leading_space(self, httpbin, invalid_header):
1830 """Ensure headers containing leading whitespace raise
1831 InvalidHeader Error before sending.
1832 """
1833 with pytest.raises(InvalidHeader):
1834 requests.get(httpbin("get"), headers=invalid_header)
1835
1836 def test_header_with_subclass_types(self, httpbin):
1837 """If the subclasses does not behave *exactly* like
1838 the base bytes/str classes, this is not supported.
1839 This test is for backwards compatibility.
1840 """
1841
1842 class MyString(str):
1843 pass
1844
1845 class MyBytes(bytes):
1846 pass
1847
1848 r_str = requests.get(httpbin("get"), headers={MyString("x-custom"): "myheader"})
1849 assert r_str.request.headers["x-custom"] == "myheader"
1850
1851 r_bytes = requests.get(
1852 httpbin("get"), headers={MyBytes(b"x-custom"): b"myheader"}
1853 )
1854 assert r_bytes.request.headers["x-custom"] == b"myheader"
1855
1856 r_mixed = requests.get(
1857 httpbin("get"), headers={MyString("x-custom"): MyBytes(b"myheader")}
1858 )
1859 assert r_mixed.request.headers["x-custom"] == b"myheader"
1860
1861 @pytest.mark.parametrize("files", ("foo", b"foo", bytearray(b"foo")))
1862 def test_can_send_objects_with_files(self, httpbin, files):
1863 data = {"a": "this is a string"}
1864 files = {"b": files}
1865 r = requests.Request("POST", httpbin("post"), data=data, files=files)
1866 p = r.prepare()
1867 assert "multipart/form-data" in p.headers["Content-Type"]
1868
1869 def test_can_send_file_object_with_non_string_filename(self, httpbin):
1870 f = io.BytesIO()
1871 f.name = 2
1872 r = requests.Request("POST", httpbin("post"), files={"f": f})
1873 p = r.prepare()
1874
1875 assert "multipart/form-data" in p.headers["Content-Type"]
1876
1877 def test_autoset_header_values_are_native(self, httpbin):
1878 data = "this is a string"
1879 length = "16"
1880 req = requests.Request("POST", httpbin("post"), data=data)
1881 p = req.prepare()
1882
1883 assert p.headers["Content-Length"] == length
1884
1885 def test_nonhttp_schemes_dont_check_URLs(self):
1886 test_urls = (
1887 "data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==",
1888 "file:///etc/passwd",
1889 "magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431",
1890 )
1891 for test_url in test_urls:
1892 req = requests.Request("GET", test_url)
1893 preq = req.prepare()
1894 assert test_url == preq.url
1895
1896 def test_auth_is_stripped_on_http_downgrade(
1897 self, httpbin, httpbin_secure, httpbin_ca_bundle
1898 ):
1899 r = requests.get(
1900 httpbin_secure("redirect-to"),
1901 params={"url": httpbin("get")},
1902 auth=("user", "pass"),
1903 verify=httpbin_ca_bundle,
1904 )
1905 assert r.history[0].request.headers["Authorization"]
1906 assert "Authorization" not in r.request.headers
1907
1908 def test_auth_is_retained_for_redirect_on_host(self, httpbin):
1909 r = requests.get(httpbin("redirect/1"), auth=("user", "pass"))
1910 h1 = r.history[0].request.headers["Authorization"]
1911 h2 = r.request.headers["Authorization"]
1912
1913 assert h1 == h2
1914
1915 def test_should_strip_auth_host_change(self):
1916 s = requests.Session()
1917 assert s.should_strip_auth(
1918 "http://example.com/foo", "http://another.example.com/"
1919 )
1920
1921 def test_should_strip_auth_http_downgrade(self):
1922 s = requests.Session()
1923 assert s.should_strip_auth("https://example.com/foo", "http://example.com/bar")
1924
1925 def test_should_strip_auth_https_upgrade(self):
1926 s = requests.Session()
1927 assert not s.should_strip_auth(
1928 "http://example.com/foo", "https://example.com/bar"
1929 )
1930 assert not s.should_strip_auth(
1931 "http://example.com:80/foo", "https://example.com/bar"
1932 )
1933 assert not s.should_strip_auth(
1934 "http://example.com/foo", "https://example.com:443/bar"
1935 )
1936 # Non-standard ports should trigger stripping
1937 assert s.should_strip_auth(
1938 "http://example.com:8080/foo", "https://example.com/bar"
1939 )
1940 assert s.should_strip_auth(
1941 "http://example.com/foo", "https://example.com:8443/bar"
1942 )
1943
1944 def test_should_strip_auth_port_change(self):
1945 s = requests.Session()
1946 assert s.should_strip_auth(
1947 "http://example.com:1234/foo", "https://example.com:4321/bar"
1948 )
1949
1950 @pytest.mark.parametrize(
1951 "old_uri, new_uri",
1952 (
1953 ("https://example.com:443/foo", "https://example.com/bar"),
1954 ("http://example.com:80/foo", "http://example.com/bar"),
1955 ("https://example.com/foo", "https://example.com:443/bar"),
1956 ("http://example.com/foo", "http://example.com:80/bar"),
1957 ),
1958 )
1959 def test_should_strip_auth_default_port(self, old_uri, new_uri):
1960 s = requests.Session()
1961 assert not s.should_strip_auth(old_uri, new_uri)
1962
1963 def test_manual_redirect_with_partial_body_read(self, httpbin):
1964 s = requests.Session()
1965 r1 = s.get(httpbin("redirect/2"), allow_redirects=False, stream=True)
1966 assert r1.is_redirect
1967 rg = s.resolve_redirects(r1, r1.request, stream=True)
1968
1969 # read only the first eight bytes of the response body,
1970 # then follow the redirect
1971 r1.iter_content(8)
1972 r2 = next(rg)
1973 assert r2.is_redirect
1974
1975 # read all of the response via iter_content,
1976 # then follow the redirect
1977 for _ in r2.iter_content():
1978 pass
1979 r3 = next(rg)
1980 assert not r3.is_redirect
1981
1982 def test_prepare_body_position_non_stream(self):
1983 data = b"the data"
1984 prep = requests.Request("GET", "http://example.com", data=data).prepare()
1985 assert prep._body_position is None
1986
1987 def test_rewind_body(self):
1988 data = io.BytesIO(b"the data")
1989 prep = requests.Request("GET", "http://example.com", data=data).prepare()
1990 assert prep._body_position == 0
1991 assert prep.body.read() == b"the data"
1992
1993 # the data has all been read
1994 assert prep.body.read() == b""
1995
1996 # rewind it back
1997 requests.utils.rewind_body(prep)
1998 assert prep.body.read() == b"the data"
1999
2000 def test_rewind_partially_read_body(self):
2001 data = io.BytesIO(b"the data")
2002 data.read(4) # read some data
2003 prep = requests.Request("GET", "http://example.com", data=data).prepare()
2004 assert prep._body_position == 4
2005 assert prep.body.read() == b"data"
2006
2007 # the data has all been read
2008 assert prep.body.read() == b""
2009
2010 # rewind it back
2011 requests.utils.rewind_body(prep)
2012 assert prep.body.read() == b"data"
2013
2014 def test_rewind_body_no_seek(self):
2015 class BadFileObj:
2016 def __init__(self, data):
2017 self.data = data
2018
2019 def tell(self):
2020 return 0
2021
2022 def __iter__(self):
2023 return
2024
2025 data = BadFileObj("the data")
2026 prep = requests.Request("GET", "http://example.com", data=data).prepare()
2027 assert prep._body_position == 0
2028
2029 with pytest.raises(UnrewindableBodyError) as e:
2030 requests.utils.rewind_body(prep)
2031
2032 assert "Unable to rewind request body" in str(e)
2033
2034 def test_rewind_body_failed_seek(self):
2035 class BadFileObj:
2036 def __init__(self, data):
2037 self.data = data
2038
2039 def tell(self):
2040 return 0
2041
2042 def seek(self, pos, whence=0):
2043 raise OSError()
2044
2045 def __iter__(self):
2046 return
2047
2048 data = BadFileObj("the data")
2049 prep = requests.Request("GET", "http://example.com", data=data).prepare()
2050 assert prep._body_position == 0
2051
2052 with pytest.raises(UnrewindableBodyError) as e:
2053 requests.utils.rewind_body(prep)
2054
2055 assert "error occurred when rewinding request body" in str(e)
2056
2057 def test_rewind_body_failed_tell(self):
2058 class BadFileObj:
2059 def __init__(self, data):
2060 self.data = data
2061
2062 def tell(self):
2063 raise OSError()
2064
2065 def __iter__(self):
2066 return
2067
2068 data = BadFileObj("the data")
2069 prep = requests.Request("GET", "http://example.com", data=data).prepare()
2070 assert prep._body_position is not None
2071
2072 with pytest.raises(UnrewindableBodyError) as e:
2073 requests.utils.rewind_body(prep)
2074
2075 assert "Unable to rewind request body" in str(e)
2076
2077 def test_getattr_proxy_stream_follows_redirect(self, httpbin):
2078 """Ensure stream wrappers that don't implement __iter__ directly are still detected."""
2079
2080 class AttrProxy:
2081 def __init__(self):
2082 self._file = io.BytesIO(b"data")
2083
2084 def __getattr__(self, name):
2085 return getattr(self._file, name)
2086
2087 r = requests.post(
2088 httpbin("redirect-to?url=/post&status_code=307"), data=AttrProxy()
2089 )
2090 assert r.json()["data"] == "data"
2091
2092 def _patch_adapter_gzipped_redirect(self, session, url):
2093 adapter = session.get_adapter(url=url)
2094 org_build_response = adapter.build_response
2095 self._patched_response = False
2096
2097 def build_response(*args, **kwargs):
2098 resp = org_build_response(*args, **kwargs)
2099 if not self._patched_response:
2100 resp.raw.headers["content-encoding"] = "gzip"
2101 self._patched_response = True
2102 return resp
2103
2104 adapter.build_response = build_response
2105
2106 def test_redirect_with_wrong_gzipped_header(self, httpbin):
2107 s = requests.Session()
2108 url = httpbin("redirect/1")
2109 self._patch_adapter_gzipped_redirect(s, url)
2110 s.get(url)
2111
2112 @pytest.mark.parametrize(
2113 "username, password, auth_str",
2114 (
2115 ("test", "test", "Basic dGVzdDp0ZXN0"),
2116 (
2117 "имя".encode(),
2118 "пароль".encode(),
2119 "Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA==",
2120 ),
2121 ),
2122 )
2123 def test_basic_auth_str_is_always_native(self, username, password, auth_str):
2124 s = _basic_auth_str(username, password)
2125 assert isinstance(s, builtin_str)
2126 assert s == auth_str
2127
2128 def test_requests_history_is_saved(self, httpbin):
2129 r = requests.get(httpbin("redirect/5"))
2130 total = r.history[-1].history
2131 i = 0
2132 for item in r.history:
2133 assert item.history == total[0:i]
2134 i += 1
2135
2136 def test_json_param_post_content_type_works(self, httpbin):
2137 r = requests.post(httpbin("post"), json={"life": 42})
2138 assert r.status_code == 200
2139 assert "application/json" in r.request.headers["Content-Type"]
2140 assert {"life": 42} == r.json()["json"]
2141
2142 def test_json_param_post_should_not_override_data_param(self, httpbin):
2143 r = requests.Request(
2144 method="POST",
2145 url=httpbin("post"),
2146 data={"stuff": "elixr"},
2147 json={"music": "flute"},
2148 )
2149 prep = r.prepare()
2150 assert "stuff=elixr" == prep.body
2151
2152 def test_response_iter_lines(self, httpbin):
2153 r = requests.get(httpbin("stream/4"), stream=True)
2154 assert r.status_code == 200
2155
2156 it = r.iter_lines()
2157 next(it)
2158 assert len(list(it)) == 3
2159
2160 def test_response_context_manager(self, httpbin):
2161 with requests.get(httpbin("stream/4"), stream=True) as response:
2162 assert isinstance(response, requests.Response)
2163
2164 assert response.raw.closed
2165
2166 def test_unconsumed_session_response_closes_connection(self, httpbin):
2167 s = requests.session()
2168
2169 with contextlib.closing(s.get(httpbin("stream/4"), stream=True)) as response:
2170 pass
2171
2172 assert response._content_consumed is False
2173 assert response.raw.closed
2174
2175 @pytest.mark.xfail
2176 def test_response_iter_lines_reentrant(self, httpbin):
2177 """Response.iter_lines() is not reentrant safe"""
2178 r = requests.get(httpbin("stream/4"), stream=True)
2179 assert r.status_code == 200
2180
2181 next(r.iter_lines())
2182 assert len(list(r.iter_lines())) == 3
2183
2184 def test_session_close_proxy_clear(self):
2185 proxies = {
2186 "one": mock.Mock(),
2187 "two": mock.Mock(),
2188 }
2189 session = requests.Session()
2190 with mock.patch.dict(session.adapters["http://"].proxy_manager, proxies):
2191 session.close()
2192 proxies["one"].clear.assert_called_once_with()
2193 proxies["two"].clear.assert_called_once_with()
2194
2195 def test_proxy_auth(self):
2196 adapter = HTTPAdapter()
2197 headers = adapter.proxy_headers("http://user:[email protected]")
2198 assert headers == {"Proxy-Authorization": "Basic dXNlcjpwYXNz"}
2199
2200 def test_proxy_auth_empty_pass(self):
2201 adapter = HTTPAdapter()
2202 headers = adapter.proxy_headers("http://user:@httpbin.org")
2203 assert headers == {"Proxy-Authorization": "Basic dXNlcjo="}
2204
2205 def test_response_json_when_content_is_None(self, httpbin):
2206 r = requests.get(httpbin("/status/204"))
2207 # Make sure r.content is None
2208 r.status_code = 0
2209 r._content = False
2210 r._content_consumed = False
2211
2212 assert r.content is None
2213 with pytest.raises(ValueError):
2214 r.json()
2215
2216 def test_response_without_release_conn(self):
2217 """Test `close` call for non-urllib3-like raw objects.
2218 Should work when `release_conn` attr doesn't exist on `response.raw`.
2219 """
2220 resp = requests.Response()
2221 resp.raw = StringIO.StringIO("test")
2222 assert not resp.raw.closed
2223 resp.close()
2224 assert resp.raw.closed
2225
2226 def test_empty_stream_with_auth_does_not_set_content_length_header(self, httpbin):
2227 """Ensure that a byte stream with size 0 will not set both a Content-Length
2228 and Transfer-Encoding header.
2229 """
2230 auth = ("user", "pass")
2231 url = httpbin("post")
2232 file_obj = io.BytesIO(b"")
2233 r = requests.Request("POST", url, auth=auth, data=file_obj)
2234 prepared_request = r.prepare()
2235 assert "Transfer-Encoding" in prepared_request.headers
2236 assert "Content-Length" not in prepared_request.headers
2237
2238 def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):
2239 """Ensure that a byte stream with size > 0 will not set both a Content-Length
2240 and Transfer-Encoding header.
2241 """
2242 auth = ("user", "pass")
2243 url = httpbin("post")
2244 file_obj = io.BytesIO(b"test data")
2245 r = requests.Request("POST", url, auth=auth, data=file_obj)
2246 prepared_request = r.prepare()
2247 assert "Transfer-Encoding" not in prepared_request.headers
2248 assert "Content-Length" in prepared_request.headers
2249
2250 def test_chunked_upload_does_not_set_content_length_header(self, httpbin):
2251 """Ensure that requests with a generator body stream using
2252 Transfer-Encoding: chunked, not a Content-Length header.
2253 """
2254 data = (i for i in [b"a", b"b", b"c"])
2255 url = httpbin("post")
2256 r = requests.Request("POST", url, data=data)
2257 prepared_request = r.prepare()
2258 assert "Transfer-Encoding" in prepared_request.headers
2259 assert "Content-Length" not in prepared_request.headers
2260
2261 def test_custom_redirect_mixin(self, httpbin):
2262 """Tests a custom mixin to overwrite ``get_redirect_target``.
2263
2264 Ensures a subclassed ``requests.Session`` can handle a certain type of
2265 malformed redirect responses.
2266
2267 1. original request receives a proper response: 302 redirect
2268 2. following the redirect, a malformed response is given:
2269 status code = HTTP 200
2270 location = alternate url
2271 3. the custom session catches the edge case and follows the redirect
2272 """
2273 url_final = httpbin("html")
2274 querystring_malformed = urlencode({"location": url_final})
2275 url_redirect_malformed = httpbin("response-headers?%s" % querystring_malformed)
2276 querystring_redirect = urlencode({"url": url_redirect_malformed})
2277 url_redirect = httpbin("redirect-to?%s" % querystring_redirect)
2278 urls_test = [
2279 url_redirect,
2280 url_redirect_malformed,
2281 url_final,
2282 ]
2283
2284 class CustomRedirectSession(requests.Session):
2285 def get_redirect_target(self, resp):
2286 # default behavior
2287 if resp.is_redirect:
2288 return resp.headers["location"]
2289 # edge case - check to see if 'location' is in headers anyways
2290 location = resp.headers.get("location")
2291 if location and (location != resp.url):
2292 return location
2293 return None
2294
2295 session = CustomRedirectSession()
2296 r = session.get(urls_test[0])
2297 assert len(r.history) == 2
2298 assert r.status_code == 200
2299 assert r.history[0].status_code == 302
2300 assert r.history[0].is_redirect
2301 assert r.history[1].status_code == 200
2302 assert not r.history[1].is_redirect
2303 assert r.url == urls_test[2]
2304
2305
2306 class TestCaseInsensitiveDict:
2307 @pytest.mark.parametrize(
2308 "cid",
2309 (
2310 CaseInsensitiveDict({"Foo": "foo", "BAr": "bar"}),
2311 CaseInsensitiveDict([("Foo", "foo"), ("BAr", "bar")]),
2312 CaseInsensitiveDict(FOO="foo", BAr="bar"),
2313 ),
2314 )
2315 def test_init(self, cid):
2316 assert len(cid) == 2
2317 assert "foo" in cid
2318 assert "bar" in cid
2319
2320 def test_docstring_example(self):
2321 cid = CaseInsensitiveDict()
2322 cid["Accept"] = "application/json"
2323 assert cid["aCCEPT"] == "application/json"
2324 assert list(cid) == ["Accept"]
2325
2326 def test_len(self):
2327 cid = CaseInsensitiveDict({"a": "a", "b": "b"})
2328 cid["A"] = "a"
2329 assert len(cid) == 2
2330
2331 def test_getitem(self):
2332 cid = CaseInsensitiveDict({"Spam": "blueval"})
2333 assert cid["spam"] == "blueval"
2334 assert cid["SPAM"] == "blueval"
2335
2336 def test_fixes_649(self):
2337 """__setitem__ should behave case-insensitively."""
2338 cid = CaseInsensitiveDict()
2339 cid["spam"] = "oneval"
2340 cid["Spam"] = "twoval"
2341 cid["sPAM"] = "redval"
2342 cid["SPAM"] = "blueval"
2343 assert cid["spam"] == "blueval"
2344 assert cid["SPAM"] == "blueval"
2345 assert list(cid.keys()) == ["SPAM"]
2346
2347 def test_delitem(self):
2348 cid = CaseInsensitiveDict()
2349 cid["Spam"] = "someval"
2350 del cid["sPam"]
2351 assert "spam" not in cid
2352 assert len(cid) == 0
2353
2354 def test_contains(self):
2355 cid = CaseInsensitiveDict()
2356 cid["Spam"] = "someval"
2357 assert "Spam" in cid
2358 assert "spam" in cid
2359 assert "SPAM" in cid
2360 assert "sPam" in cid
2361 assert "notspam" not in cid
2362
2363 def test_get(self):
2364 cid = CaseInsensitiveDict()
2365 cid["spam"] = "oneval"
2366 cid["SPAM"] = "blueval"
2367 assert cid.get("spam") == "blueval"
2368 assert cid.get("SPAM") == "blueval"
2369 assert cid.get("sPam") == "blueval"
2370 assert cid.get("notspam", "default") == "default"
2371
2372 def test_update(self):
2373 cid = CaseInsensitiveDict()
2374 cid["spam"] = "blueval"
2375 cid.update({"sPam": "notblueval"})
2376 assert cid["spam"] == "notblueval"
2377 cid = CaseInsensitiveDict({"Foo": "foo", "BAr": "bar"})
2378 cid.update({"fOO": "anotherfoo", "bAR": "anotherbar"})
2379 assert len(cid) == 2
2380 assert cid["foo"] == "anotherfoo"
2381 assert cid["bar"] == "anotherbar"
2382
2383 def test_update_retains_unchanged(self):
2384 cid = CaseInsensitiveDict({"foo": "foo", "bar": "bar"})
2385 cid.update({"foo": "newfoo"})
2386 assert cid["bar"] == "bar"
2387
2388 def test_iter(self):
2389 cid = CaseInsensitiveDict({"Spam": "spam", "Eggs": "eggs"})
2390 keys = frozenset(["Spam", "Eggs"])
2391 assert frozenset(iter(cid)) == keys
2392
2393 def test_equality(self):
2394 cid = CaseInsensitiveDict({"SPAM": "blueval", "Eggs": "redval"})
2395 othercid = CaseInsensitiveDict({"spam": "blueval", "eggs": "redval"})
2396 assert cid == othercid
2397 del othercid["spam"]
2398 assert cid != othercid
2399 assert cid == {"spam": "blueval", "eggs": "redval"}
2400 assert cid != object()
2401
2402 def test_setdefault(self):
2403 cid = CaseInsensitiveDict({"Spam": "blueval"})
2404 assert cid.setdefault("spam", "notblueval") == "blueval"
2405 assert cid.setdefault("notspam", "notblueval") == "notblueval"
2406
2407 def test_lower_items(self):
2408 cid = CaseInsensitiveDict(
2409 {
2410 "Accept": "application/json",
2411 "user-Agent": "requests",
2412 }
2413 )
2414 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())
2415 lowerkeyset = frozenset(["accept", "user-agent"])
2416 assert keyset == lowerkeyset
2417
2418 def test_preserve_key_case(self):
2419 cid = CaseInsensitiveDict(
2420 {
2421 "Accept": "application/json",
2422 "user-Agent": "requests",
2423 }
2424 )
2425 keyset = frozenset(["Accept", "user-Agent"])
2426 assert frozenset(i[0] for i in cid.items()) == keyset
2427 assert frozenset(cid.keys()) == keyset
2428 assert frozenset(cid) == keyset
2429
2430 def test_preserve_last_key_case(self):
2431 cid = CaseInsensitiveDict(
2432 {
2433 "Accept": "application/json",
2434 "user-Agent": "requests",
2435 }
2436 )
2437 cid.update({"ACCEPT": "application/json"})
2438 cid["USER-AGENT"] = "requests"
2439 keyset = frozenset(["ACCEPT", "USER-AGENT"])
2440 assert frozenset(i[0] for i in cid.items()) == keyset
2441 assert frozenset(cid.keys()) == keyset
2442 assert frozenset(cid) == keyset
2443
2444 def test_copy(self):
2445 cid = CaseInsensitiveDict(
2446 {
2447 "Accept": "application/json",
2448 "user-Agent": "requests",
2449 }
2450 )
2451 cid_copy = cid.copy()
2452 assert cid == cid_copy
2453 cid["changed"] = True
2454 assert cid != cid_copy
2455
2456
2457 class TestMorselToCookieExpires:
2458 """Tests for morsel_to_cookie when morsel contains expires."""
2459
2460 def test_expires_valid_str(self):
2461 """Test case where we convert expires from string time."""
2462
2463 morsel = Morsel()
2464 morsel["expires"] = "Thu, 01-Jan-1970 00:00:01 GMT"
2465 cookie = morsel_to_cookie(morsel)
2466 assert cookie.expires == 1
2467
2468 @pytest.mark.parametrize(
2469 "value, exception",
2470 (
2471 (100, TypeError),
2472 ("woops", ValueError),
2473 ),
2474 )
2475 def test_expires_invalid_int(self, value, exception):
2476 """Test case where an invalid type is passed for expires."""
2477 morsel = Morsel()
2478 morsel["expires"] = value
2479 with pytest.raises(exception):
2480 morsel_to_cookie(morsel)
2481
2482 def test_expires_none(self):
2483 """Test case where expires is None."""
2484
2485 morsel = Morsel()
2486 morsel["expires"] = None
2487 cookie = morsel_to_cookie(morsel)
2488 assert cookie.expires is None
2489
2490
2491 class TestMorselToCookieMaxAge:
2492 """Tests for morsel_to_cookie when morsel contains max-age."""
2493
2494 def test_max_age_valid_int(self):
2495 """Test case where a valid max age in seconds is passed."""
2496
2497 morsel = Morsel()
2498 morsel["max-age"] = 60
2499 cookie = morsel_to_cookie(morsel)
2500 assert isinstance(cookie.expires, int)
2501
2502 def test_max_age_invalid_str(self):
2503 """Test case where a invalid max age is passed."""
2504
2505 morsel = Morsel()
2506 morsel["max-age"] = "woops"
2507 with pytest.raises(TypeError):
2508 morsel_to_cookie(morsel)
2509
2510
2511 class TestTimeout:
2512 def test_stream_timeout(self, httpbin):
2513 try:
2514 requests.get(httpbin("delay/10"), timeout=2.0)
2515 except requests.exceptions.Timeout as e:
2516 assert "Read timed out" in e.args[0].args[0]
2517
2518 @pytest.mark.parametrize(
2519 "timeout, error_text",
2520 (
2521 ((3, 4, 5), "(connect, read)"),
2522 ("foo", "must be an int, float or None"),
2523 ),
2524 )
2525 def test_invalid_timeout(self, httpbin, timeout, error_text):
2526 with pytest.raises(ValueError) as e:
2527 requests.get(httpbin("get"), timeout=timeout)
2528 assert error_text in str(e)
2529
2530 @pytest.mark.parametrize("timeout", (None, Urllib3Timeout(connect=None, read=None)))
2531 def test_none_timeout(self, httpbin, timeout):
2532 """Check that you can set None as a valid timeout value.
2533
2534 To actually test this behavior, we'd want to check that setting the
2535 timeout to None actually lets the request block past the system default
2536 timeout. However, this would make the test suite unbearably slow.
2537 Instead we verify that setting the timeout to None does not prevent the
2538 request from succeeding.
2539 """
2540 r = requests.get(httpbin("get"), timeout=timeout)
2541 assert r.status_code == 200
2542
2543 @pytest.mark.parametrize(
2544 "timeout", ((None, 0.1), Urllib3Timeout(connect=None, read=0.1))
2545 )
2546 def test_read_timeout(self, httpbin, timeout):
2547 try:
2548 requests.get(httpbin("delay/10"), timeout=timeout)
2549 pytest.fail("The recv() request should time out.")
2550 except ReadTimeout:
2551 pass
2552
2553 @pytest.mark.parametrize(
2554 "timeout", ((0.1, None), Urllib3Timeout(connect=0.1, read=None))
2555 )
2556 def test_connect_timeout(self, timeout):
2557 try:
2558 requests.get(TARPIT, timeout=timeout)
2559 pytest.fail("The connect() request should time out.")
2560 except ConnectTimeout as e:
2561 assert isinstance(e, ConnectionError)
2562 assert isinstance(e, Timeout)
2563
2564 @pytest.mark.parametrize(
2565 "timeout", ((0.1, 0.1), Urllib3Timeout(connect=0.1, read=0.1))
2566 )
2567 def test_total_timeout_connect(self, timeout):
2568 try:
2569 requests.get(TARPIT, timeout=timeout)
2570 pytest.fail("The connect() request should time out.")
2571 except ConnectTimeout:
2572 pass
2573
2574 def test_encoded_methods(self, httpbin):
2575 """See: https://github.com/psf/requests/issues/2316"""
2576 r = requests.request(b"GET", httpbin("get"))
2577 assert r.ok
2578
2579
2580 SendCall = collections.namedtuple("SendCall", ("args", "kwargs"))
2581
2582
2583 class RedirectSession(SessionRedirectMixin):
2584 def __init__(self, order_of_redirects):
2585 self.redirects = order_of_redirects
2586 self.calls = []
2587 self.max_redirects = 30
2588 self.cookies = {}
2589 self.trust_env = False
2590
2591 def send(self, *args, **kwargs):
2592 self.calls.append(SendCall(args, kwargs))
2593 return self.build_response()
2594
2595 def build_response(self):
2596 request = self.calls[-1].args[0]
2597 r = requests.Response()
2598 r.url = request.url
2599
2600 try:
2601 r.status_code = int(self.redirects.pop(0))
2602 except IndexError:
2603 r.status_code = 200
2604
2605 r.headers = CaseInsensitiveDict({"Location": "/"})
2606 r.raw = self._build_raw()
2607 r.request = request
2608 return r
2609
2610 def _build_raw(self):
2611 string = StringIO.StringIO("")
2612 setattr(string, "release_conn", lambda *args: args)
2613 return string
2614
2615
2616 def test_json_encodes_as_bytes():
2617 # urllib3 expects bodies as bytes-like objects
2618 body = {"key": "value"}
2619 p = PreparedRequest()
2620 p.prepare(method="GET", url="https://www.example.com/", json=body)
2621 assert isinstance(p.body, bytes)
2622
2623
2624 def test_requests_are_updated_each_time(httpbin):
2625 session = RedirectSession([303, 307])
2626 prep = requests.Request("POST", httpbin("post")).prepare()
2627 r0 = session.send(prep)
2628 assert r0.request.method == "POST"
2629 assert session.calls[-1] == SendCall((r0.request,), {})
2630 redirect_generator = session.resolve_redirects(r0, prep)
2631 default_keyword_args = {
2632 "stream": False,
2633 "verify": True,
2634 "cert": None,
2635 "timeout": None,
2636 "allow_redirects": False,
2637 "proxies": {},
2638 }
2639 for response in redirect_generator:
2640 assert response.request.method == "GET"
2641 send_call = SendCall((response.request,), default_keyword_args)
2642 assert session.calls[-1] == send_call
2643
2644
2645 @pytest.mark.parametrize(
2646 "var,url,proxy",
2647 [
2648 ("http_proxy", "http://example.com", "socks5://proxy.com:9876"),
2649 ("https_proxy", "https://example.com", "socks5://proxy.com:9876"),
2650 ("all_proxy", "http://example.com", "socks5://proxy.com:9876"),
2651 ("all_proxy", "https://example.com", "socks5://proxy.com:9876"),
2652 ],
2653 )
2654 def test_proxy_env_vars_override_default(var, url, proxy):
2655 session = requests.Session()
2656 prep = PreparedRequest()
2657 prep.prepare(method="GET", url=url)
2658
2659 kwargs = {var: proxy}
2660 scheme = urlparse(url).scheme
2661 with override_environ(**kwargs):
2662 proxies = session.rebuild_proxies(prep, {})
2663 assert scheme in proxies
2664 assert proxies[scheme] == proxy
2665
2666
2667 @pytest.mark.parametrize(
2668 "data",
2669 (
2670 (("a", "b"), ("c", "d")),
2671 (("c", "d"), ("a", "b")),
2672 (("a", "b"), ("c", "d"), ("e", "f")),
2673 ),
2674 )
2675 def test_data_argument_accepts_tuples(data):
2676 """Ensure that the data argument will accept tuples of strings
2677 and properly encode them.
2678 """
2679 p = PreparedRequest()
2680 p.prepare(
2681 method="GET", url="http://www.example.com", data=data, hooks=default_hooks()
2682 )
2683 assert p.body == urlencode(data)
2684
2685
2686 @pytest.mark.parametrize(
2687 "kwargs",
2688 (
2689 None,
2690 {
2691 "method": "GET",
2692 "url": "http://www.example.com",
2693 "data": "foo=bar",
2694 "hooks": default_hooks(),
2695 },
2696 {
2697 "method": "GET",
2698 "url": "http://www.example.com",
2699 "data": "foo=bar",
2700 "hooks": default_hooks(),
2701 "cookies": {"foo": "bar"},
2702 },
2703 {"method": "GET", "url": "http://www.example.com/üniçø∂é"},
2704 ),
2705 )
2706 def test_prepared_copy(kwargs):
2707 p = PreparedRequest()
2708 if kwargs:
2709 p.prepare(**kwargs)
2710 copy = p.copy()
2711 for attr in ("method", "url", "headers", "_cookies", "body", "hooks"):
2712 assert getattr(p, attr) == getattr(copy, attr)
2713
2714
2715 def test_urllib3_retries(httpbin):
2716 from urllib3.util import Retry
2717
2718 s = requests.Session()
2719 s.mount("http://", HTTPAdapter(max_retries=Retry(total=2, status_forcelist=[500])))
2720
2721 with pytest.raises(RetryError):
2722 s.get(httpbin("status/500"))
2723
2724
2725 def test_urllib3_pool_connection_closed(httpbin):
2726 s = requests.Session()
2727 s.mount("http://", HTTPAdapter(pool_connections=0, pool_maxsize=0))
2728
2729 try:
2730 s.get(httpbin("status/200"))
2731 except ConnectionError as e:
2732 assert "Pool is closed." in str(e)
2733
2734
2735 class TestPreparingURLs:
2736 @pytest.mark.parametrize(
2737 "url,expected",
2738 (
2739 ("http://google.com", "http://google.com/"),
2740 ("http://ジェーピーニック.jp", "http://xn--hckqz9bzb1cyrb.jp/"),
2741 ("http://xn--n3h.net/", "http://xn--n3h.net/"),
2742 ("http://ジェーピーニック.jp".encode(), "http://xn--hckqz9bzb1cyrb.jp/"),
2743 ("http://straße.de/straße", "http://xn--strae-oqa.de/stra%C3%9Fe"),
2744 (
2745 "http://straße.de/straße".encode(),
2746 "http://xn--strae-oqa.de/stra%C3%9Fe",
2747 ),
2748 (
2749 "http://Königsgäßchen.de/straße",
2750 "http://xn--knigsgchen-b4a3dun.de/stra%C3%9Fe",
2751 ),
2752 (
2753 "http://Königsgäßchen.de/straße".encode(),
2754 "http://xn--knigsgchen-b4a3dun.de/stra%C3%9Fe",
2755 ),
2756 (b"http://xn--n3h.net/", "http://xn--n3h.net/"),
2757 (
2758 b"http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/",
2759 "http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/",
2760 ),
2761 (
2762 "http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/",
2763 "http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/",
2764 ),
2765 ),
2766 )
2767 def test_preparing_url(self, url, expected):
2768 def normalize_percent_encode(x):
2769 # Helper function that normalizes equivalent
2770 # percent-encoded bytes before comparisons
2771 for c in re.findall(r"%[a-fA-F0-9]{2}", x):
2772 x = x.replace(c, c.upper())
2773 return x
2774
2775 r = requests.Request("GET", url=url)
2776 p = r.prepare()
2777 assert normalize_percent_encode(p.url) == expected
2778
2779 @pytest.mark.parametrize(
2780 "url",
2781 (
2782 b"http://*.google.com",
2783 b"http://*",
2784 "http://*.google.com",
2785 "http://*",
2786 "http://☃.net/",
2787 ),
2788 )
2789 def test_preparing_bad_url(self, url):
2790 r = requests.Request("GET", url=url)
2791 with pytest.raises(requests.exceptions.InvalidURL):
2792 r.prepare()
2793
2794 @pytest.mark.parametrize("url, exception", (("http://:1", InvalidURL),))
2795 def test_redirecting_to_bad_url(self, httpbin, url, exception):
2796 with pytest.raises(exception):
2797 requests.get(httpbin("redirect-to"), params={"url": url})
2798
2799 @pytest.mark.parametrize(
2800 "input, expected",
2801 (
2802 (
2803 b"http+unix://%2Fvar%2Frun%2Fsocket/path%7E",
2804 "http+unix://%2Fvar%2Frun%2Fsocket/path~",
2805 ),
2806 (
2807 "http+unix://%2Fvar%2Frun%2Fsocket/path%7E",
2808 "http+unix://%2Fvar%2Frun%2Fsocket/path~",
2809 ),
2810 (
2811 b"mailto:[email protected]",
2812 "mailto:[email protected]",
2813 ),
2814 (
2815 "mailto:[email protected]",
2816 "mailto:[email protected]",
2817 ),
2818 (
2819 b"data:SSDimaUgUHl0aG9uIQ==",
2820 "data:SSDimaUgUHl0aG9uIQ==",
2821 ),
2822 ),
2823 )
2824 def test_url_mutation(self, input, expected):
2825 """
2826 This test validates that we correctly exclude some URLs from
2827 preparation, and that we handle others. Specifically, it tests that
2828 any URL whose scheme doesn't begin with "http" is left alone, and
2829 those whose scheme *does* begin with "http" are mutated.
2830 """
2831 r = requests.Request("GET", url=input)
2832 p = r.prepare()
2833 assert p.url == expected
2834
2835 @pytest.mark.parametrize(
2836 "input, params, expected",
2837 (
2838 (
2839 b"http+unix://%2Fvar%2Frun%2Fsocket/path",
2840 {"key": "value"},
2841 "http+unix://%2Fvar%2Frun%2Fsocket/path?key=value",
2842 ),
2843 (
2844 "http+unix://%2Fvar%2Frun%2Fsocket/path",
2845 {"key": "value"},
2846 "http+unix://%2Fvar%2Frun%2Fsocket/path?key=value",
2847 ),
2848 (
2849 b"mailto:[email protected]",
2850 {"key": "value"},
2851 "mailto:[email protected]",
2852 ),
2853 (
2854 "mailto:[email protected]",
2855 {"key": "value"},
2856 "mailto:[email protected]",
2857 ),
2858 ),
2859 )
2860 def test_parameters_for_nonstandard_schemes(self, input, params, expected):
2861 """
2862 Setting parameters for nonstandard schemes is allowed if those schemes
2863 begin with "http", and is forbidden otherwise.
2864 """
2865 r = requests.Request("GET", url=input, params=params)
2866 p = r.prepare()
2867 assert p.url == expected
2868
2869 def test_post_json_nan(self, httpbin):
2870 data = {"foo": float("nan")}
2871 with pytest.raises(requests.exceptions.InvalidJSONError):
2872 requests.post(httpbin("post"), json=data)
2873
2874 def test_json_decode_compatibility(self, httpbin):
2875 r = requests.get(httpbin("bytes/20"))
2876 with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:
2877 r.json()
2878 assert isinstance(excinfo.value, RequestException)
2879 assert isinstance(excinfo.value, JSONDecodeError)
2880 assert r.text not in str(excinfo.value)
2881
2882 def test_json_decode_persists_doc_attr(self, httpbin):
2883 r = requests.get(httpbin("bytes/20"))
2884 with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:
2885 r.json()
2886 assert excinfo.value.doc == r.text
2887
2888 def test_status_code_425(self):
2889 r1 = requests.codes.get("TOO_EARLY")
2890 r2 = requests.codes.get("too_early")
2891 r3 = requests.codes.get("UNORDERED")
2892 r4 = requests.codes.get("unordered")
2893 r5 = requests.codes.get("UNORDERED_COLLECTION")
2894 r6 = requests.codes.get("unordered_collection")
2895
2896 assert r1 == 425
2897 assert r2 == 425
2898 assert r3 == 425
2899 assert r4 == 425
2900 assert r5 == 425
2901 assert r6 == 425
2902
2903 def test_different_connection_pool_for_tls_settings_verify_True(self):
2904 def response_handler(sock):
2905 consume_socket_content(sock, timeout=0.5)
2906 sock.send(
2907 b"HTTP/1.1 200 OK\r\n"
2908 b"Content-Length: 18\r\n\r\n"
2909 b'\xff\xfe{\x00"\x00K0"\x00=\x00"\x00\xab0"\x00\r\n'
2910 )
2911
2912 s = requests.Session()
2913 close_server = threading.Event()
2914 server = TLSServer(
2915 handler=response_handler,
2916 wait_to_close_event=close_server,
2917 requests_to_handle=3,
2918 cert_chain="tests/certs/expired/server/server.pem",
2919 keyfile="tests/certs/expired/server/server.key",
2920 )
2921
2922 with server as (host, port):
2923 url = f"https://{host}:{port}"
2924 r1 = s.get(url, verify=False)
2925 assert r1.status_code == 200
2926
2927 # Cannot verify self-signed certificate
2928 with pytest.raises(requests.exceptions.SSLError):
2929 s.get(url)
2930
2931 close_server.set()
2932 assert 2 == len(s.adapters["https://"].poolmanager.pools)
2933
2934 def test_different_connection_pool_for_tls_settings_verify_bundle_expired_cert(
2935 self,
2936 ):
2937 def response_handler(sock):
2938 consume_socket_content(sock, timeout=0.5)
2939 sock.send(
2940 b"HTTP/1.1 200 OK\r\n"
2941 b"Content-Length: 18\r\n\r\n"
2942 b'\xff\xfe{\x00"\x00K0"\x00=\x00"\x00\xab0"\x00\r\n'
2943 )
2944
2945 s = requests.Session()
2946 close_server = threading.Event()
2947 server = TLSServer(
2948 handler=response_handler,
2949 wait_to_close_event=close_server,
2950 requests_to_handle=3,
2951 cert_chain="tests/certs/expired/server/server.pem",
2952 keyfile="tests/certs/expired/server/server.key",
2953 )
2954
2955 with server as (host, port):
2956 url = f"https://{host}:{port}"
2957 r1 = s.get(url, verify=False)
2958 assert r1.status_code == 200
2959
2960 # Has right trust bundle, but certificate expired
2961 with pytest.raises(requests.exceptions.SSLError):
2962 s.get(url, verify="tests/certs/expired/ca/ca.crt")
2963
2964 close_server.set()
2965 assert 2 == len(s.adapters["https://"].poolmanager.pools)
2966
2967 def test_different_connection_pool_for_tls_settings_verify_bundle_unexpired_cert(
2968 self,
2969 ):
2970 def response_handler(sock):
2971 consume_socket_content(sock, timeout=0.5)
2972 sock.send(
2973 b"HTTP/1.1 200 OK\r\n"
2974 b"Content-Length: 18\r\n\r\n"
2975 b'\xff\xfe{\x00"\x00K0"\x00=\x00"\x00\xab0"\x00\r\n'
2976 )
2977
2978 s = requests.Session()
2979 close_server = threading.Event()
2980 server = TLSServer(
2981 handler=response_handler,
2982 wait_to_close_event=close_server,
2983 requests_to_handle=3,
2984 cert_chain="tests/certs/valid/server/server.pem",
2985 keyfile="tests/certs/valid/server/server.key",
2986 )
2987
2988 with server as (host, port):
2989 url = f"https://{host}:{port}"
2990 r1 = s.get(url, verify=False)
2991 assert r1.status_code == 200
2992
2993 r2 = s.get(url, verify="tests/certs/valid/ca/ca.crt")
2994 assert r2.status_code == 200
2995
2996 close_server.set()
2997 assert 2 == len(s.adapters["https://"].poolmanager.pools)
2998
2999 def test_different_connection_pool_for_mtls_settings(self):
3000 client_cert = None
3001
3002 def response_handler(sock):
3003 nonlocal client_cert
3004 client_cert = sock.getpeercert()
3005 consume_socket_content(sock, timeout=0.5)
3006 sock.send(
3007 b"HTTP/1.1 200 OK\r\n"
3008 b"Content-Length: 18\r\n\r\n"
3009 b'\xff\xfe{\x00"\x00K0"\x00=\x00"\x00\xab0"\x00\r\n'
3010 )
3011
3012 s = requests.Session()
3013 close_server = threading.Event()
3014 server = TLSServer(
3015 handler=response_handler,
3016 wait_to_close_event=close_server,
3017 requests_to_handle=2,
3018 cert_chain="tests/certs/expired/server/server.pem",
3019 keyfile="tests/certs/expired/server/server.key",
3020 mutual_tls=True,
3021 cacert="tests/certs/expired/ca/ca.crt",
3022 )
3023
3024 cert = (
3025 "tests/certs/mtls/client/client.pem",
3026 "tests/certs/mtls/client/client.key",
3027 )
3028 with server as (host, port):
3029 url = f"https://{host}:{port}"
3030 r1 = s.get(url, verify=False, cert=cert)
3031 assert r1.status_code == 200
3032 with pytest.raises(requests.exceptions.SSLError):
3033 s.get(url, cert=cert)
3034 close_server.set()
3035
3036 assert client_cert is not None
3037
3038
3039 def test_content_length_for_bytes_data(httpbin):
3040 data = "This is a string containing multi-byte UTF-8 ☃️"
3041 encoded_data = data.encode("utf-8")
3042 length = str(len(encoded_data))
3043 req = requests.Request("POST", httpbin("post"), data=encoded_data)
3044 p = req.prepare()
3045
3046 assert p.headers["Content-Length"] == length
3047
3048
3049 @pytest.mark.skipif(
3050 is_urllib3_1,
3051 reason="urllib3 2.x encodes all strings to utf-8, urllib3 1.x uses latin-1",
3052 )
3053 def test_content_length_for_string_data_counts_bytes(httpbin):
3054 data = "This is a string containing multi-byte UTF-8 ☃️"
3055 length = str(len(data.encode("utf-8")))
3056 req = requests.Request("POST", httpbin("post"), data=data)
3057 p = req.prepare()
3058
3059 assert p.headers["Content-Length"] == length
3060
3061
3062 def test_json_decode_errors_are_serializable_deserializable():
3063 json_decode_error = requests.exceptions.JSONDecodeError(
3064 "Extra data",
3065 '{"responseCode":["706"],"data":null}{"responseCode":["706"],"data":null}',
3066 36,
3067 )
3068 deserialized_error = pickle.loads(pickle.dumps(json_decode_error))
3069 assert repr(json_decode_error) == repr(deserialized_error)