Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

2,375 lines · 82.0 KiB · Python

Last changed by

Merge pull request #4004 from Lukasa/prepare-2.14Cory Benfieldbefore adoptionbf1a2a4

History of this file

Take it

The walk stopped after 200 commits: lines older than 05d90b9 point at it.

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 1–21why, one step back
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import collections11import contextlib12import warnings1314import io15import requests16import pytest17from requests.adapters import HTTPAdapter18from requests.auth import HTTPDigestAuth, _basic_auth_str19from requests.compat import (20 Morsel, cookielib, getproxies, str, urlparse,21 builtin_str, OrderedDict)

Merge pull request #3591 from nateprewitt/3579_cookie_mergeCory Benfieldbefore adoption439451c

line 22why, one step back
22from requests.cookies import (

Merge pull request #3809 from JungWinter/masterCory Benfieldbefore adoptione2bd1f9

line 23why, one step back
23 cookiejar_from_dict, morsel_to_cookie)

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 24–26why, one step back
24from requests.exceptions import (
25 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,26 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

line 27why, one step back
27 ProxyError, InvalidHeader, UnrewindableBodyError)

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 28–35why, one step back
28from requests.models import PreparedRequest
29from requests.structures import CaseInsensitiveDict30from requests.sessions import SessionRedirectMixin31from requests.models import urlencode32from requests.hooks import default_hooks3334from .compat import StringIO, u35from .utils import override_environ

Merge pull request #3943 from leo-b/timeoutCory Benfieldbefore adoption342096a

line 36why, one step back
36from requests.packages.urllib3.util import Timeout as Urllib3Timeout

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 37–94why, one step back
37
38# Requests to this URL should always fail with a connection timeout (nothing39# listening on that port)40TARPIT = 'http://10.255.255.1'4142try:43 from ssl import SSLContext44 del SSLContext45 HAS_MODERN_SSL = True46except ImportError:47 HAS_MODERN_SSL = False4849try:50 requests.pyopenssl51 HAS_PYOPENSSL = True52except AttributeError:53 HAS_PYOPENSSL = False545556class TestRequests:5758 def test_entry_points(self):5960 requests.session61 requests.session().get62 requests.session().head63 requests.get64 requests.head65 requests.put66 requests.patch67 requests.post6869 @pytest.mark.parametrize(70 'exception, url', (71 (MissingSchema, 'hiwpefhipowhefopw'),72 (InvalidSchema, 'localhost:3128'),73 (InvalidSchema, 'localhost.localdomain:3128/'),74 (InvalidSchema, '10.122.1.1:3128/'),75 (InvalidURL, 'http://'),76 ))77 def test_invalid_url(self, exception, url):78 with pytest.raises(exception):79 requests.get(url)8081 def test_basic_building(self):82 req = requests.Request()83 req.url = 'http://kennethreitz.org/'84 req.data = {'life': '42'}8586 pr = req.prepare()87 assert pr.url == req.url88 assert pr.body == 'life=42'8990 @pytest.mark.parametrize('method', ('GET', 'HEAD'))91 def test_no_content_length(self, httpbin, method):92 req = requests.Request(method, httpbin(method.lower())).prepare()93 assert 'Content-Length' not in req.headers94

Merge pull request #3545 from nateprewitt/new_prepare_content_lengthIan Cordascobefore adoption9407d69

lines 95–104why, one step back
95 @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))
96 def test_no_body_content_length(self, httpbin, method):97 req = requests.Request(method, httpbin(method.lower())).prepare()98 assert req.headers['Content-Length'] == '0'99100 @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))101 def test_empty_content_length(self, httpbin, method):102 req = requests.Request(method, httpbin(method.lower()), data='').prepare()103 assert req.headers['Content-Length'] == '0'104

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 105–143why, one step back
105 def test_override_content_length(self, httpbin):
106 headers = {107 'Content-Length': 'not zero'108 }109 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()110 assert 'Content-Length' in r.headers111 assert r.headers['Content-Length'] == 'not zero'112113 def test_path_is_not_double_encoded(self):114 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()115116 assert request.path_url == '/get/test%20case'117118 @pytest.mark.parametrize(119 'url, expected', (120 ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),121 ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')122 ))123 def test_params_are_added_before_fragment(self, url, expected):124 request = requests.Request('GET', url, params={"a": "b"}).prepare()125 assert request.url == expected126127 def test_params_original_order_is_preserved_by_default(self):128 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))129 session = requests.Session()130 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)131 prep = session.prepare_request(request)132 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'133134 def test_params_bytes_are_encoded(self):135 request = requests.Request('GET', 'http://example.com',136 params=b'test=foo').prepare()137 assert request.url == 'http://example.com/?test=foo'138139 def test_binary_put(self):140 request = requests.Request('PUT', 'http://example.com',141 data=u"ööö".encode("utf-8")).prepare()142 assert isinstance(request.body, bytes)143

Merge pull request #3697 from hussaintamboli/masterCory Benfieldbefore adoption1e198f9

lines 144–148why, one step back
144 def test_whitespaces_are_removed_from_url(self):
145 # Test for issue #3696146 request = requests.Request('GET', ' http://example.com').prepare()147 assert request.url == 'http://example.com/'148

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 149–173why, one step back
149 @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))
150 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):151 s = requests.Session()152 s.proxies = getproxies()153 parts = urlparse(httpbin('get'))154 url = scheme + parts.netloc + parts.path155 r = requests.Request('GET', url)156 r = s.send(r.prepare())157 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)158159 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):160 r = requests.Request('GET', httpbin('get'))161 s = requests.Session()162 s.proxies = getproxies()163164 r = s.send(r.prepare())165166 assert r.status_code == 200167168 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):169 r = requests.get(httpbin('redirect', '1'))170 assert r.status_code == 200171 assert r.history[0].status_code == 302172 assert r.history[0].is_redirect173

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

lines 174–188why, one step back
174 def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):
175 r = requests.post(httpbin('redirect-to'), data='test', params={'url': 'post', 'status_code': 307})176 assert r.status_code == 200177 assert r.history[0].status_code == 307178 assert r.history[0].is_redirect179 assert r.json()['data'] == 'test'180181 def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):182 byte_str = b'test'183 r = requests.post(httpbin('redirect-to'), data=io.BytesIO(byte_str), params={'url': 'post', 'status_code': 307})184 assert r.status_code == 200185 assert r.history[0].status_code == 307186 assert r.history[0].is_redirect187 assert r.json()['data'] == byte_str.decode('utf-8')188

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 189–255why, one step back
189 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):
190 try:191 requests.get(httpbin('relative-redirect', '50'))192 except TooManyRedirects as e:193 url = httpbin('relative-redirect', '20')194 assert e.request.url == url195 assert e.response.url == url196 assert len(e.response.history) == 30197 else:198 pytest.fail('Expected redirect to raise TooManyRedirects but it did not')199200 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):201 s = requests.session()202 s.max_redirects = 5203 try:204 s.get(httpbin('relative-redirect', '50'))205 except TooManyRedirects as e:206 url = httpbin('relative-redirect', '45')207 assert e.request.url == url208 assert e.response.url == url209 assert len(e.response.history) == 5210 else:211 pytest.fail('Expected custom max number of redirects to be respected but was not')212213 def test_http_301_changes_post_to_get(self, httpbin):214 r = requests.post(httpbin('status', '301'))215 assert r.status_code == 200216 assert r.request.method == 'GET'217 assert r.history[0].status_code == 301218 assert r.history[0].is_redirect219220 def test_http_301_doesnt_change_head_to_get(self, httpbin):221 r = requests.head(httpbin('status', '301'), allow_redirects=True)222 print(r.content)223 assert r.status_code == 200224 assert r.request.method == 'HEAD'225 assert r.history[0].status_code == 301226 assert r.history[0].is_redirect227228 def test_http_302_changes_post_to_get(self, httpbin):229 r = requests.post(httpbin('status', '302'))230 assert r.status_code == 200231 assert r.request.method == 'GET'232 assert r.history[0].status_code == 302233 assert r.history[0].is_redirect234235 def test_http_302_doesnt_change_head_to_get(self, httpbin):236 r = requests.head(httpbin('status', '302'), allow_redirects=True)237 assert r.status_code == 200238 assert r.request.method == 'HEAD'239 assert r.history[0].status_code == 302240 assert r.history[0].is_redirect241242 def test_http_303_changes_post_to_get(self, httpbin):243 r = requests.post(httpbin('status', '303'))244 assert r.status_code == 200245 assert r.request.method == 'GET'246 assert r.history[0].status_code == 303247 assert r.history[0].is_redirect248249 def test_http_303_doesnt_change_head_to_get(self, httpbin):250 r = requests.head(httpbin('status', '303'), allow_redirects=True)251 assert r.status_code == 200252 assert r.request.method == 'HEAD'253 assert r.history[0].status_code == 303254 assert r.history[0].is_redirect255

Merge pull request #3493 from nateprewitt/3490_drop_headersIan Cordascobefore adoptionf5ff345

lines 256–295why, one step back
256 def test_header_and_body_removal_on_redirect(self, httpbin):
257 purged_headers = ('Content-Length', 'Content-Type')258 ses = requests.Session()259 req = requests.Request('POST', httpbin('post'), data={'test': 'data'})260 prep = ses.prepare_request(req)261 resp = ses.send(prep)262263 # Mimic a redirect response264 resp.status_code = 302265 resp.headers['location'] = 'get'266267 # Run request through resolve_redirects268 next_resp = next(ses.resolve_redirects(resp, prep))269 assert next_resp.request.body is None270 for header in purged_headers:271 assert header not in next_resp.request.headers272273 def test_transfer_enc_removal_on_redirect(self, httpbin):274 purged_headers = ('Transfer-Encoding', 'Content-Type')275 ses = requests.Session()276 req = requests.Request('POST', httpbin('post'), data=(b'x' for x in range(1)))277 prep = ses.prepare_request(req)278 assert 'Transfer-Encoding' in prep.headers279280 # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33281 resp = requests.Response()282 resp.raw = io.BytesIO(b'the content')283 resp.request = prep284 setattr(resp.raw, 'release_conn', lambda *args: args)285286 # Mimic a redirect response287 resp.status_code = 302288 resp.headers['location'] = httpbin('get')289290 # Run request through resolve_redirect291 next_resp = next(ses.resolve_redirects(resp, prep))292 assert next_resp.request.body is None293 for header in purged_headers:294 assert header not in next_resp.request.headers295

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 296–377why, one step back
296 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):
297 heads = {'User-agent': 'Mozilla/5.0'}298299 r = requests.get(httpbin('user-agent'), headers=heads)300301 assert heads['User-agent'] in r.text302 assert r.status_code == 200303304 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):305 heads = {'User-agent': 'Mozilla/5.0'}306307 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)308 assert r.status_code == 200309310 def test_set_cookie_on_301(self, httpbin):311 s = requests.session()312 url = httpbin('cookies/set?foo=bar')313 s.get(url)314 assert s.cookies['foo'] == 'bar'315316 def test_cookie_sent_on_redirect(self, httpbin):317 s = requests.session()318 s.get(httpbin('cookies/set?foo=bar'))319 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')320 assert 'Cookie' in r.json()['headers']321322 def test_cookie_removed_on_expire(self, httpbin):323 s = requests.session()324 s.get(httpbin('cookies/set?foo=bar'))325 assert s.cookies['foo'] == 'bar'326 s.get(327 httpbin('response-headers'),328 params={329 'Set-Cookie':330 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'331 }332 )333 assert 'foo' not in s.cookies334335 def test_cookie_quote_wrapped(self, httpbin):336 s = requests.session()337 s.get(httpbin('cookies/set?foo="bar:baz"'))338 assert s.cookies['foo'] == '"bar:baz"'339340 def test_cookie_persists_via_api(self, httpbin):341 s = requests.session()342 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})343 assert 'foo' in r.request.headers['Cookie']344 assert 'foo' in r.history[0].request.headers['Cookie']345346 def test_request_cookie_overrides_session_cookie(self, httpbin):347 s = requests.session()348 s.cookies['foo'] = 'bar'349 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})350 assert r.json()['cookies']['foo'] == 'baz'351 # Session cookie should not be modified352 assert s.cookies['foo'] == 'bar'353354 def test_request_cookies_not_persisted(self, httpbin):355 s = requests.session()356 s.get(httpbin('cookies'), cookies={'foo': 'baz'})357 # Sending a request with cookies should not add cookies to the session358 assert not s.cookies359360 def test_generic_cookiejar_works(self, httpbin):361 cj = cookielib.CookieJar()362 cookiejar_from_dict({'foo': 'bar'}, cj)363 s = requests.session()364 s.cookies = cj365 r = s.get(httpbin('cookies'))366 # Make sure the cookie was sent367 assert r.json()['cookies']['foo'] == 'bar'368 # Make sure the session cj is still the custom one369 assert s.cookies is cj370371 def test_param_cookiejar_works(self, httpbin):372 cj = cookielib.CookieJar()373 cookiejar_from_dict({'foo': 'bar'}, cj)374 s = requests.session()375 r = s.get(httpbin('cookies'), cookies=cj)376 # Make sure the cookie was sent377 assert r.json()['cookies']['foo'] == 'bar'

Merge pull request #3591 from nateprewitt/3579_cookie_mergeCory Benfieldbefore adoption439451c

lines 378–409why, one step back
378
379 def test_cookielib_cookiejar_on_redirect(self, httpbin):380 """Tests resolve_redirect doesn't fail when merging cookies381 with non-RequestsCookieJar cookiejar.382383 See GH #3579384 """385 cj = cookiejar_from_dict({'foo': 'bar'}, cookielib.CookieJar())386 s = requests.Session()387 s.cookies = cookiejar_from_dict({'cookie': 'tasty'})388389 # Prepare request without using Session390 req = requests.Request('GET', httpbin('headers'), cookies=cj)391 prep_req = req.prepare()392393 # Send request and simulate redirect394 resp = s.send(prep_req)395 resp.status_code = 302396 resp.headers['location'] = httpbin('get')397 redirects = s.resolve_redirects(resp, prep_req)398 resp = next(redirects)399400 # Verify CookieJar isn't being converted to RequestsCookieJar401 assert isinstance(prep_req._cookies, cookielib.CookieJar)402 assert isinstance(resp.request._cookies, cookielib.CookieJar)403 assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)404405 cookies = {}406 for c in resp.request._cookies:407 cookies[c.name] = c.value408 assert cookies['foo'] == 'bar'409 assert cookies['cookie'] == 'tasty'

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 410–484why, one step back
410
411 def test_requests_in_history_are_not_overridden(self, httpbin):412 resp = requests.get(httpbin('redirect/3'))413 urls = [r.url for r in resp.history]414 req_urls = [r.request.url for r in resp.history]415 assert urls == req_urls416417 def test_history_is_always_a_list(self, httpbin):418 """Show that even with redirects, Response.history is always a list."""419 resp = requests.get(httpbin('get'))420 assert isinstance(resp.history, list)421 resp = requests.get(httpbin('redirect/1'))422 assert isinstance(resp.history, list)423 assert not isinstance(resp.history, tuple)424425 def test_headers_on_session_with_None_are_not_sent(self, httpbin):426 """Do not send headers in Session.headers with None values."""427 ses = requests.Session()428 ses.headers['Accept-Encoding'] = None429 req = requests.Request('GET', httpbin('get'))430 prep = ses.prepare_request(req)431 assert 'Accept-Encoding' not in prep.headers432433 def test_headers_preserve_order(self, httpbin):434 """Preserve order when headers provided as OrderedDict."""435 ses = requests.Session()436 ses.headers = OrderedDict()437 ses.headers['Accept-Encoding'] = 'identity'438 ses.headers['First'] = '1'439 ses.headers['Second'] = '2'440 headers = OrderedDict([('Third', '3'), ('Fourth', '4')])441 headers['Fifth'] = '5'442 headers['Second'] = '222'443 req = requests.Request('GET', httpbin('get'), headers=headers)444 prep = ses.prepare_request(req)445 items = list(prep.headers.items())446 assert items[0] == ('Accept-Encoding', 'identity')447 assert items[1] == ('First', '1')448 assert items[2] == ('Second', '222')449 assert items[3] == ('Third', '3')450 assert items[4] == ('Fourth', '4')451 assert items[5] == ('Fifth', '5')452453 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))454 def test_user_agent_transfers(self, httpbin, key):455456 heads = {key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'}457458 r = requests.get(httpbin('user-agent'), headers=heads)459 assert heads[key] in r.text460461 def test_HTTP_200_OK_HEAD(self, httpbin):462 r = requests.head(httpbin('get'))463 assert r.status_code == 200464465 def test_HTTP_200_OK_PUT(self, httpbin):466 r = requests.put(httpbin('put'))467 assert r.status_code == 200468469 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):470 auth = ('user', 'pass')471 url = httpbin('basic-auth', 'user', 'pass')472473 r = requests.get(url, auth=auth)474 assert r.status_code == 200475476 r = requests.get(url)477 assert r.status_code == 401478479 s = requests.session()480 s.auth = auth481 r = s.get(url)482 assert r.status_code == 200483484 @pytest.mark.parametrize(

Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44

lines 485–487why, one step back
485 'username, password', (
486 ('user', 'pass'),487 (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8')),

Merge pull request #3760 from sigmavirus24/deprecation-warningCory Benfieldbefore adoption4683f16

lines 488–489why, one step back
488 (42, 42),
489 (None, None),

Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44

lines 490–498why, one step back
490 ))
491 def test_set_basicauth(self, httpbin, username, password):492 auth = (username, password)493 url = httpbin('get')494495 r = requests.Request('GET', url, auth=auth)496 p = r.prepare()497498 assert p.headers['Authorization'] == _basic_auth_str(username, password)

Merge pull request #3758 from nateprewitt/3753_allow_non_string_params_basic_authCory Benfieldbefore adoption449d748

lines 499–508why, one step back
499
500 def test_basicauth_encodes_byte_strings(self):501 """Ensure b'test' formats as the byte string "test" rather502 than the unicode string "b'test'" in Python 3.503 """504 auth = (b'\xc5\xafsername', b'test\xc6\xb6')505 r = requests.Request('GET', 'http://localhost', auth=auth)506 p = r.prepare()507508 assert p.headers['Authorization'] == 'Basic xa9zZXJuYW1lOnRlc3TGtg=='

Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44

lines 509–510why, one step back
509
510 @pytest.mark.parametrize(

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 511–635why, one step back
511 'url, exception', (
512 # Connecting to an unknown domain should raise a ConnectionError513 ('http://doesnotexist.google.com', ConnectionError),514 # Connecting to an invalid port should raise a ConnectionError515 ('http://localhost:1', ConnectionError),516 # Inputing a URL that cannot be parsed should raise an InvalidURL error517 ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)518 ))519 def test_errors(self, url, exception):520 with pytest.raises(exception):521 requests.get(url, timeout=1)522523 def test_proxy_error(self):524 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError525 with pytest.raises(ProxyError):526 requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})527528 def test_basicauth_with_netrc(self, httpbin):529 auth = ('user', 'pass')530 wrong_auth = ('wronguser', 'wrongpass')531 url = httpbin('basic-auth', 'user', 'pass')532533 old_auth = requests.sessions.get_netrc_auth534535 try:536 def get_netrc_auth_mock(url):537 return auth538 requests.sessions.get_netrc_auth = get_netrc_auth_mock539540 # Should use netrc and work.541 r = requests.get(url)542 assert r.status_code == 200543544 # Given auth should override and fail.545 r = requests.get(url, auth=wrong_auth)546 assert r.status_code == 401547548 s = requests.session()549550 # Should use netrc and work.551 r = s.get(url)552 assert r.status_code == 200553554 # Given auth should override and fail.555 s.auth = wrong_auth556 r = s.get(url)557 assert r.status_code == 401558 finally:559 requests.sessions.get_netrc_auth = old_auth560561 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):562563 auth = HTTPDigestAuth('user', 'pass')564 url = httpbin('digest-auth', 'auth', 'user', 'pass')565566 r = requests.get(url, auth=auth)567 assert r.status_code == 200568569 r = requests.get(url)570 assert r.status_code == 401571572 s = requests.session()573 s.auth = HTTPDigestAuth('user', 'pass')574 r = s.get(url)575 assert r.status_code == 200576577 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):578 url = httpbin('digest-auth', 'auth', 'user', 'pass')579 auth = HTTPDigestAuth('user', 'pass')580 r = requests.get(url)581 assert r.cookies['fake'] == 'fake_value'582583 r = requests.get(url, auth=auth)584 assert r.status_code == 200585586 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):587 url = httpbin('digest-auth', 'auth', 'user', 'pass')588 auth = HTTPDigestAuth('user', 'pass')589 s = requests.Session()590 s.get(url, auth=auth)591 assert s.cookies['fake'] == 'fake_value'592593 def test_DIGEST_STREAM(self, httpbin):594595 auth = HTTPDigestAuth('user', 'pass')596 url = httpbin('digest-auth', 'auth', 'user', 'pass')597598 r = requests.get(url, auth=auth, stream=True)599 assert r.raw.read() != b''600601 r = requests.get(url, auth=auth, stream=False)602 assert r.raw.read() == b''603604 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):605606 auth = HTTPDigestAuth('user', 'wrongpass')607 url = httpbin('digest-auth', 'auth', 'user', 'pass')608609 r = requests.get(url, auth=auth)610 assert r.status_code == 401611612 r = requests.get(url)613 assert r.status_code == 401614615 s = requests.session()616 s.auth = auth617 r = s.get(url)618 assert r.status_code == 401619620 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):621622 auth = HTTPDigestAuth('user', 'pass')623 url = httpbin('digest-auth', 'auth', 'user', 'pass')624625 r = requests.get(url, auth=auth)626 assert '"auth"' in r.request.headers['Authorization']627628 def test_POSTBIN_GET_POST_FILES(self, httpbin):629630 url = httpbin('post')631 requests.post(url).raise_for_status()632633 post1 = requests.post(url, data={'some': 'data'})634 assert post1.status_code == 200635

fix broken testsKenneth Reitzbefore adoption97b5bc2

line 636why, one step back
636 with open('Pipfile') as f:

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 637–695why, one step back
637 post2 = requests.post(url, files={'some': f})
638 assert post2.status_code == 200639640 post4 = requests.post(url, data='[{"some": "json"}]')641 assert post4.status_code == 200642643 with pytest.raises(ValueError):644 requests.post(url, files=['bad file data'])645646 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):647648 class TestStream(object):649 def __init__(self, data):650 self.data = data.encode()651 self.length = len(self.data)652 self.index = 0653654 def __len__(self):655 return self.length656657 def read(self, size=None):658 if size:659 ret = self.data[self.index:self.index + size]660 self.index += size661 else:662 ret = self.data[self.index:]663 self.index = self.length664 return ret665666 def tell(self):667 return self.index668669 def seek(self, offset, where=0):670 if where == 0:671 self.index = offset672 elif where == 1:673 self.index += offset674 elif where == 2:675 self.index = self.length + offset676677 test = TestStream('test')678 post1 = requests.post(httpbin('post'), data=test)679 assert post1.status_code == 200680 assert post1.json()['data'] == 'test'681682 test = TestStream('test')683 test.seek(2)684 post2 = requests.post(httpbin('post'), data=test)685 assert post2.status_code == 200686 assert post2.json()['data'] == 'st'687688 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):689690 url = httpbin('post')691 requests.post(url).raise_for_status()692693 post1 = requests.post(url, data={'some': 'data'})694 assert post1.status_code == 200695

fix broken testsKenneth Reitzbefore adoption97b5bc2

line 696why, one step back
696 with open('Pipfile') as f:

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 697–705why, one step back
697 post2 = requests.post(url, data={'some': 'data'}, files={'some': f})
698 assert post2.status_code == 200699700 post4 = requests.post(url, data='[{"some": "json"}]')701 assert post4.status_code == 200702703 with pytest.raises(ValueError):704 requests.post(url, files=['bad file data'])705

Merge pull request #3652 from gardiac2002/masterIan Cordascobefore adoption9deb603

lines 706–730why, one step back
706 def test_post_with_custom_mapping(self, httpbin):
707 class CustomMapping(collections.MutableMapping):708 def __init__(self, *args, **kwargs):709 self.data = dict(*args, **kwargs)710711 def __delitem__(self, key):712 del self.data[key]713714 def __getitem__(self, key):715 return self.data[key]716717 def __setitem__(self, key, value):718 self.data[key] = value719720 def __iter__(self):721 return iter(self.data)722723 def __len__(self):724 return len(self.data)725726 data = CustomMapping({'some': 'data'})727 url = httpbin('post')728 found_json = requests.post(url, data=data).json().get('form')729 assert found_json == {'some': 'data'}730

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 731–732why, one step back
731 def test_conflicting_post_params(self, httpbin):
732 url = httpbin('post')

fix broken testsKenneth Reitzbefore adoption97b5bc2

line 733why, one step back
733 with open('Pipfile') as f:

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 734–772why, one step back
734 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")
735 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")736737 def test_request_ok_set(self, httpbin):738 r = requests.get(httpbin('status', '404'))739 assert not r.ok740741 def test_status_raising(self, httpbin):742 r = requests.get(httpbin('status', '404'))743 with pytest.raises(requests.exceptions.HTTPError):744 r.raise_for_status()745746 r = requests.get(httpbin('status', '500'))747 assert not r.ok748749 def test_decompress_gzip(self, httpbin):750 r = requests.get(httpbin('gzip'))751 r.content.decode('ascii')752753 @pytest.mark.parametrize(754 'url, params', (755 ('/get', {'foo': 'føø'}),756 ('/get', {'føø': 'føø'}),757 ('/get', {'føø': 'føø'}),758 ('/get', {'foo': 'foo'}),759 ('ø', {'foo': 'foo'}),760 ))761 def test_unicode_get(self, httpbin, url, params):762 requests.get(httpbin(url), params=params)763764 def test_unicode_header_name(self, httpbin):765 requests.put(766 httpbin('put'),767 headers={str('Content-Type'): 'application/octet-stream'},768 data='\xff') # compat.str is unicode.769770 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):771 requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)772

Merge pull request #3927 from bagerard/raise_IOError_invalid_certificate_filesCory Benfieldbefore adoption993cbf5

lines 773–788why, one step back
773 def test_invalid_ca_certificate_path(self, httpbin_secure):
774 INVALID_PATH = '/garbage'775 with pytest.raises(IOError) as e:776 requests.get(httpbin_secure(), verify=INVALID_PATH)777 assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {0}'.format(INVALID_PATH)778779 def test_invalid_ssl_certificate_files(self, httpbin_secure):780 INVALID_PATH = '/garbage'781 with pytest.raises(IOError) as e:782 requests.get(httpbin_secure(), cert=INVALID_PATH)783 assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {0}'.format(INVALID_PATH)784785 with pytest.raises(IOError) as e:786 requests.get(httpbin_secure(), cert=('.', INVALID_PATH))787 assert str(e.value) == 'Could not find the TLS key file, invalid path: {0}'.format(INVALID_PATH)788

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 789–948why, one step back
789 def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):
790 """warnings are emitted with requests.get"""791 if HAS_MODERN_SSL or HAS_PYOPENSSL:792 warnings_expected = ('SubjectAltNameWarning', )793 else:794 warnings_expected = ('SNIMissingWarning',795 'InsecurePlatformWarning',796 'SubjectAltNameWarning', )797798 with pytest.warns(None) as warning_records:799 warnings.simplefilter('always')800 requests.get(httpbin_secure('status', '200'),801 verify=httpbin_ca_bundle)802803 warning_records = [item for item in warning_records804 if item.category.__name__ != 'ResourceWarning']805806 warnings_category = tuple(807 item.category.__name__ for item in warning_records)808 assert warnings_category == warnings_expected809810 def test_urlencoded_get_query_multivalued_param(self, httpbin):811812 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))813 assert r.status_code == 200814 assert r.url == httpbin('get?test=foo&test=baz')815816 def test_different_encodings_dont_break_post(self, httpbin):817 r = requests.post(httpbin('post'),818 data={'stuff': json.dumps({'a': 123})},819 params={'blah': 'asdf1234'},820 files={'file': ('test_requests.py', open(__file__, 'rb'))})821 assert r.status_code == 200822823 @pytest.mark.parametrize(824 'data', (825 {'stuff': u('ëlïxr')},826 {'stuff': u('ëlïxr').encode('utf-8')},827 {'stuff': 'elixr'},828 {'stuff': 'elixr'.encode('utf-8')},829 ))830 def test_unicode_multipart_post(self, httpbin, data):831 r = requests.post(httpbin('post'),832 data=data,833 files={'file': ('test_requests.py', open(__file__, 'rb'))})834 assert r.status_code == 200835836 def test_unicode_multipart_post_fieldnames(self, httpbin):837 filename = os.path.splitext(__file__)[0] + '.py'838 r = requests.Request(839 method='POST', url=httpbin('post'),840 data={'stuff'.encode('utf-8'): 'elixr'},841 files={'file': ('test_requests.py', open(filename, 'rb'))})842 prep = r.prepare()843 assert b'name="stuff"' in prep.body844 assert b'name="b\'stuff\'"' not in prep.body845846 def test_unicode_method_name(self, httpbin):847 files = {'file': open(__file__, 'rb')}848 r = requests.request(849 method=u('POST'), url=httpbin('post'), files=files)850 assert r.status_code == 200851852 def test_unicode_method_name_with_request_object(self, httpbin):853 files = {'file': open(__file__, 'rb')}854 s = requests.Session()855 req = requests.Request(u('POST'), httpbin('post'), files=files)856 prep = s.prepare_request(req)857 assert isinstance(prep.method, builtin_str)858 assert prep.method == 'POST'859860 resp = s.send(prep)861 assert resp.status_code == 200862863 def test_non_prepared_request_error(self):864 s = requests.Session()865 req = requests.Request(u('POST'), '/')866867 with pytest.raises(ValueError) as e:868 s.send(req)869 assert str(e.value) == 'You can only send PreparedRequests.'870871 def test_custom_content_type(self, httpbin):872 r = requests.post(873 httpbin('post'),874 data={'stuff': json.dumps({'a': 123})},875 files={876 'file1': ('test_requests.py', open(__file__, 'rb')),877 'file2': ('test_requests', open(__file__, 'rb'),878 'text/py-content-type')})879 assert r.status_code == 200880 assert b"text/py-content-type" in r.request.body881882 def test_hook_receives_request_arguments(self, httpbin):883 def hook(resp, **kwargs):884 assert resp is not None885 assert kwargs != {}886887 s = requests.Session()888 r = requests.Request('GET', httpbin(), hooks={'response': hook})889 prep = s.prepare_request(r)890 s.send(prep)891892 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):893 hook = lambda x, *args, **kwargs: x894 s = requests.Session()895 s.hooks['response'].append(hook)896 r = requests.Request('GET', httpbin())897 prep = s.prepare_request(r)898 assert prep.hooks['response'] != []899 assert prep.hooks['response'] == [hook]900901 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):902 hook1 = lambda x, *args, **kwargs: x903 hook2 = lambda x, *args, **kwargs: x904 assert hook1 is not hook2905 s = requests.Session()906 s.hooks['response'].append(hook2)907 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})908 prep = s.prepare_request(r)909 assert prep.hooks['response'] == [hook1]910911 def test_prepared_request_hook(self, httpbin):912 def hook(resp, **kwargs):913 resp.hook_working = True914 return resp915916 req = requests.Request('GET', httpbin(), hooks={'response': hook})917 prep = req.prepare()918919 s = requests.Session()920 s.proxies = getproxies()921 resp = s.send(prep)922923 assert hasattr(resp, 'hook_working')924925 def test_prepared_from_session(self, httpbin):926 class DummyAuth(requests.auth.AuthBase):927 def __call__(self, r):928 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'929 return r930931 req = requests.Request('GET', httpbin('headers'))932 assert not req.auth933934 s = requests.Session()935 s.auth = DummyAuth()936937 prep = s.prepare_request(req)938 resp = s.send(prep)939940 assert resp.json()['headers'][941 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'942943 def test_prepare_request_with_bytestring_url(self):944 req = requests.Request('GET', b'https://httpbin.org/')945 s = requests.Session()946 prep = s.prepare_request(req)947 assert prep.url == "https://httpbin.org/"948

Merge pull request #3606 from bbamsch/httpbinTestFixCory Benfieldbefore adoption022e23c

line 949why, one step back
949 def test_request_with_bytestring_host(self, httpbin):

Merge pull request #3598 from bbamsch/bytestringHostFixCory Benfieldbefore adoption5eabcb7

lines 950–952why, one step back
950 s = requests.Session()
951 resp = s.request(952 'GET',

Merge pull request #3606 from bbamsch/httpbinTestFixCory Benfieldbefore adoption022e23c

line 953why, one step back
953 httpbin('cookies/set?cookie=value'),

Merge pull request #3598 from bbamsch/bytestringHostFixCory Benfieldbefore adoption5eabcb7

lines 954–958why, one step back
954 allow_redirects=False,
955 headers={'Host': b'httpbin.org'}956 )957 assert resp.cookies.get('cookie') == 'value'958

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 959–1125why, one step back
959 def test_links(self):
960 r = requests.Response()961 r.headers = {962 'cache-control': 'public, max-age=60, s-maxage=60',963 'connection': 'keep-alive',964 'content-encoding': 'gzip',965 'content-type': 'application/json; charset=utf-8',966 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',967 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',968 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',969 'link': ('<https://api.github.com/users/kennethreitz/repos?'970 'page=2&per_page=10>; rel="next", <https://api.github.'971 'com/users/kennethreitz/repos?page=7&per_page=10>; '972 ' rel="last"'),973 'server': 'GitHub.com',974 'status': '200 OK',975 'vary': 'Accept',976 'x-content-type-options': 'nosniff',977 'x-github-media-type': 'github.beta',978 'x-ratelimit-limit': '60',979 'x-ratelimit-remaining': '57'980 }981 assert r.links['next']['rel'] == 'next'982983 def test_cookie_parameters(self):984 key = 'some_cookie'985 value = 'some_value'986 secure = True987 domain = 'test.com'988 rest = {'HttpOnly': True}989990 jar = requests.cookies.RequestsCookieJar()991 jar.set(key, value, secure=secure, domain=domain, rest=rest)992993 assert len(jar) == 1994 assert 'some_cookie' in jar995996 cookie = list(jar)[0]997 assert cookie.secure == secure998 assert cookie.domain == domain999 assert cookie._rest['HttpOnly'] == rest['HttpOnly']10001001 def test_cookie_as_dict_keeps_len(self):1002 key = 'some_cookie'1003 value = 'some_value'10041005 key1 = 'some_cookie1'1006 value1 = 'some_value1'10071008 jar = requests.cookies.RequestsCookieJar()1009 jar.set(key, value)1010 jar.set(key1, value1)10111012 d1 = dict(jar)1013 d2 = dict(jar.iteritems())1014 d3 = dict(jar.items())10151016 assert len(jar) == 21017 assert len(d1) == 21018 assert len(d2) == 21019 assert len(d3) == 210201021 def test_cookie_as_dict_keeps_items(self):1022 key = 'some_cookie'1023 value = 'some_value'10241025 key1 = 'some_cookie1'1026 value1 = 'some_value1'10271028 jar = requests.cookies.RequestsCookieJar()1029 jar.set(key, value)1030 jar.set(key1, value1)10311032 d1 = dict(jar)1033 d2 = dict(jar.iteritems())1034 d3 = dict(jar.items())10351036 assert d1['some_cookie'] == 'some_value'1037 assert d2['some_cookie'] == 'some_value'1038 assert d3['some_cookie1'] == 'some_value1'10391040 def test_cookie_as_dict_keys(self):1041 key = 'some_cookie'1042 value = 'some_value'10431044 key1 = 'some_cookie1'1045 value1 = 'some_value1'10461047 jar = requests.cookies.RequestsCookieJar()1048 jar.set(key, value)1049 jar.set(key1, value1)10501051 keys = jar.keys()1052 assert keys == list(keys)1053 # make sure one can use keys multiple times1054 assert list(keys) == list(keys)10551056 def test_cookie_as_dict_values(self):1057 key = 'some_cookie'1058 value = 'some_value'10591060 key1 = 'some_cookie1'1061 value1 = 'some_value1'10621063 jar = requests.cookies.RequestsCookieJar()1064 jar.set(key, value)1065 jar.set(key1, value1)10661067 values = jar.values()1068 assert values == list(values)1069 # make sure one can use values multiple times1070 assert list(values) == list(values)10711072 def test_cookie_as_dict_items(self):1073 key = 'some_cookie'1074 value = 'some_value'10751076 key1 = 'some_cookie1'1077 value1 = 'some_value1'10781079 jar = requests.cookies.RequestsCookieJar()1080 jar.set(key, value)1081 jar.set(key1, value1)10821083 items = jar.items()1084 assert items == list(items)1085 # make sure one can use items multiple times1086 assert list(items) == list(items)10871088 def test_cookie_duplicate_names_different_domains(self):1089 key = 'some_cookie'1090 value = 'some_value'1091 domain1 = 'test1.com'1092 domain2 = 'test2.com'10931094 jar = requests.cookies.RequestsCookieJar()1095 jar.set(key, value, domain=domain1)1096 jar.set(key, value, domain=domain2)1097 assert key in jar1098 items = jar.items()1099 assert len(items) == 211001101 # Verify that CookieConflictError is raised if domain is not specified1102 with pytest.raises(requests.cookies.CookieConflictError):1103 jar.get(key)11041105 # Verify that CookieConflictError is not raised if domain is specified1106 cookie = jar.get(key, domain=domain1)1107 assert cookie == value11081109 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1110 key = 'some_cookie'1111 value = 'some_value'1112 path = 'some_path'11131114 jar = requests.cookies.RequestsCookieJar()1115 jar.set(key, value, path=path)1116 jar.set(key, value)1117 with pytest.raises(requests.cookies.CookieConflictError):1118 jar.get(key)11191120 def test_time_elapsed_blank(self, httpbin):1121 r = requests.get(httpbin('get'))1122 td = r.elapsed1123 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)1124 assert total_seconds > 0.01125

Merge pull request #3718 from nsoranzo/masterCory Benfieldbefore adoption36c9c8c

lines 1126–1129why, one step back
1126 def test_empty_response_has_content_none(self):
1127 r = requests.Response()1128 assert r.content is None1129

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 1130–1169why, one step back
1130 def test_response_is_iterable(self):
1131 r = requests.Response()1132 io = StringIO.StringIO('abc')1133 read_ = io.read11341135 def read_mock(amt, decode_content=None):1136 return read_(amt)1137 setattr(io, 'read', read_mock)1138 r.raw = io1139 assert next(iter(r))1140 io.close()11411142 def test_response_decode_unicode(self):1143 """When called with decode_unicode, Response.iter_content should always1144 return unicode.1145 """1146 r = requests.Response()1147 r._content_consumed = True1148 r._content = b'the content'1149 r.encoding = 'ascii'11501151 chunks = r.iter_content(decode_unicode=True)1152 assert all(isinstance(chunk, str) for chunk in chunks)11531154 # also for streaming1155 r = requests.Response()1156 r.raw = io.BytesIO(b'the content')1157 r.encoding = 'ascii'1158 chunks = r.iter_content(decode_unicode=True)1159 assert all(isinstance(chunk, str) for chunk in chunks)11601161 def test_response_reason_unicode(self):1162 # check for unicode HTTP status1163 r = requests.Response()1164 r.url = u'unicode URL'1165 r.reason = u'Komponenttia ei löydy'.encode('utf-8')1166 r.status_code = 4041167 r.encoding = None1168 assert not r.ok # old behaviour - crashes here1169

Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693

lines 1170–1173why, one step back
1170 def test_response_reason_unicode_fallback(self):
1171 # check raise_status falls back to ISO-8859-11172 r = requests.Response()1173 r.url = 'some url'

Merge pull request #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

lines 1174–1175why, one step back
1174 reason = u'Komponenttia ei löydy'
1175 r.reason = reason.encode('latin-1')

Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693

lines 1176–1179why, one step back
1176 r.status_code = 500
1177 r.encoding = None1178 with pytest.raises(requests.exceptions.HTTPError) as e:1179 r.raise_for_status()

Merge pull request #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

line 1180why, one step back
1180 assert reason in e.value.args[0]

Merge pull request #3554 from nateprewitt/3538_fallback_to_ISO_8591_1Ian Cordascobefore adoption87f9693

line 1181why, one step back
1181

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 1182–1212why, one step back
1182 def test_response_chunk_size_type(self):
1183 """Ensure that chunk_size is passed as None or an integer, otherwise1184 raise a TypeError.1185 """1186 r = requests.Response()1187 r.raw = io.BytesIO(b'the content')1188 chunks = r.iter_content(1)1189 assert all(len(chunk) == 1 for chunk in chunks)11901191 r = requests.Response()1192 r.raw = io.BytesIO(b'the content')1193 chunks = r.iter_content(None)1194 assert list(chunks) == [b'the content']11951196 r = requests.Response()1197 r.raw = io.BytesIO(b'the content')1198 with pytest.raises(TypeError):1199 chunks = r.iter_content("1024")12001201 def test_request_and_response_are_pickleable(self, httpbin):1202 r = requests.get(httpbin('get'))12031204 # verify we can pickle the original request1205 assert pickle.loads(pickle.dumps(r.request))12061207 # verify we can pickle the response and that we have access to1208 # the original request.1209 pr = pickle.loads(pickle.dumps(r))1210 assert r.request.url == pr.request.url1211 assert r.request.headers == pr.request.headers1212

Merge pull request #3489 from nateprewitt/1558_pickling_prepared_requestCory Benfieldbefore adoptiond24da4a

lines 1213–1258why, one step back
1213 def test_prepared_request_is_pickleable(self, httpbin):
1214 p = requests.Request('GET', httpbin('get')).prepare()12151216 # Verify PreparedRequest can be pickled and unpickled1217 r = pickle.loads(pickle.dumps(p))1218 assert r.url == p.url1219 assert r.headers == p.headers1220 assert r.body == p.body12211222 # Verify unpickled PreparedRequest sends properly1223 s = requests.Session()1224 resp = s.send(r)1225 assert resp.status_code == 20012261227 def test_prepared_request_with_file_is_pickleable(self, httpbin):1228 files = {'file': open(__file__, 'rb')}1229 r = requests.Request('POST', httpbin('post'), files=files)1230 p = r.prepare()12311232 # Verify PreparedRequest can be pickled and unpickled1233 r = pickle.loads(pickle.dumps(p))1234 assert r.url == p.url1235 assert r.headers == p.headers1236 assert r.body == p.body12371238 # Verify unpickled PreparedRequest sends properly1239 s = requests.Session()1240 resp = s.send(r)1241 assert resp.status_code == 20012421243 def test_prepared_request_with_hook_is_pickleable(self, httpbin):1244 r = requests.Request('GET', httpbin('get'), hooks=default_hooks())1245 p = r.prepare()12461247 # Verify PreparedRequest can be pickled1248 r = pickle.loads(pickle.dumps(p))1249 assert r.url == p.url1250 assert r.headers == p.headers1251 assert r.body == p.body1252 assert r.hooks == p.hooks12531254 # Verify unpickled PreparedRequest sends properly1255 s = requests.Session()1256 resp = s.send(r)1257 assert resp.status_code == 2001258

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 1259–1500why, one step back
1259 def test_cannot_send_unprepared_requests(self, httpbin):
1260 r = requests.Request(url=httpbin())1261 with pytest.raises(ValueError):1262 requests.Session().send(r)12631264 def test_http_error(self):1265 error = requests.exceptions.HTTPError()1266 assert not error.response1267 response = requests.Response()1268 error = requests.exceptions.HTTPError(response=response)1269 assert error.response == response1270 error = requests.exceptions.HTTPError('message', response=response)1271 assert str(error) == 'message'1272 assert error.response == response12731274 def test_session_pickling(self, httpbin):1275 r = requests.Request('GET', httpbin('get'))1276 s = requests.Session()12771278 s = pickle.loads(pickle.dumps(s))1279 s.proxies = getproxies()12801281 r = s.send(r.prepare())1282 assert r.status_code == 20012831284 def test_fixes_1329(self, httpbin):1285 """Ensure that header updates are done case-insensitively."""1286 s = requests.Session()1287 s.headers.update({'ACCEPT': 'BOGUS'})1288 s.headers.update({'accept': 'application/json'})1289 r = s.get(httpbin('get'))1290 headers = r.request.headers1291 assert headers['accept'] == 'application/json'1292 assert headers['Accept'] == 'application/json'1293 assert headers['ACCEPT'] == 'application/json'12941295 def test_uppercase_scheme_redirect(self, httpbin):1296 parts = urlparse(httpbin('html'))1297 url = "HTTP://" + parts.netloc + parts.path1298 r = requests.get(httpbin('redirect-to'), params={'url': url})1299 assert r.status_code == 2001300 assert r.url.lower() == url.lower()13011302 def test_transport_adapter_ordering(self):1303 s = requests.Session()1304 order = ['https://', 'http://']1305 assert order == list(s.adapters)1306 s.mount('http://git', HTTPAdapter())1307 s.mount('http://github', HTTPAdapter())1308 s.mount('http://github.com', HTTPAdapter())1309 s.mount('http://github.com/about/', HTTPAdapter())1310 order = [1311 'http://github.com/about/',1312 'http://github.com',1313 'http://github',1314 'http://git',1315 'https://',1316 'http://',1317 ]1318 assert order == list(s.adapters)1319 s.mount('http://gittip', HTTPAdapter())1320 s.mount('http://gittip.com', HTTPAdapter())1321 s.mount('http://gittip.com/about/', HTTPAdapter())1322 order = [1323 'http://github.com/about/',1324 'http://gittip.com/about/',1325 'http://github.com',1326 'http://gittip.com',1327 'http://github',1328 'http://gittip',1329 'http://git',1330 'https://',1331 'http://',1332 ]1333 assert order == list(s.adapters)1334 s2 = requests.Session()1335 s2.adapters = {'http://': HTTPAdapter()}1336 s2.mount('https://', HTTPAdapter())1337 assert 'http://' in s2.adapters1338 assert 'https://' in s2.adapters13391340 def test_header_remove_is_case_insensitive(self, httpbin):1341 # From issue #13211342 s = requests.Session()1343 s.headers['foo'] = 'bar'1344 r = s.get(httpbin('get'), headers={'FOO': None})1345 assert 'foo' not in r.request.headers13461347 def test_params_are_merged_case_sensitive(self, httpbin):1348 s = requests.Session()1349 s.params['foo'] = 'bar'1350 r = s.get(httpbin('get'), params={'FOO': 'bar'})1351 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}13521353 def test_long_authinfo_in_url(self):1354 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(1355 'E8A3BE87-9E3F-4620-8858-95478E385B5B',1356 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1357 'exactly-------------sixty-----------three------------characters',1358 )1359 r = requests.Request('GET', url).prepare()1360 assert r.url == url13611362 def test_header_keys_are_native(self, httpbin):1363 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1364 r = requests.Request('GET', httpbin('get'), headers=headers)1365 p = r.prepare()13661367 # This is testing that they are builtin strings. A bit weird, but there1368 # we go.1369 assert 'unicode' in p.headers.keys()1370 assert 'byte' in p.headers.keys()13711372 def test_header_validation(self, httpbin):1373 """Ensure prepare_headers regex isn't flagging valid header contents."""1374 headers_ok = {'foo': 'bar baz qux',1375 'bar': u'fbbq'.encode('utf8'),1376 'baz': '',1377 'qux': '1'}1378 r = requests.get(httpbin('get'), headers=headers_ok)1379 assert r.request.headers['foo'] == headers_ok['foo']13801381 def test_header_value_not_str(self, httpbin):1382 """Ensure the header value is of type string or bytes as1383 per discussion in GH issue #33861384 """1385 headers_int = {'foo': 3}1386 headers_dict = {'bar': {'foo': 'bar'}}1387 headers_list = {'baz': ['foo', 'bar']}13881389 # Test for int1390 with pytest.raises(InvalidHeader):1391 r = requests.get(httpbin('get'), headers=headers_int)1392 # Test for dict1393 with pytest.raises(InvalidHeader):1394 r = requests.get(httpbin('get'), headers=headers_dict)1395 # Test for list1396 with pytest.raises(InvalidHeader):1397 r = requests.get(httpbin('get'), headers=headers_list)13981399 def test_header_no_return_chars(self, httpbin):1400 """Ensure that a header containing return character sequences raise an1401 exception. Otherwise, multiple headers are created from single string.1402 """1403 headers_ret = {'foo': 'bar\r\nbaz: qux'}1404 headers_lf = {'foo': 'bar\nbaz: qux'}1405 headers_cr = {'foo': 'bar\rbaz: qux'}14061407 # Test for newline1408 with pytest.raises(InvalidHeader):1409 r = requests.get(httpbin('get'), headers=headers_ret)1410 # Test for line feed1411 with pytest.raises(InvalidHeader):1412 r = requests.get(httpbin('get'), headers=headers_lf)1413 # Test for carriage return1414 with pytest.raises(InvalidHeader):1415 r = requests.get(httpbin('get'), headers=headers_cr)14161417 def test_header_no_leading_space(self, httpbin):1418 """Ensure headers containing leading whitespace raise1419 InvalidHeader Error before sending.1420 """1421 headers_space = {'foo': ' bar'}1422 headers_tab = {'foo': ' bar'}14231424 # Test for whitespace1425 with pytest.raises(InvalidHeader):1426 r = requests.get(httpbin('get'), headers=headers_space)1427 # Test for tab1428 with pytest.raises(InvalidHeader):1429 r = requests.get(httpbin('get'), headers=headers_tab)14301431 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1432 def test_can_send_objects_with_files(self, httpbin, files):1433 data = {'a': 'this is a string'}1434 files = {'b': files}1435 r = requests.Request('POST', httpbin('post'), data=data, files=files)1436 p = r.prepare()1437 assert 'multipart/form-data' in p.headers['Content-Type']14381439 def test_can_send_file_object_with_non_string_filename(self, httpbin):1440 f = io.BytesIO()1441 f.name = 21442 r = requests.Request('POST', httpbin('post'), files={'f': f})1443 p = r.prepare()14441445 assert 'multipart/form-data' in p.headers['Content-Type']14461447 def test_autoset_header_values_are_native(self, httpbin):1448 data = 'this is a string'1449 length = '16'1450 req = requests.Request('POST', httpbin('post'), data=data)1451 p = req.prepare()14521453 assert p.headers['Content-Length'] == length14541455 def test_nonhttp_schemes_dont_check_URLs(self):1456 test_urls = (1457 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1458 'file:///etc/passwd',1459 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1460 )1461 for test_url in test_urls:1462 req = requests.Request('GET', test_url)1463 preq = req.prepare()1464 assert test_url == preq.url14651466 @pytest.mark.xfail(raises=ConnectionError)1467 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1468 r = requests.get(1469 httpbin('redirect-to'),1470 params={'url': 'http://www.google.co.uk'},1471 auth=('user', 'pass'),1472 )1473 assert r.history[0].request.headers['Authorization']1474 assert not r.request.headers.get('Authorization', '')14751476 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1477 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1478 h1 = r.history[0].request.headers['Authorization']1479 h2 = r.request.headers['Authorization']14801481 assert h1 == h214821483 def test_manual_redirect_with_partial_body_read(self, httpbin):1484 s = requests.Session()1485 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1486 assert r1.is_redirect1487 rg = s.resolve_redirects(r1, r1.request, stream=True)14881489 # read only the first eight bytes of the response body,1490 # then follow the redirect1491 r1.iter_content(8)1492 r2 = next(rg)1493 assert r2.is_redirect14941495 # read all of the response via iter_content,1496 # then follow the redirect1497 for _ in r2.iter_content():1498 pass1499 r3 = next(rg)1500 assert not r3.is_redirect

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

lines 1501–1565why, one step back
1501
1502 def test_prepare_body_position_non_stream(self):1503 data = b'the data'1504 s = requests.Session()1505 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1506 assert prep._body_position is None15071508 def test_rewind_body(self):1509 data = io.BytesIO(b'the data')1510 s = requests.Session()1511 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1512 assert prep._body_position == 01513 assert prep.body.read() == b'the data'15141515 # the data has all been read1516 assert prep.body.read() == b''15171518 # rewind it back1519 requests.utils.rewind_body(prep)1520 assert prep.body.read() == b'the data'15211522 def test_rewind_partially_read_body(self):1523 data = io.BytesIO(b'the data')1524 s = requests.Session()1525 data.read(4) # read some data1526 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1527 assert prep._body_position == 41528 assert prep.body.read() == b'data'15291530 # the data has all been read1531 assert prep.body.read() == b''15321533 # rewind it back1534 requests.utils.rewind_body(prep)1535 assert prep.body.read() == b'data'15361537 def test_rewind_body_no_seek(self):1538 class BadFileObj:1539 def __init__(self, data):1540 self.data = data15411542 def tell(self):1543 return 015441545 def __iter__(self):1546 return15471548 data = BadFileObj('the data')1549 s = requests.Session()1550 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1551 assert prep._body_position == 015521553 with pytest.raises(UnrewindableBodyError) as e:1554 requests.utils.rewind_body(prep)15551556 assert 'Unable to rewind request body' in str(e)15571558 def test_rewind_body_failed_seek(self):1559 class BadFileObj:1560 def __init__(self, data):1561 self.data = data15621563 def tell(self):1564 return 01565

Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoptionb60c5a5

line 1566why, one step back
1566 def seek(self, pos, whence=0):

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

lines 1567–1579why, one step back
1567 raise OSError()
15681569 def __iter__(self):1570 return15711572 data = BadFileObj('the data')1573 s = requests.Session()1574 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1575 assert prep._body_position == 015761577 with pytest.raises(UnrewindableBodyError) as e:1578 requests.utils.rewind_body(prep)1579

Merge branch 'master' of github.com:kennethreitz/requestsKenneth Reitzbefore adoptionb60c5a5

line 1580why, one step back
1580 assert 'error occurred when rewinding request body' in str(e)

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

lines 1581–1601why, one step back
1581
1582 def test_rewind_body_failed_tell(self):1583 class BadFileObj:1584 def __init__(self, data):1585 self.data = data15861587 def tell(self):1588 raise OSError()15891590 def __iter__(self):1591 return15921593 data = BadFileObj('the data')1594 s = requests.Session()1595 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1596 assert prep._body_position is not None15971598 with pytest.raises(UnrewindableBodyError) as e:1599 requests.utils.rewind_body(prep)16001601 assert 'Unable to rewind request body' in str(e)

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 1602–1622why, one step back
1602
1603 def _patch_adapter_gzipped_redirect(self, session, url):1604 adapter = session.get_adapter(url=url)1605 org_build_response = adapter.build_response1606 self._patched_response = False16071608 def build_response(*args, **kwargs):1609 resp = org_build_response(*args, **kwargs)1610 if not self._patched_response:1611 resp.raw.headers['content-encoding'] = 'gzip'1612 self._patched_response = True1613 return resp16141615 adapter.build_response = build_response16161617 def test_redirect_with_wrong_gzipped_header(self, httpbin):1618 s = requests.Session()1619 url = httpbin('redirect/1')1620 self._patch_adapter_gzipped_redirect(s, url)1621 s.get(url)1622

Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44

lines 1623–1629why, one step back
1623 @pytest.mark.parametrize(
1624 'username, password, auth_str', (1625 ('test', 'test', 'Basic dGVzdDp0ZXN0'),1626 (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8'), 'Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA=='),1627 ))1628 def test_basic_auth_str_is_always_native(self, username, password, auth_str):1629 s = _basic_auth_str(username, password)

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

line 1630why, one step back
1630 assert isinstance(s, builtin_str)

Merge pull request #3673 from klimenko-forks/auth-unicodeCory Benfieldbefore adoptionb9f1c44

line 1631why, one step back
1631 assert s == auth_str

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 1632–1693why, one step back
1632
1633 def test_requests_history_is_saved(self, httpbin):1634 r = requests.get(httpbin('redirect/5'))1635 total = r.history[-1].history1636 i = 01637 for item in r.history:1638 assert item.history == total[0:i]1639 i += 116401641 def test_json_param_post_content_type_works(self, httpbin):1642 r = requests.post(1643 httpbin('post'),1644 json={'life': 42}1645 )1646 assert r.status_code == 2001647 assert 'application/json' in r.request.headers['Content-Type']1648 assert {'life': 42} == r.json()['json']16491650 def test_json_param_post_should_not_override_data_param(self, httpbin):1651 r = requests.Request(method='POST', url=httpbin('post'),1652 data={'stuff': 'elixr'},1653 json={'music': 'flute'})1654 prep = r.prepare()1655 assert 'stuff=elixr' == prep.body16561657 def test_response_iter_lines(self, httpbin):1658 r = requests.get(httpbin('stream/4'), stream=True)1659 assert r.status_code == 20016601661 it = r.iter_lines()1662 next(it)1663 assert len(list(it)) == 316641665 def test_unconsumed_session_response_closes_connection(self, httpbin):1666 s = requests.session()16671668 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1669 pass16701671 assert response._content_consumed is False1672 assert response.raw.closed16731674 @pytest.mark.xfail1675 def test_response_iter_lines_reentrant(self, httpbin):1676 """Response.iter_lines() is not reentrant safe"""1677 r = requests.get(httpbin('stream/4'), stream=True)1678 assert r.status_code == 20016791680 next(r.iter_lines())1681 assert len(list(r.iter_lines())) == 316821683 def test_session_close_proxy_clear(self, mocker):1684 proxies = {1685 'one': mocker.Mock(),1686 'two': mocker.Mock(),1687 }1688 session = requests.Session()1689 mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1690 session.close()1691 proxies['one'].clear.assert_called_once_with()1692 proxies['two'].clear.assert_called_once_with()1693

Merge pull request #3660 from pawelmhm/proxy_empty_passCory Benfieldbefore adoptionbf19750

lines 1694–1703why, one step back
1694 def test_proxy_auth(self, httpbin):
1695 adapter = HTTPAdapter()1696 headers = adapter.proxy_headers("http://user:pass@httpbin.org")1697 assert headers == {'Proxy-Authorization': 'Basic dXNlcjpwYXNz'}16981699 def test_proxy_auth_empty_pass(self, httpbin):1700 adapter = HTTPAdapter()1701 headers = adapter.proxy_headers("http://user:@httpbin.org")1702 assert headers == {'Proxy-Authorization': 'Basic dXNlcjo='}1703

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 1704–1714why, one step back
1704 def test_response_json_when_content_is_None(self, httpbin):
1705 r = requests.get(httpbin('/status/204'))1706 # Make sure r.content is None1707 r.status_code = 01708 r._content = False1709 r._content_consumed = False17101711 assert r.content is None1712 with pytest.raises(ValueError):1713 r.json()1714

Merge pull request #3510 from nateprewitt/add_close_passthroughCory Benfieldbefore adoptiond3567aa

lines 1715–1723why, one step back
1715 def test_response_without_release_conn(self):
1716 """Test `close` call for non-urllib3-like raw objects.1717 Should work when `release_conn` attr doesn't exist on `response.raw`.1718 """1719 resp = requests.Response()1720 resp.raw = StringIO.StringIO('test')1721 assert not resp.raw.closed1722 resp.close()1723 assert resp.raw.closed

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

line 1724why, one step back
1724

Merge pull request #3754 from nateprewitt/3066_auth_and_dataCory Benfieldbefore adoption11a86a5

lines 1725–1759why, one step back
1725 def test_empty_stream_with_auth_does_not_set_content_length_header(self, httpbin):
1726 """Ensure that a byte stream with size 0 will not set both a Content-Length1727 and Transfer-Encoding header.1728 """1729 auth = ('user', 'pass')1730 url = httpbin('post')1731 file_obj = io.BytesIO(b'')1732 r = requests.Request('POST', url, auth=auth, data=file_obj)1733 prepared_request = r.prepare()1734 assert 'Transfer-Encoding' in prepared_request.headers1735 assert 'Content-Length' not in prepared_request.headers17361737 def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):1738 """Ensure that a byte stream with size > 0 will not set both a Content-Length1739 and Transfer-Encoding header.1740 """1741 auth = ('user', 'pass')1742 url = httpbin('post')1743 file_obj = io.BytesIO(b'test data')1744 r = requests.Request('POST', url, auth=auth, data=file_obj)1745 prepared_request = r.prepare()1746 assert 'Transfer-Encoding' not in prepared_request.headers1747 assert 'Content-Length' in prepared_request.headers17481749 def test_chunked_upload_does_not_set_content_length_header(self, httpbin):1750 """Ensure that requests with a generator body stream using1751 Transfer-Encoding: chunked, not a Content-Length header.1752 """1753 data = (i for i in [b'a', b'b', b'c'])1754 url = httpbin('post')1755 r = requests.Request('POST', url, data=data)1756 prepared_request = r.prepare()1757 assert 'Transfer-Encoding' in prepared_request.headers1758 assert 'Content-Length' not in prepared_request.headers1759

Merge pull request #3846 from jvanasco/feature-pluggable_handlingKenneth Reitzbefore adoption4533979

lines 1760–1802why, one step back
1760 def test_custom_redirect_mixin(self, httpbin):
1761 """Tests a custom mixin to overwrite ``get_redirect_target``.17621763 Ensures a subclassed ``requests.Session`` can handle a certain type of1764 malformed redirect responses.17651766 1. original request receives a proper response: 302 redirect1767 2. following the redirect, a malformed response is given:1768 status code = HTTP 2001769 location = alternate url1770 3. the custom session catches the edge case and follows the redirect1771 """1772 url_final = httpbin('html')1773 querystring_malformed = urlencode({'location': url_final})1774 url_redirect_malformed = httpbin('response-headers?%s' % querystring_malformed)1775 querystring_redirect = urlencode({'url': url_redirect_malformed})1776 url_redirect = httpbin('redirect-to?%s' % querystring_redirect)1777 urls_test = [url_redirect,1778 url_redirect_malformed,1779 url_final,1780 ]17811782 class CustomRedirectSession(requests.Session):1783 def get_redirect_target(self, resp):1784 # default behavior1785 if resp.is_redirect:1786 return resp.headers['location']1787 # edge case - check to see if 'location' is in headers anyways1788 location = resp.headers.get('location')1789 if location and (location != resp.url):1790 return location1791 return None17921793 session = CustomRedirectSession()1794 r = session.get(urls_test[0])1795 assert len(r.history) == 21796 assert r.status_code == 2001797 assert r.history[0].status_code == 3021798 assert r.history[0].is_redirect1799 assert r.history[1].status_code == 2001800 assert not r.history[1].is_redirect1801 assert r.url == urls_test[2]1802

Merge pull request #3754 from nateprewitt/3066_auth_and_dataCory Benfieldbefore adoption11a86a5

line 1803why, one step back
1803

Merge pull request #3475 from Lukasa/prepare-2.11Kenneth Reitzbefore adoption05d90b9

lines 1804–2009why, one step back
1804class TestCaseInsensitiveDict:
18051806 @pytest.mark.parametrize(1807 'cid', (1808 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1809 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1810 CaseInsensitiveDict(FOO='foo', BAr='bar'),1811 ))1812 def test_init(self, cid):1813 assert len(cid) == 21814 assert 'foo' in cid1815 assert 'bar' in cid18161817 def test_docstring_example(self):1818 cid = CaseInsensitiveDict()1819 cid['Accept'] = 'application/json'1820 assert cid['aCCEPT'] == 'application/json'1821 assert list(cid) == ['Accept']18221823 def test_len(self):1824 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1825 cid['A'] = 'a'1826 assert len(cid) == 218271828 def test_getitem(self):1829 cid = CaseInsensitiveDict({'Spam': 'blueval'})1830 assert cid['spam'] == 'blueval'1831 assert cid['SPAM'] == 'blueval'18321833 def test_fixes_649(self):1834 """__setitem__ should behave case-insensitively."""1835 cid = CaseInsensitiveDict()1836 cid['spam'] = 'oneval'1837 cid['Spam'] = 'twoval'1838 cid['sPAM'] = 'redval'1839 cid['SPAM'] = 'blueval'1840 assert cid['spam'] == 'blueval'1841 assert cid['SPAM'] == 'blueval'1842 assert list(cid.keys()) == ['SPAM']18431844 def test_delitem(self):1845 cid = CaseInsensitiveDict()1846 cid['Spam'] = 'someval'1847 del cid['sPam']1848 assert 'spam' not in cid1849 assert len(cid) == 018501851 def test_contains(self):1852 cid = CaseInsensitiveDict()1853 cid['Spam'] = 'someval'1854 assert 'Spam' in cid1855 assert 'spam' in cid1856 assert 'SPAM' in cid1857 assert 'sPam' in cid1858 assert 'notspam' not in cid18591860 def test_get(self):1861 cid = CaseInsensitiveDict()1862 cid['spam'] = 'oneval'1863 cid['SPAM'] = 'blueval'1864 assert cid.get('spam') == 'blueval'1865 assert cid.get('SPAM') == 'blueval'1866 assert cid.get('sPam') == 'blueval'1867 assert cid.get('notspam', 'default') == 'default'18681869 def test_update(self):1870 cid = CaseInsensitiveDict()1871 cid['spam'] = 'blueval'1872 cid.update({'sPam': 'notblueval'})1873 assert cid['spam'] == 'notblueval'1874 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1875 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1876 assert len(cid) == 21877 assert cid['foo'] == 'anotherfoo'1878 assert cid['bar'] == 'anotherbar'18791880 def test_update_retains_unchanged(self):1881 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1882 cid.update({'foo': 'newfoo'})1883 assert cid['bar'] == 'bar'18841885 def test_iter(self):1886 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1887 keys = frozenset(['Spam', 'Eggs'])1888 assert frozenset(iter(cid)) == keys18891890 def test_equality(self):1891 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1892 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1893 assert cid == othercid1894 del othercid['spam']1895 assert cid != othercid1896 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1897 assert cid != object()18981899 def test_setdefault(self):1900 cid = CaseInsensitiveDict({'Spam': 'blueval'})1901 assert cid.setdefault('spam', 'notblueval') == 'blueval'1902 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'19031904 def test_lower_items(self):1905 cid = CaseInsensitiveDict({1906 'Accept': 'application/json',1907 'user-Agent': 'requests',1908 })1909 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1910 lowerkeyset = frozenset(['accept', 'user-agent'])1911 assert keyset == lowerkeyset19121913 def test_preserve_key_case(self):1914 cid = CaseInsensitiveDict({1915 'Accept': 'application/json',1916 'user-Agent': 'requests',1917 })1918 keyset = frozenset(['Accept', 'user-Agent'])1919 assert frozenset(i[0] for i in cid.items()) == keyset1920 assert frozenset(cid.keys()) == keyset1921 assert frozenset(cid) == keyset19221923 def test_preserve_last_key_case(self):1924 cid = CaseInsensitiveDict({1925 'Accept': 'application/json',1926 'user-Agent': 'requests',1927 })1928 cid.update({'ACCEPT': 'application/json'})1929 cid['USER-AGENT'] = 'requests'1930 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1931 assert frozenset(i[0] for i in cid.items()) == keyset1932 assert frozenset(cid.keys()) == keyset1933 assert frozenset(cid) == keyset19341935 def test_copy(self):1936 cid = CaseInsensitiveDict({1937 'Accept': 'application/json',1938 'user-Agent': 'requests',1939 })1940 cid_copy = cid.copy()1941 assert cid == cid_copy1942 cid['changed'] = True1943 assert cid != cid_copy194419451946class TestMorselToCookieExpires:1947 """Tests for morsel_to_cookie when morsel contains expires."""19481949 def test_expires_valid_str(self):1950 """Test case where we convert expires from string time."""19511952 morsel = Morsel()1953 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1954 cookie = morsel_to_cookie(morsel)1955 assert cookie.expires == 119561957 @pytest.mark.parametrize(1958 'value, exception', (1959 (100, TypeError),1960 ('woops', ValueError),1961 ))1962 def test_expires_invalid_int(self, value, exception):1963 """Test case where an invalid type is passed for expires."""1964 morsel = Morsel()1965 morsel['expires'] = value1966 with pytest.raises(exception):1967 morsel_to_cookie(morsel)19681969 def test_expires_none(self):1970 """Test case where expires is None."""19711972 morsel = Morsel()1973 morsel['expires'] = None1974 cookie = morsel_to_cookie(morsel)1975 assert cookie.expires is None197619771978class TestMorselToCookieMaxAge:19791980 """Tests for morsel_to_cookie when morsel contains max-age."""19811982 def test_max_age_valid_int(self):1983 """Test case where a valid max age in seconds is passed."""19841985 morsel = Morsel()1986 morsel['max-age'] = 601987 cookie = morsel_to_cookie(morsel)1988 assert isinstance(cookie.expires, int)19891990 def test_max_age_invalid_str(self):1991 """Test case where a invalid max age is passed."""19921993 morsel = Morsel()1994 morsel['max-age'] = 'woops'1995 with pytest.raises(TypeError):1996 morsel_to_cookie(morsel)199719981999class TestTimeout:2000

The first 2,000 of 2,375 lines.