Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

2,379 lines · 82.1 KiB · Python

Last changed by

Merge branch 'kaptajnen-master'Cory Benfieldbefore adoptionfb3f2a0

History of this file

Take it

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

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

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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

lines 189–377why, 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_redirect255256 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.headers295296 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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

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 #3576 from nateprewitt/3557_revert_and_fix_encodingIan Cordascobefore adoptionddf7df9

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 branch 'kaptajnen-master'Cory Benfieldbefore adoptionfb3f2a0

lines 789–792why, one step back
789 def test_http_with_certificate(self, httpbin):
790 r = requests.get(httpbin(), cert='.')791 assert r.status_code == 200792

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

lines 793–952why, one step back
793 def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):
794 """warnings are emitted with requests.get"""795 if HAS_MODERN_SSL or HAS_PYOPENSSL:796 warnings_expected = ('SubjectAltNameWarning', )797 else:798 warnings_expected = ('SNIMissingWarning',799 'InsecurePlatformWarning',800 'SubjectAltNameWarning', )801802 with pytest.warns(None) as warning_records:803 warnings.simplefilter('always')804 requests.get(httpbin_secure('status', '200'),805 verify=httpbin_ca_bundle)806807 warning_records = [item for item in warning_records808 if item.category.__name__ != 'ResourceWarning']809810 warnings_category = tuple(811 item.category.__name__ for item in warning_records)812 assert warnings_category == warnings_expected813814 def test_urlencoded_get_query_multivalued_param(self, httpbin):815816 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))817 assert r.status_code == 200818 assert r.url == httpbin('get?test=foo&test=baz')819820 def test_different_encodings_dont_break_post(self, httpbin):821 r = requests.post(httpbin('post'),822 data={'stuff': json.dumps({'a': 123})},823 params={'blah': 'asdf1234'},824 files={'file': ('test_requests.py', open(__file__, 'rb'))})825 assert r.status_code == 200826827 @pytest.mark.parametrize(828 'data', (829 {'stuff': u('ëlïxr')},830 {'stuff': u('ëlïxr').encode('utf-8')},831 {'stuff': 'elixr'},832 {'stuff': 'elixr'.encode('utf-8')},833 ))834 def test_unicode_multipart_post(self, httpbin, data):835 r = requests.post(httpbin('post'),836 data=data,837 files={'file': ('test_requests.py', open(__file__, 'rb'))})838 assert r.status_code == 200839840 def test_unicode_multipart_post_fieldnames(self, httpbin):841 filename = os.path.splitext(__file__)[0] + '.py'842 r = requests.Request(843 method='POST', url=httpbin('post'),844 data={'stuff'.encode('utf-8'): 'elixr'},845 files={'file': ('test_requests.py', open(filename, 'rb'))})846 prep = r.prepare()847 assert b'name="stuff"' in prep.body848 assert b'name="b\'stuff\'"' not in prep.body849850 def test_unicode_method_name(self, httpbin):851 files = {'file': open(__file__, 'rb')}852 r = requests.request(853 method=u('POST'), url=httpbin('post'), files=files)854 assert r.status_code == 200855856 def test_unicode_method_name_with_request_object(self, httpbin):857 files = {'file': open(__file__, 'rb')}858 s = requests.Session()859 req = requests.Request(u('POST'), httpbin('post'), files=files)860 prep = s.prepare_request(req)861 assert isinstance(prep.method, builtin_str)862 assert prep.method == 'POST'863864 resp = s.send(prep)865 assert resp.status_code == 200866867 def test_non_prepared_request_error(self):868 s = requests.Session()869 req = requests.Request(u('POST'), '/')870871 with pytest.raises(ValueError) as e:872 s.send(req)873 assert str(e.value) == 'You can only send PreparedRequests.'874875 def test_custom_content_type(self, httpbin):876 r = requests.post(877 httpbin('post'),878 data={'stuff': json.dumps({'a': 123})},879 files={880 'file1': ('test_requests.py', open(__file__, 'rb')),881 'file2': ('test_requests', open(__file__, 'rb'),882 'text/py-content-type')})883 assert r.status_code == 200884 assert b"text/py-content-type" in r.request.body885886 def test_hook_receives_request_arguments(self, httpbin):887 def hook(resp, **kwargs):888 assert resp is not None889 assert kwargs != {}890891 s = requests.Session()892 r = requests.Request('GET', httpbin(), hooks={'response': hook})893 prep = s.prepare_request(r)894 s.send(prep)895896 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):897 hook = lambda x, *args, **kwargs: x898 s = requests.Session()899 s.hooks['response'].append(hook)900 r = requests.Request('GET', httpbin())901 prep = s.prepare_request(r)902 assert prep.hooks['response'] != []903 assert prep.hooks['response'] == [hook]904905 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):906 hook1 = lambda x, *args, **kwargs: x907 hook2 = lambda x, *args, **kwargs: x908 assert hook1 is not hook2909 s = requests.Session()910 s.hooks['response'].append(hook2)911 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})912 prep = s.prepare_request(r)913 assert prep.hooks['response'] == [hook1]914915 def test_prepared_request_hook(self, httpbin):916 def hook(resp, **kwargs):917 resp.hook_working = True918 return resp919920 req = requests.Request('GET', httpbin(), hooks={'response': hook})921 prep = req.prepare()922923 s = requests.Session()924 s.proxies = getproxies()925 resp = s.send(prep)926927 assert hasattr(resp, 'hook_working')928929 def test_prepared_from_session(self, httpbin):930 class DummyAuth(requests.auth.AuthBase):931 def __call__(self, r):932 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'933 return r934935 req = requests.Request('GET', httpbin('headers'))936 assert not req.auth937938 s = requests.Session()939 s.auth = DummyAuth()940941 prep = s.prepare_request(req)942 resp = s.send(prep)943944 assert resp.json()['headers'][945 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'946947 def test_prepare_request_with_bytestring_url(self):948 req = requests.Request('GET', b'https://httpbin.org/')949 s = requests.Session()950 prep = s.prepare_request(req)951 assert prep.url == "https://httpbin.org/"952

Merge pull request #3606 from bbamsch/httpbinTestFixCory Benfieldbefore adoption022e23c

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

Merge pull request #3598 from bbamsch/bytestringHostFixCory Benfieldbefore adoption5eabcb7

lines 954–956why, one step back
954 s = requests.Session()
955 resp = s.request(956 'GET',

Merge pull request #3606 from bbamsch/httpbinTestFixCory Benfieldbefore adoption022e23c

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

Merge pull request #3598 from bbamsch/bytestringHostFixCory Benfieldbefore adoption5eabcb7

lines 958–962why, one step back
958 allow_redirects=False,
959 headers={'Host': b'httpbin.org'}960 )961 assert resp.cookies.get('cookie') == 'value'962

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

lines 963–1129why, one step back
963 def test_links(self):
964 r = requests.Response()965 r.headers = {966 'cache-control': 'public, max-age=60, s-maxage=60',967 'connection': 'keep-alive',968 'content-encoding': 'gzip',969 'content-type': 'application/json; charset=utf-8',970 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',971 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',972 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',973 'link': ('<https://api.github.com/users/kennethreitz/repos?'974 'page=2&per_page=10>; rel="next", <https://api.github.'975 'com/users/kennethreitz/repos?page=7&per_page=10>; '976 ' rel="last"'),977 'server': 'GitHub.com',978 'status': '200 OK',979 'vary': 'Accept',980 'x-content-type-options': 'nosniff',981 'x-github-media-type': 'github.beta',982 'x-ratelimit-limit': '60',983 'x-ratelimit-remaining': '57'984 }985 assert r.links['next']['rel'] == 'next'986987 def test_cookie_parameters(self):988 key = 'some_cookie'989 value = 'some_value'990 secure = True991 domain = 'test.com'992 rest = {'HttpOnly': True}993994 jar = requests.cookies.RequestsCookieJar()995 jar.set(key, value, secure=secure, domain=domain, rest=rest)996997 assert len(jar) == 1998 assert 'some_cookie' in jar9991000 cookie = list(jar)[0]1001 assert cookie.secure == secure1002 assert cookie.domain == domain1003 assert cookie._rest['HttpOnly'] == rest['HttpOnly']10041005 def test_cookie_as_dict_keeps_len(self):1006 key = 'some_cookie'1007 value = 'some_value'10081009 key1 = 'some_cookie1'1010 value1 = 'some_value1'10111012 jar = requests.cookies.RequestsCookieJar()1013 jar.set(key, value)1014 jar.set(key1, value1)10151016 d1 = dict(jar)1017 d2 = dict(jar.iteritems())1018 d3 = dict(jar.items())10191020 assert len(jar) == 21021 assert len(d1) == 21022 assert len(d2) == 21023 assert len(d3) == 210241025 def test_cookie_as_dict_keeps_items(self):1026 key = 'some_cookie'1027 value = 'some_value'10281029 key1 = 'some_cookie1'1030 value1 = 'some_value1'10311032 jar = requests.cookies.RequestsCookieJar()1033 jar.set(key, value)1034 jar.set(key1, value1)10351036 d1 = dict(jar)1037 d2 = dict(jar.iteritems())1038 d3 = dict(jar.items())10391040 assert d1['some_cookie'] == 'some_value'1041 assert d2['some_cookie'] == 'some_value'1042 assert d3['some_cookie1'] == 'some_value1'10431044 def test_cookie_as_dict_keys(self):1045 key = 'some_cookie'1046 value = 'some_value'10471048 key1 = 'some_cookie1'1049 value1 = 'some_value1'10501051 jar = requests.cookies.RequestsCookieJar()1052 jar.set(key, value)1053 jar.set(key1, value1)10541055 keys = jar.keys()1056 assert keys == list(keys)1057 # make sure one can use keys multiple times1058 assert list(keys) == list(keys)10591060 def test_cookie_as_dict_values(self):1061 key = 'some_cookie'1062 value = 'some_value'10631064 key1 = 'some_cookie1'1065 value1 = 'some_value1'10661067 jar = requests.cookies.RequestsCookieJar()1068 jar.set(key, value)1069 jar.set(key1, value1)10701071 values = jar.values()1072 assert values == list(values)1073 # make sure one can use values multiple times1074 assert list(values) == list(values)10751076 def test_cookie_as_dict_items(self):1077 key = 'some_cookie'1078 value = 'some_value'10791080 key1 = 'some_cookie1'1081 value1 = 'some_value1'10821083 jar = requests.cookies.RequestsCookieJar()1084 jar.set(key, value)1085 jar.set(key1, value1)10861087 items = jar.items()1088 assert items == list(items)1089 # make sure one can use items multiple times1090 assert list(items) == list(items)10911092 def test_cookie_duplicate_names_different_domains(self):1093 key = 'some_cookie'1094 value = 'some_value'1095 domain1 = 'test1.com'1096 domain2 = 'test2.com'10971098 jar = requests.cookies.RequestsCookieJar()1099 jar.set(key, value, domain=domain1)1100 jar.set(key, value, domain=domain2)1101 assert key in jar1102 items = jar.items()1103 assert len(items) == 211041105 # Verify that CookieConflictError is raised if domain is not specified1106 with pytest.raises(requests.cookies.CookieConflictError):1107 jar.get(key)11081109 # Verify that CookieConflictError is not raised if domain is specified1110 cookie = jar.get(key, domain=domain1)1111 assert cookie == value11121113 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1114 key = 'some_cookie'1115 value = 'some_value'1116 path = 'some_path'11171118 jar = requests.cookies.RequestsCookieJar()1119 jar.set(key, value, path=path)1120 jar.set(key, value)1121 with pytest.raises(requests.cookies.CookieConflictError):1122 jar.get(key)11231124 def test_time_elapsed_blank(self, httpbin):1125 r = requests.get(httpbin('get'))1126 td = r.elapsed1127 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)1128 assert total_seconds > 0.01129

Merge pull request #3718 from nsoranzo/masterCory Benfieldbefore adoption36c9c8c

lines 1130–1133why, one step back
1130 def test_empty_response_has_content_none(self):
1131 r = requests.Response()1132 assert r.content is None1133

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

lines 1134–1216why, one step back
1134 def test_response_is_iterable(self):
1135 r = requests.Response()1136 io = StringIO.StringIO('abc')1137 read_ = io.read11381139 def read_mock(amt, decode_content=None):1140 return read_(amt)1141 setattr(io, 'read', read_mock)1142 r.raw = io1143 assert next(iter(r))1144 io.close()11451146 def test_response_decode_unicode(self):1147 """When called with decode_unicode, Response.iter_content should always1148 return unicode.1149 """1150 r = requests.Response()1151 r._content_consumed = True1152 r._content = b'the content'1153 r.encoding = 'ascii'11541155 chunks = r.iter_content(decode_unicode=True)1156 assert all(isinstance(chunk, str) for chunk in chunks)11571158 # also for streaming1159 r = requests.Response()1160 r.raw = io.BytesIO(b'the content')1161 r.encoding = 'ascii'1162 chunks = r.iter_content(decode_unicode=True)1163 assert all(isinstance(chunk, str) for chunk in chunks)11641165 def test_response_reason_unicode(self):1166 # check for unicode HTTP status1167 r = requests.Response()1168 r.url = u'unicode URL'1169 r.reason = u'Komponenttia ei löydy'.encode('utf-8')1170 r.status_code = 4041171 r.encoding = None1172 assert not r.ok # old behaviour - crashes here11731174 def test_response_reason_unicode_fallback(self):1175 # check raise_status falls back to ISO-8859-11176 r = requests.Response()1177 r.url = 'some url'1178 reason = u'Komponenttia ei löydy'1179 r.reason = reason.encode('latin-1')1180 r.status_code = 5001181 r.encoding = None1182 with pytest.raises(requests.exceptions.HTTPError) as e:1183 r.raise_for_status()1184 assert reason in e.value.args[0]11851186 def test_response_chunk_size_type(self):1187 """Ensure that chunk_size is passed as None or an integer, otherwise1188 raise a TypeError.1189 """1190 r = requests.Response()1191 r.raw = io.BytesIO(b'the content')1192 chunks = r.iter_content(1)1193 assert all(len(chunk) == 1 for chunk in chunks)11941195 r = requests.Response()1196 r.raw = io.BytesIO(b'the content')1197 chunks = r.iter_content(None)1198 assert list(chunks) == [b'the content']11991200 r = requests.Response()1201 r.raw = io.BytesIO(b'the content')1202 with pytest.raises(TypeError):1203 chunks = r.iter_content("1024")12041205 def test_request_and_response_are_pickleable(self, httpbin):1206 r = requests.get(httpbin('get'))12071208 # verify we can pickle the original request1209 assert pickle.loads(pickle.dumps(r.request))12101211 # verify we can pickle the response and that we have access to1212 # the original request.1213 pr = pickle.loads(pickle.dumps(r))1214 assert r.request.url == pr.request.url1215 assert r.request.headers == pr.request.headers1216

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

lines 1217–1262why, one step back
1217 def test_prepared_request_is_pickleable(self, httpbin):
1218 p = requests.Request('GET', httpbin('get')).prepare()12191220 # Verify PreparedRequest can be pickled and unpickled1221 r = pickle.loads(pickle.dumps(p))1222 assert r.url == p.url1223 assert r.headers == p.headers1224 assert r.body == p.body12251226 # Verify unpickled PreparedRequest sends properly1227 s = requests.Session()1228 resp = s.send(r)1229 assert resp.status_code == 20012301231 def test_prepared_request_with_file_is_pickleable(self, httpbin):1232 files = {'file': open(__file__, 'rb')}1233 r = requests.Request('POST', httpbin('post'), files=files)1234 p = r.prepare()12351236 # Verify PreparedRequest can be pickled and unpickled1237 r = pickle.loads(pickle.dumps(p))1238 assert r.url == p.url1239 assert r.headers == p.headers1240 assert r.body == p.body12411242 # Verify unpickled PreparedRequest sends properly1243 s = requests.Session()1244 resp = s.send(r)1245 assert resp.status_code == 20012461247 def test_prepared_request_with_hook_is_pickleable(self, httpbin):1248 r = requests.Request('GET', httpbin('get'), hooks=default_hooks())1249 p = r.prepare()12501251 # Verify PreparedRequest can be pickled1252 r = pickle.loads(pickle.dumps(p))1253 assert r.url == p.url1254 assert r.headers == p.headers1255 assert r.body == p.body1256 assert r.hooks == p.hooks12571258 # Verify unpickled PreparedRequest sends properly1259 s = requests.Session()1260 resp = s.send(r)1261 assert resp.status_code == 2001262

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

lines 1263–1504why, one step back
1263 def test_cannot_send_unprepared_requests(self, httpbin):
1264 r = requests.Request(url=httpbin())1265 with pytest.raises(ValueError):1266 requests.Session().send(r)12671268 def test_http_error(self):1269 error = requests.exceptions.HTTPError()1270 assert not error.response1271 response = requests.Response()1272 error = requests.exceptions.HTTPError(response=response)1273 assert error.response == response1274 error = requests.exceptions.HTTPError('message', response=response)1275 assert str(error) == 'message'1276 assert error.response == response12771278 def test_session_pickling(self, httpbin):1279 r = requests.Request('GET', httpbin('get'))1280 s = requests.Session()12811282 s = pickle.loads(pickle.dumps(s))1283 s.proxies = getproxies()12841285 r = s.send(r.prepare())1286 assert r.status_code == 20012871288 def test_fixes_1329(self, httpbin):1289 """Ensure that header updates are done case-insensitively."""1290 s = requests.Session()1291 s.headers.update({'ACCEPT': 'BOGUS'})1292 s.headers.update({'accept': 'application/json'})1293 r = s.get(httpbin('get'))1294 headers = r.request.headers1295 assert headers['accept'] == 'application/json'1296 assert headers['Accept'] == 'application/json'1297 assert headers['ACCEPT'] == 'application/json'12981299 def test_uppercase_scheme_redirect(self, httpbin):1300 parts = urlparse(httpbin('html'))1301 url = "HTTP://" + parts.netloc + parts.path1302 r = requests.get(httpbin('redirect-to'), params={'url': url})1303 assert r.status_code == 2001304 assert r.url.lower() == url.lower()13051306 def test_transport_adapter_ordering(self):1307 s = requests.Session()1308 order = ['https://', 'http://']1309 assert order == list(s.adapters)1310 s.mount('http://git', HTTPAdapter())1311 s.mount('http://github', HTTPAdapter())1312 s.mount('http://github.com', HTTPAdapter())1313 s.mount('http://github.com/about/', HTTPAdapter())1314 order = [1315 'http://github.com/about/',1316 'http://github.com',1317 'http://github',1318 'http://git',1319 'https://',1320 'http://',1321 ]1322 assert order == list(s.adapters)1323 s.mount('http://gittip', HTTPAdapter())1324 s.mount('http://gittip.com', HTTPAdapter())1325 s.mount('http://gittip.com/about/', HTTPAdapter())1326 order = [1327 'http://github.com/about/',1328 'http://gittip.com/about/',1329 'http://github.com',1330 'http://gittip.com',1331 'http://github',1332 'http://gittip',1333 'http://git',1334 'https://',1335 'http://',1336 ]1337 assert order == list(s.adapters)1338 s2 = requests.Session()1339 s2.adapters = {'http://': HTTPAdapter()}1340 s2.mount('https://', HTTPAdapter())1341 assert 'http://' in s2.adapters1342 assert 'https://' in s2.adapters13431344 def test_header_remove_is_case_insensitive(self, httpbin):1345 # From issue #13211346 s = requests.Session()1347 s.headers['foo'] = 'bar'1348 r = s.get(httpbin('get'), headers={'FOO': None})1349 assert 'foo' not in r.request.headers13501351 def test_params_are_merged_case_sensitive(self, httpbin):1352 s = requests.Session()1353 s.params['foo'] = 'bar'1354 r = s.get(httpbin('get'), params={'FOO': 'bar'})1355 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}13561357 def test_long_authinfo_in_url(self):1358 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(1359 'E8A3BE87-9E3F-4620-8858-95478E385B5B',1360 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1361 'exactly-------------sixty-----------three------------characters',1362 )1363 r = requests.Request('GET', url).prepare()1364 assert r.url == url13651366 def test_header_keys_are_native(self, httpbin):1367 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1368 r = requests.Request('GET', httpbin('get'), headers=headers)1369 p = r.prepare()13701371 # This is testing that they are builtin strings. A bit weird, but there1372 # we go.1373 assert 'unicode' in p.headers.keys()1374 assert 'byte' in p.headers.keys()13751376 def test_header_validation(self, httpbin):1377 """Ensure prepare_headers regex isn't flagging valid header contents."""1378 headers_ok = {'foo': 'bar baz qux',1379 'bar': u'fbbq'.encode('utf8'),1380 'baz': '',1381 'qux': '1'}1382 r = requests.get(httpbin('get'), headers=headers_ok)1383 assert r.request.headers['foo'] == headers_ok['foo']13841385 def test_header_value_not_str(self, httpbin):1386 """Ensure the header value is of type string or bytes as1387 per discussion in GH issue #33861388 """1389 headers_int = {'foo': 3}1390 headers_dict = {'bar': {'foo': 'bar'}}1391 headers_list = {'baz': ['foo', 'bar']}13921393 # Test for int1394 with pytest.raises(InvalidHeader):1395 r = requests.get(httpbin('get'), headers=headers_int)1396 # Test for dict1397 with pytest.raises(InvalidHeader):1398 r = requests.get(httpbin('get'), headers=headers_dict)1399 # Test for list1400 with pytest.raises(InvalidHeader):1401 r = requests.get(httpbin('get'), headers=headers_list)14021403 def test_header_no_return_chars(self, httpbin):1404 """Ensure that a header containing return character sequences raise an1405 exception. Otherwise, multiple headers are created from single string.1406 """1407 headers_ret = {'foo': 'bar\r\nbaz: qux'}1408 headers_lf = {'foo': 'bar\nbaz: qux'}1409 headers_cr = {'foo': 'bar\rbaz: qux'}14101411 # Test for newline1412 with pytest.raises(InvalidHeader):1413 r = requests.get(httpbin('get'), headers=headers_ret)1414 # Test for line feed1415 with pytest.raises(InvalidHeader):1416 r = requests.get(httpbin('get'), headers=headers_lf)1417 # Test for carriage return1418 with pytest.raises(InvalidHeader):1419 r = requests.get(httpbin('get'), headers=headers_cr)14201421 def test_header_no_leading_space(self, httpbin):1422 """Ensure headers containing leading whitespace raise1423 InvalidHeader Error before sending.1424 """1425 headers_space = {'foo': ' bar'}1426 headers_tab = {'foo': ' bar'}14271428 # Test for whitespace1429 with pytest.raises(InvalidHeader):1430 r = requests.get(httpbin('get'), headers=headers_space)1431 # Test for tab1432 with pytest.raises(InvalidHeader):1433 r = requests.get(httpbin('get'), headers=headers_tab)14341435 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1436 def test_can_send_objects_with_files(self, httpbin, files):1437 data = {'a': 'this is a string'}1438 files = {'b': files}1439 r = requests.Request('POST', httpbin('post'), data=data, files=files)1440 p = r.prepare()1441 assert 'multipart/form-data' in p.headers['Content-Type']14421443 def test_can_send_file_object_with_non_string_filename(self, httpbin):1444 f = io.BytesIO()1445 f.name = 21446 r = requests.Request('POST', httpbin('post'), files={'f': f})1447 p = r.prepare()14481449 assert 'multipart/form-data' in p.headers['Content-Type']14501451 def test_autoset_header_values_are_native(self, httpbin):1452 data = 'this is a string'1453 length = '16'1454 req = requests.Request('POST', httpbin('post'), data=data)1455 p = req.prepare()14561457 assert p.headers['Content-Length'] == length14581459 def test_nonhttp_schemes_dont_check_URLs(self):1460 test_urls = (1461 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1462 'file:///etc/passwd',1463 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1464 )1465 for test_url in test_urls:1466 req = requests.Request('GET', test_url)1467 preq = req.prepare()1468 assert test_url == preq.url14691470 @pytest.mark.xfail(raises=ConnectionError)1471 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1472 r = requests.get(1473 httpbin('redirect-to'),1474 params={'url': 'http://www.google.co.uk'},1475 auth=('user', 'pass'),1476 )1477 assert r.history[0].request.headers['Authorization']1478 assert not r.request.headers.get('Authorization', '')14791480 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1481 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1482 h1 = r.history[0].request.headers['Authorization']1483 h2 = r.request.headers['Authorization']14841485 assert h1 == h214861487 def test_manual_redirect_with_partial_body_read(self, httpbin):1488 s = requests.Session()1489 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1490 assert r1.is_redirect1491 rg = s.resolve_redirects(r1, r1.request, stream=True)14921493 # read only the first eight bytes of the response body,1494 # then follow the redirect1495 r1.iter_content(8)1496 r2 = next(rg)1497 assert r2.is_redirect14981499 # read all of the response via iter_content,1500 # then follow the redirect1501 for _ in r2.iter_content():1502 pass1503 r3 = next(rg)1504 assert not r3.is_redirect

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

lines 1505–1569why, one step back
1505
1506 def test_prepare_body_position_non_stream(self):1507 data = b'the data'1508 s = requests.Session()1509 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1510 assert prep._body_position is None15111512 def test_rewind_body(self):1513 data = io.BytesIO(b'the data')1514 s = requests.Session()1515 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1516 assert prep._body_position == 01517 assert prep.body.read() == b'the data'15181519 # the data has all been read1520 assert prep.body.read() == b''15211522 # rewind it back1523 requests.utils.rewind_body(prep)1524 assert prep.body.read() == b'the data'15251526 def test_rewind_partially_read_body(self):1527 data = io.BytesIO(b'the data')1528 s = requests.Session()1529 data.read(4) # read some data1530 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1531 assert prep._body_position == 41532 assert prep.body.read() == b'data'15331534 # the data has all been read1535 assert prep.body.read() == b''15361537 # rewind it back1538 requests.utils.rewind_body(prep)1539 assert prep.body.read() == b'data'15401541 def test_rewind_body_no_seek(self):1542 class BadFileObj:1543 def __init__(self, data):1544 self.data = data15451546 def tell(self):1547 return 015481549 def __iter__(self):1550 return15511552 data = BadFileObj('the data')1553 s = requests.Session()1554 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1555 assert prep._body_position == 015561557 with pytest.raises(UnrewindableBodyError) as e:1558 requests.utils.rewind_body(prep)15591560 assert 'Unable to rewind request body' in str(e)15611562 def test_rewind_body_failed_seek(self):1563 class BadFileObj:1564 def __init__(self, data):1565 self.data = data15661567 def tell(self):1568 return 01569

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

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

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

lines 1571–1583why, one step back
1571 raise OSError()
15721573 def __iter__(self):1574 return15751576 data = BadFileObj('the data')1577 s = requests.Session()1578 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1579 assert prep._body_position == 015801581 with pytest.raises(UnrewindableBodyError) as e:1582 requests.utils.rewind_body(prep)1583

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

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

Merge pull request #3655 from nateprewitt/tzickel_post_redirect_w_streamableCory Benfieldbefore adoptionf72684e

lines 1585–1605why, one step back
1585
1586 def test_rewind_body_failed_tell(self):1587 class BadFileObj:1588 def __init__(self, data):1589 self.data = data15901591 def tell(self):1592 raise OSError()15931594 def __iter__(self):1595 return15961597 data = BadFileObj('the data')1598 s = requests.Session()1599 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1600 assert prep._body_position is not None16011602 with pytest.raises(UnrewindableBodyError) as e:1603 requests.utils.rewind_body(prep)16041605 assert 'Unable to rewind request body' in str(e)

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

lines 1606–1626why, one step back
1606
1607 def _patch_adapter_gzipped_redirect(self, session, url):1608 adapter = session.get_adapter(url=url)1609 org_build_response = adapter.build_response1610 self._patched_response = False16111612 def build_response(*args, **kwargs):1613 resp = org_build_response(*args, **kwargs)1614 if not self._patched_response:1615 resp.raw.headers['content-encoding'] = 'gzip'1616 self._patched_response = True1617 return resp16181619 adapter.build_response = build_response16201621 def test_redirect_with_wrong_gzipped_header(self, httpbin):1622 s = requests.Session()1623 url = httpbin('redirect/1')1624 self._patch_adapter_gzipped_redirect(s, url)1625 s.get(url)1626

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

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

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

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

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

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

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

lines 1636–1697why, one step back
1636
1637 def test_requests_history_is_saved(self, httpbin):1638 r = requests.get(httpbin('redirect/5'))1639 total = r.history[-1].history1640 i = 01641 for item in r.history:1642 assert item.history == total[0:i]1643 i += 116441645 def test_json_param_post_content_type_works(self, httpbin):1646 r = requests.post(1647 httpbin('post'),1648 json={'life': 42}1649 )1650 assert r.status_code == 2001651 assert 'application/json' in r.request.headers['Content-Type']1652 assert {'life': 42} == r.json()['json']16531654 def test_json_param_post_should_not_override_data_param(self, httpbin):1655 r = requests.Request(method='POST', url=httpbin('post'),1656 data={'stuff': 'elixr'},1657 json={'music': 'flute'})1658 prep = r.prepare()1659 assert 'stuff=elixr' == prep.body16601661 def test_response_iter_lines(self, httpbin):1662 r = requests.get(httpbin('stream/4'), stream=True)1663 assert r.status_code == 20016641665 it = r.iter_lines()1666 next(it)1667 assert len(list(it)) == 316681669 def test_unconsumed_session_response_closes_connection(self, httpbin):1670 s = requests.session()16711672 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1673 pass16741675 assert response._content_consumed is False1676 assert response.raw.closed16771678 @pytest.mark.xfail1679 def test_response_iter_lines_reentrant(self, httpbin):1680 """Response.iter_lines() is not reentrant safe"""1681 r = requests.get(httpbin('stream/4'), stream=True)1682 assert r.status_code == 20016831684 next(r.iter_lines())1685 assert len(list(r.iter_lines())) == 316861687 def test_session_close_proxy_clear(self, mocker):1688 proxies = {1689 'one': mocker.Mock(),1690 'two': mocker.Mock(),1691 }1692 session = requests.Session()1693 mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1694 session.close()1695 proxies['one'].clear.assert_called_once_with()1696 proxies['two'].clear.assert_called_once_with()1697

Merge pull request #3660 from pawelmhm/proxy_empty_passCory Benfieldbefore adoptionbf19750

lines 1698–1707why, one step back
1698 def test_proxy_auth(self, httpbin):
1699 adapter = HTTPAdapter()1700 headers = adapter.proxy_headers("http://user:pass@httpbin.org")1701 assert headers == {'Proxy-Authorization': 'Basic dXNlcjpwYXNz'}17021703 def test_proxy_auth_empty_pass(self, httpbin):1704 adapter = HTTPAdapter()1705 headers = adapter.proxy_headers("http://user:@httpbin.org")1706 assert headers == {'Proxy-Authorization': 'Basic dXNlcjo='}1707

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

lines 1708–1728why, one step back
1708 def test_response_json_when_content_is_None(self, httpbin):
1709 r = requests.get(httpbin('/status/204'))1710 # Make sure r.content is None1711 r.status_code = 01712 r._content = False1713 r._content_consumed = False17141715 assert r.content is None1716 with pytest.raises(ValueError):1717 r.json()17181719 def test_response_without_release_conn(self):1720 """Test `close` call for non-urllib3-like raw objects.1721 Should work when `release_conn` attr doesn't exist on `response.raw`.1722 """1723 resp = requests.Response()1724 resp.raw = StringIO.StringIO('test')1725 assert not resp.raw.closed1726 resp.close()1727 assert resp.raw.closed1728

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

lines 1729–1763why, one step back
1729 def test_empty_stream_with_auth_does_not_set_content_length_header(self, httpbin):
1730 """Ensure that a byte stream with size 0 will not set both a Content-Length1731 and Transfer-Encoding header.1732 """1733 auth = ('user', 'pass')1734 url = httpbin('post')1735 file_obj = io.BytesIO(b'')1736 r = requests.Request('POST', url, auth=auth, data=file_obj)1737 prepared_request = r.prepare()1738 assert 'Transfer-Encoding' in prepared_request.headers1739 assert 'Content-Length' not in prepared_request.headers17401741 def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):1742 """Ensure that a byte stream with size > 0 will not set both a Content-Length1743 and Transfer-Encoding header.1744 """1745 auth = ('user', 'pass')1746 url = httpbin('post')1747 file_obj = io.BytesIO(b'test data')1748 r = requests.Request('POST', url, auth=auth, data=file_obj)1749 prepared_request = r.prepare()1750 assert 'Transfer-Encoding' not in prepared_request.headers1751 assert 'Content-Length' in prepared_request.headers17521753 def test_chunked_upload_does_not_set_content_length_header(self, httpbin):1754 """Ensure that requests with a generator body stream using1755 Transfer-Encoding: chunked, not a Content-Length header.1756 """1757 data = (i for i in [b'a', b'b', b'c'])1758 url = httpbin('post')1759 r = requests.Request('POST', url, data=data)1760 prepared_request = r.prepare()1761 assert 'Transfer-Encoding' in prepared_request.headers1762 assert 'Content-Length' not in prepared_request.headers1763

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

lines 1764–1806why, one step back
1764 def test_custom_redirect_mixin(self, httpbin):
1765 """Tests a custom mixin to overwrite ``get_redirect_target``.17661767 Ensures a subclassed ``requests.Session`` can handle a certain type of1768 malformed redirect responses.17691770 1. original request receives a proper response: 302 redirect1771 2. following the redirect, a malformed response is given:1772 status code = HTTP 2001773 location = alternate url1774 3. the custom session catches the edge case and follows the redirect1775 """1776 url_final = httpbin('html')1777 querystring_malformed = urlencode({'location': url_final})1778 url_redirect_malformed = httpbin('response-headers?%s' % querystring_malformed)1779 querystring_redirect = urlencode({'url': url_redirect_malformed})1780 url_redirect = httpbin('redirect-to?%s' % querystring_redirect)1781 urls_test = [url_redirect,1782 url_redirect_malformed,1783 url_final,1784 ]17851786 class CustomRedirectSession(requests.Session):1787 def get_redirect_target(self, resp):1788 # default behavior1789 if resp.is_redirect:1790 return resp.headers['location']1791 # edge case - check to see if 'location' is in headers anyways1792 location = resp.headers.get('location')1793 if location and (location != resp.url):1794 return location1795 return None17961797 session = CustomRedirectSession()1798 r = session.get(urls_test[0])1799 assert len(r.history) == 21800 assert r.status_code == 2001801 assert r.history[0].status_code == 3021802 assert r.history[0].is_redirect1803 assert r.history[1].status_code == 2001804 assert not r.history[1].is_redirect1805 assert r.url == urls_test[2]1806

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

line 1807why, one step back
1807

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

lines 1808–2013why, one step back
1808class TestCaseInsensitiveDict:
18091810 @pytest.mark.parametrize(1811 'cid', (1812 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1813 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1814 CaseInsensitiveDict(FOO='foo', BAr='bar'),1815 ))1816 def test_init(self, cid):1817 assert len(cid) == 21818 assert 'foo' in cid1819 assert 'bar' in cid18201821 def test_docstring_example(self):1822 cid = CaseInsensitiveDict()1823 cid['Accept'] = 'application/json'1824 assert cid['aCCEPT'] == 'application/json'1825 assert list(cid) == ['Accept']18261827 def test_len(self):1828 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1829 cid['A'] = 'a'1830 assert len(cid) == 218311832 def test_getitem(self):1833 cid = CaseInsensitiveDict({'Spam': 'blueval'})1834 assert cid['spam'] == 'blueval'1835 assert cid['SPAM'] == 'blueval'18361837 def test_fixes_649(self):1838 """__setitem__ should behave case-insensitively."""1839 cid = CaseInsensitiveDict()1840 cid['spam'] = 'oneval'1841 cid['Spam'] = 'twoval'1842 cid['sPAM'] = 'redval'1843 cid['SPAM'] = 'blueval'1844 assert cid['spam'] == 'blueval'1845 assert cid['SPAM'] == 'blueval'1846 assert list(cid.keys()) == ['SPAM']18471848 def test_delitem(self):1849 cid = CaseInsensitiveDict()1850 cid['Spam'] = 'someval'1851 del cid['sPam']1852 assert 'spam' not in cid1853 assert len(cid) == 018541855 def test_contains(self):1856 cid = CaseInsensitiveDict()1857 cid['Spam'] = 'someval'1858 assert 'Spam' in cid1859 assert 'spam' in cid1860 assert 'SPAM' in cid1861 assert 'sPam' in cid1862 assert 'notspam' not in cid18631864 def test_get(self):1865 cid = CaseInsensitiveDict()1866 cid['spam'] = 'oneval'1867 cid['SPAM'] = 'blueval'1868 assert cid.get('spam') == 'blueval'1869 assert cid.get('SPAM') == 'blueval'1870 assert cid.get('sPam') == 'blueval'1871 assert cid.get('notspam', 'default') == 'default'18721873 def test_update(self):1874 cid = CaseInsensitiveDict()1875 cid['spam'] = 'blueval'1876 cid.update({'sPam': 'notblueval'})1877 assert cid['spam'] == 'notblueval'1878 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1879 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1880 assert len(cid) == 21881 assert cid['foo'] == 'anotherfoo'1882 assert cid['bar'] == 'anotherbar'18831884 def test_update_retains_unchanged(self):1885 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1886 cid.update({'foo': 'newfoo'})1887 assert cid['bar'] == 'bar'18881889 def test_iter(self):1890 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1891 keys = frozenset(['Spam', 'Eggs'])1892 assert frozenset(iter(cid)) == keys18931894 def test_equality(self):1895 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1896 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1897 assert cid == othercid1898 del othercid['spam']1899 assert cid != othercid1900 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1901 assert cid != object()19021903 def test_setdefault(self):1904 cid = CaseInsensitiveDict({'Spam': 'blueval'})1905 assert cid.setdefault('spam', 'notblueval') == 'blueval'1906 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'19071908 def test_lower_items(self):1909 cid = CaseInsensitiveDict({1910 'Accept': 'application/json',1911 'user-Agent': 'requests',1912 })1913 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1914 lowerkeyset = frozenset(['accept', 'user-agent'])1915 assert keyset == lowerkeyset19161917 def test_preserve_key_case(self):1918 cid = CaseInsensitiveDict({1919 'Accept': 'application/json',1920 'user-Agent': 'requests',1921 })1922 keyset = frozenset(['Accept', 'user-Agent'])1923 assert frozenset(i[0] for i in cid.items()) == keyset1924 assert frozenset(cid.keys()) == keyset1925 assert frozenset(cid) == keyset19261927 def test_preserve_last_key_case(self):1928 cid = CaseInsensitiveDict({1929 'Accept': 'application/json',1930 'user-Agent': 'requests',1931 })1932 cid.update({'ACCEPT': 'application/json'})1933 cid['USER-AGENT'] = 'requests'1934 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1935 assert frozenset(i[0] for i in cid.items()) == keyset1936 assert frozenset(cid.keys()) == keyset1937 assert frozenset(cid) == keyset19381939 def test_copy(self):1940 cid = CaseInsensitiveDict({1941 'Accept': 'application/json',1942 'user-Agent': 'requests',1943 })1944 cid_copy = cid.copy()1945 assert cid == cid_copy1946 cid['changed'] = True1947 assert cid != cid_copy194819491950class TestMorselToCookieExpires:1951 """Tests for morsel_to_cookie when morsel contains expires."""19521953 def test_expires_valid_str(self):1954 """Test case where we convert expires from string time."""19551956 morsel = Morsel()1957 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1958 cookie = morsel_to_cookie(morsel)1959 assert cookie.expires == 119601961 @pytest.mark.parametrize(1962 'value, exception', (1963 (100, TypeError),1964 ('woops', ValueError),1965 ))1966 def test_expires_invalid_int(self, value, exception):1967 """Test case where an invalid type is passed for expires."""1968 morsel = Morsel()1969 morsel['expires'] = value1970 with pytest.raises(exception):1971 morsel_to_cookie(morsel)19721973 def test_expires_none(self):1974 """Test case where expires is None."""19751976 morsel = Morsel()1977 morsel['expires'] = None1978 cookie = morsel_to_cookie(morsel)1979 assert cookie.expires is None198019811982class TestMorselToCookieMaxAge:19831984 """Tests for morsel_to_cookie when morsel contains max-age."""19851986 def test_max_age_valid_int(self):1987 """Test case where a valid max age in seconds is passed."""19881989 morsel = Morsel()1990 morsel['max-age'] = 601991 cookie = morsel_to_cookie(morsel)1992 assert isinstance(cookie.expires, int)19931994 def test_max_age_invalid_str(self):1995 """Test case where a invalid max age is passed."""19961997 morsel = Morsel()1998 morsel['max-age'] = 'woops'1999 with pytest.raises(TypeError):2000 morsel_to_cookie(morsel)

The first 2,000 of 2,379 lines.