Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

2,372 lines · 82.0 KiB · Python

Last changed by

test entrypointsKenneth Reitzbefore adoption4c155de

History of this file

Take it

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

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 1–22why, 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)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 #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 24–35why, one step back
24from requests.exceptions import (
25 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,26 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,27 ProxyError, InvalidHeader, UnrewindableBodyError)28from requests.models import PreparedRequest29from 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 #4067 from kennethreitz/depsKenneth Reitzbefore adoptiona6c3a0c

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

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 37–67why, 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.post

test entrypointsKenneth Reitzbefore adoption4c155de

lines 68–69why, one step back
68 # Not really an entry point, but people rely on it.
69 from requests.packages.urllib3.poolmanager import PoolManager

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 70–145why, one step back
70
71 @pytest.mark.parametrize(72 'exception, url', (73 (MissingSchema, 'hiwpefhipowhefopw'),74 (InvalidSchema, 'localhost:3128'),75 (InvalidSchema, 'localhost.localdomain:3128/'),76 (InvalidSchema, '10.122.1.1:3128/'),77 (InvalidURL, 'http://'),78 ))79 def test_invalid_url(self, exception, url):80 with pytest.raises(exception):81 requests.get(url)8283 def test_basic_building(self):84 req = requests.Request()85 req.url = 'http://kennethreitz.org/'86 req.data = {'life': '42'}8788 pr = req.prepare()89 assert pr.url == req.url90 assert pr.body == 'life=42'9192 @pytest.mark.parametrize('method', ('GET', 'HEAD'))93 def test_no_content_length(self, httpbin, method):94 req = requests.Request(method, httpbin(method.lower())).prepare()95 assert 'Content-Length' not in req.headers9697 @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))98 def test_no_body_content_length(self, httpbin, method):99 req = requests.Request(method, httpbin(method.lower())).prepare()100 assert req.headers['Content-Length'] == '0'101102 @pytest.mark.parametrize('method', ('POST', 'PUT', 'PATCH', 'OPTIONS'))103 def test_empty_content_length(self, httpbin, method):104 req = requests.Request(method, httpbin(method.lower()), data='').prepare()105 assert req.headers['Content-Length'] == '0'106107 def test_override_content_length(self, httpbin):108 headers = {109 'Content-Length': 'not zero'110 }111 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()112 assert 'Content-Length' in r.headers113 assert r.headers['Content-Length'] == 'not zero'114115 def test_path_is_not_double_encoded(self):116 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()117118 assert request.path_url == '/get/test%20case'119120 @pytest.mark.parametrize(121 'url, expected', (122 ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),123 ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')124 ))125 def test_params_are_added_before_fragment(self, url, expected):126 request = requests.Request('GET', url, params={"a": "b"}).prepare()127 assert request.url == expected128129 def test_params_original_order_is_preserved_by_default(self):130 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))131 session = requests.Session()132 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)133 prep = session.prepare_request(request)134 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'135136 def test_params_bytes_are_encoded(self):137 request = requests.Request('GET', 'http://example.com',138 params=b'test=foo').prepare()139 assert request.url == 'http://example.com/?test=foo'140141 def test_binary_put(self):142 request = requests.Request('PUT', 'http://example.com',143 data=u"ööö".encode("utf-8")).prepare()144 assert isinstance(request.body, bytes)145

Merge pull request #3697 from hussaintamboli/masterCory Benfieldbefore adoption1e198f9

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

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 151–486why, one step back
151 @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))
152 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):153 s = requests.Session()154 s.proxies = getproxies()155 parts = urlparse(httpbin('get'))156 url = scheme + parts.netloc + parts.path157 r = requests.Request('GET', url)158 r = s.send(r.prepare())159 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)160161 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):162 r = requests.Request('GET', httpbin('get'))163 s = requests.Session()164 s.proxies = getproxies()165166 r = s.send(r.prepare())167168 assert r.status_code == 200169170 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):171 r = requests.get(httpbin('redirect', '1'))172 assert r.status_code == 200173 assert r.history[0].status_code == 302174 assert r.history[0].is_redirect175176 def test_HTTP_307_ALLOW_REDIRECT_POST(self, httpbin):177 r = requests.post(httpbin('redirect-to'), data='test', params={'url': 'post', 'status_code': 307})178 assert r.status_code == 200179 assert r.history[0].status_code == 307180 assert r.history[0].is_redirect181 assert r.json()['data'] == 'test'182183 def test_HTTP_307_ALLOW_REDIRECT_POST_WITH_SEEKABLE(self, httpbin):184 byte_str = b'test'185 r = requests.post(httpbin('redirect-to'), data=io.BytesIO(byte_str), params={'url': 'post', 'status_code': 307})186 assert r.status_code == 200187 assert r.history[0].status_code == 307188 assert r.history[0].is_redirect189 assert r.json()['data'] == byte_str.decode('utf-8')190191 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):192 try:193 requests.get(httpbin('relative-redirect', '50'))194 except TooManyRedirects as e:195 url = httpbin('relative-redirect', '20')196 assert e.request.url == url197 assert e.response.url == url198 assert len(e.response.history) == 30199 else:200 pytest.fail('Expected redirect to raise TooManyRedirects but it did not')201202 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):203 s = requests.session()204 s.max_redirects = 5205 try:206 s.get(httpbin('relative-redirect', '50'))207 except TooManyRedirects as e:208 url = httpbin('relative-redirect', '45')209 assert e.request.url == url210 assert e.response.url == url211 assert len(e.response.history) == 5212 else:213 pytest.fail('Expected custom max number of redirects to be respected but was not')214215 def test_http_301_changes_post_to_get(self, httpbin):216 r = requests.post(httpbin('status', '301'))217 assert r.status_code == 200218 assert r.request.method == 'GET'219 assert r.history[0].status_code == 301220 assert r.history[0].is_redirect221222 def test_http_301_doesnt_change_head_to_get(self, httpbin):223 r = requests.head(httpbin('status', '301'), allow_redirects=True)224 print(r.content)225 assert r.status_code == 200226 assert r.request.method == 'HEAD'227 assert r.history[0].status_code == 301228 assert r.history[0].is_redirect229230 def test_http_302_changes_post_to_get(self, httpbin):231 r = requests.post(httpbin('status', '302'))232 assert r.status_code == 200233 assert r.request.method == 'GET'234 assert r.history[0].status_code == 302235 assert r.history[0].is_redirect236237 def test_http_302_doesnt_change_head_to_get(self, httpbin):238 r = requests.head(httpbin('status', '302'), allow_redirects=True)239 assert r.status_code == 200240 assert r.request.method == 'HEAD'241 assert r.history[0].status_code == 302242 assert r.history[0].is_redirect243244 def test_http_303_changes_post_to_get(self, httpbin):245 r = requests.post(httpbin('status', '303'))246 assert r.status_code == 200247 assert r.request.method == 'GET'248 assert r.history[0].status_code == 303249 assert r.history[0].is_redirect250251 def test_http_303_doesnt_change_head_to_get(self, httpbin):252 r = requests.head(httpbin('status', '303'), allow_redirects=True)253 assert r.status_code == 200254 assert r.request.method == 'HEAD'255 assert r.history[0].status_code == 303256 assert r.history[0].is_redirect257258 def test_header_and_body_removal_on_redirect(self, httpbin):259 purged_headers = ('Content-Length', 'Content-Type')260 ses = requests.Session()261 req = requests.Request('POST', httpbin('post'), data={'test': 'data'})262 prep = ses.prepare_request(req)263 resp = ses.send(prep)264265 # Mimic a redirect response266 resp.status_code = 302267 resp.headers['location'] = 'get'268269 # Run request through resolve_redirects270 next_resp = next(ses.resolve_redirects(resp, prep))271 assert next_resp.request.body is None272 for header in purged_headers:273 assert header not in next_resp.request.headers274275 def test_transfer_enc_removal_on_redirect(self, httpbin):276 purged_headers = ('Transfer-Encoding', 'Content-Type')277 ses = requests.Session()278 req = requests.Request('POST', httpbin('post'), data=(b'x' for x in range(1)))279 prep = ses.prepare_request(req)280 assert 'Transfer-Encoding' in prep.headers281282 # Create Response to avoid https://github.com/kevin1024/pytest-httpbin/issues/33283 resp = requests.Response()284 resp.raw = io.BytesIO(b'the content')285 resp.request = prep286 setattr(resp.raw, 'release_conn', lambda *args: args)287288 # Mimic a redirect response289 resp.status_code = 302290 resp.headers['location'] = httpbin('get')291292 # Run request through resolve_redirect293 next_resp = next(ses.resolve_redirects(resp, prep))294 assert next_resp.request.body is None295 for header in purged_headers:296 assert header not in next_resp.request.headers297298 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):299 heads = {'User-agent': 'Mozilla/5.0'}300301 r = requests.get(httpbin('user-agent'), headers=heads)302303 assert heads['User-agent'] in r.text304 assert r.status_code == 200305306 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):307 heads = {'User-agent': 'Mozilla/5.0'}308309 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)310 assert r.status_code == 200311312 def test_set_cookie_on_301(self, httpbin):313 s = requests.session()314 url = httpbin('cookies/set?foo=bar')315 s.get(url)316 assert s.cookies['foo'] == 'bar'317318 def test_cookie_sent_on_redirect(self, httpbin):319 s = requests.session()320 s.get(httpbin('cookies/set?foo=bar'))321 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')322 assert 'Cookie' in r.json()['headers']323324 def test_cookie_removed_on_expire(self, httpbin):325 s = requests.session()326 s.get(httpbin('cookies/set?foo=bar'))327 assert s.cookies['foo'] == 'bar'328 s.get(329 httpbin('response-headers'),330 params={331 'Set-Cookie':332 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'333 }334 )335 assert 'foo' not in s.cookies336337 def test_cookie_quote_wrapped(self, httpbin):338 s = requests.session()339 s.get(httpbin('cookies/set?foo="bar:baz"'))340 assert s.cookies['foo'] == '"bar:baz"'341342 def test_cookie_persists_via_api(self, httpbin):343 s = requests.session()344 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})345 assert 'foo' in r.request.headers['Cookie']346 assert 'foo' in r.history[0].request.headers['Cookie']347348 def test_request_cookie_overrides_session_cookie(self, httpbin):349 s = requests.session()350 s.cookies['foo'] = 'bar'351 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})352 assert r.json()['cookies']['foo'] == 'baz'353 # Session cookie should not be modified354 assert s.cookies['foo'] == 'bar'355356 def test_request_cookies_not_persisted(self, httpbin):357 s = requests.session()358 s.get(httpbin('cookies'), cookies={'foo': 'baz'})359 # Sending a request with cookies should not add cookies to the session360 assert not s.cookies361362 def test_generic_cookiejar_works(self, httpbin):363 cj = cookielib.CookieJar()364 cookiejar_from_dict({'foo': 'bar'}, cj)365 s = requests.session()366 s.cookies = cj367 r = s.get(httpbin('cookies'))368 # Make sure the cookie was sent369 assert r.json()['cookies']['foo'] == 'bar'370 # Make sure the session cj is still the custom one371 assert s.cookies is cj372373 def test_param_cookiejar_works(self, httpbin):374 cj = cookielib.CookieJar()375 cookiejar_from_dict({'foo': 'bar'}, cj)376 s = requests.session()377 r = s.get(httpbin('cookies'), cookies=cj)378 # Make sure the cookie was sent379 assert r.json()['cookies']['foo'] == 'bar'380381 def test_cookielib_cookiejar_on_redirect(self, httpbin):382 """Tests resolve_redirect doesn't fail when merging cookies383 with non-RequestsCookieJar cookiejar.384385 See GH #3579386 """387 cj = cookiejar_from_dict({'foo': 'bar'}, cookielib.CookieJar())388 s = requests.Session()389 s.cookies = cookiejar_from_dict({'cookie': 'tasty'})390391 # Prepare request without using Session392 req = requests.Request('GET', httpbin('headers'), cookies=cj)393 prep_req = req.prepare()394395 # Send request and simulate redirect396 resp = s.send(prep_req)397 resp.status_code = 302398 resp.headers['location'] = httpbin('get')399 redirects = s.resolve_redirects(resp, prep_req)400 resp = next(redirects)401402 # Verify CookieJar isn't being converted to RequestsCookieJar403 assert isinstance(prep_req._cookies, cookielib.CookieJar)404 assert isinstance(resp.request._cookies, cookielib.CookieJar)405 assert not isinstance(resp.request._cookies, requests.cookies.RequestsCookieJar)406407 cookies = {}408 for c in resp.request._cookies:409 cookies[c.name] = c.value410 assert cookies['foo'] == 'bar'411 assert cookies['cookie'] == 'tasty'412413 def test_requests_in_history_are_not_overridden(self, httpbin):414 resp = requests.get(httpbin('redirect/3'))415 urls = [r.url for r in resp.history]416 req_urls = [r.request.url for r in resp.history]417 assert urls == req_urls418419 def test_history_is_always_a_list(self, httpbin):420 """Show that even with redirects, Response.history is always a list."""421 resp = requests.get(httpbin('get'))422 assert isinstance(resp.history, list)423 resp = requests.get(httpbin('redirect/1'))424 assert isinstance(resp.history, list)425 assert not isinstance(resp.history, tuple)426427 def test_headers_on_session_with_None_are_not_sent(self, httpbin):428 """Do not send headers in Session.headers with None values."""429 ses = requests.Session()430 ses.headers['Accept-Encoding'] = None431 req = requests.Request('GET', httpbin('get'))432 prep = ses.prepare_request(req)433 assert 'Accept-Encoding' not in prep.headers434435 def test_headers_preserve_order(self, httpbin):436 """Preserve order when headers provided as OrderedDict."""437 ses = requests.Session()438 ses.headers = OrderedDict()439 ses.headers['Accept-Encoding'] = 'identity'440 ses.headers['First'] = '1'441 ses.headers['Second'] = '2'442 headers = OrderedDict([('Third', '3'), ('Fourth', '4')])443 headers['Fifth'] = '5'444 headers['Second'] = '222'445 req = requests.Request('GET', httpbin('get'), headers=headers)446 prep = ses.prepare_request(req)447 items = list(prep.headers.items())448 assert items[0] == ('Accept-Encoding', 'identity')449 assert items[1] == ('First', '1')450 assert items[2] == ('Second', '222')451 assert items[3] == ('Third', '3')452 assert items[4] == ('Fourth', '4')453 assert items[5] == ('Fifth', '5')454455 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))456 def test_user_agent_transfers(self, httpbin, key):457458 heads = {key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'}459460 r = requests.get(httpbin('user-agent'), headers=heads)461 assert heads[key] in r.text462463 def test_HTTP_200_OK_HEAD(self, httpbin):464 r = requests.head(httpbin('get'))465 assert r.status_code == 200466467 def test_HTTP_200_OK_PUT(self, httpbin):468 r = requests.put(httpbin('put'))469 assert r.status_code == 200470471 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):472 auth = ('user', 'pass')473 url = httpbin('basic-auth', 'user', 'pass')474475 r = requests.get(url, auth=auth)476 assert r.status_code == 200477478 r = requests.get(url)479 assert r.status_code == 401480481 s = requests.session()482 s.auth = auth483 r = s.get(url)484 assert r.status_code == 200485486 @pytest.mark.parametrize(

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

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

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

lines 490–491why, one step back
490 (42, 42),
491 (None, None),

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

lines 492–500why, one step back
492 ))
493 def test_set_basicauth(self, httpbin, username, password):494 auth = (username, password)495 url = httpbin('get')496497 r = requests.Request('GET', url, auth=auth)498 p = r.prepare()499500 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 501–510why, one step back
501
502 def test_basicauth_encodes_byte_strings(self):503 """Ensure b'test' formats as the byte string "test" rather504 than the unicode string "b'test'" in Python 3.505 """506 auth = (b'\xc5\xafsername', b'test\xc6\xb6')507 r = requests.Request('GET', 'http://localhost', auth=auth)508 p = r.prepare()509510 assert p.headers['Authorization'] == 'Basic xa9zZXJuYW1lOnRlc3TGtg=='

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

lines 511–512why, one step back
511
512 @pytest.mark.parametrize(

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 513–637why, one step back
513 'url, exception', (
514 # Connecting to an unknown domain should raise a ConnectionError515 ('http://doesnotexist.google.com', ConnectionError),516 # Connecting to an invalid port should raise a ConnectionError517 ('http://localhost:1', ConnectionError),518 # Inputing a URL that cannot be parsed should raise an InvalidURL error519 ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)520 ))521 def test_errors(self, url, exception):522 with pytest.raises(exception):523 requests.get(url, timeout=1)524525 def test_proxy_error(self):526 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError527 with pytest.raises(ProxyError):528 requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})529530 def test_basicauth_with_netrc(self, httpbin):531 auth = ('user', 'pass')532 wrong_auth = ('wronguser', 'wrongpass')533 url = httpbin('basic-auth', 'user', 'pass')534535 old_auth = requests.sessions.get_netrc_auth536537 try:538 def get_netrc_auth_mock(url):539 return auth540 requests.sessions.get_netrc_auth = get_netrc_auth_mock541542 # Should use netrc and work.543 r = requests.get(url)544 assert r.status_code == 200545546 # Given auth should override and fail.547 r = requests.get(url, auth=wrong_auth)548 assert r.status_code == 401549550 s = requests.session()551552 # Should use netrc and work.553 r = s.get(url)554 assert r.status_code == 200555556 # Given auth should override and fail.557 s.auth = wrong_auth558 r = s.get(url)559 assert r.status_code == 401560 finally:561 requests.sessions.get_netrc_auth = old_auth562563 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):564565 auth = HTTPDigestAuth('user', 'pass')566 url = httpbin('digest-auth', 'auth', 'user', 'pass')567568 r = requests.get(url, auth=auth)569 assert r.status_code == 200570571 r = requests.get(url)572 assert r.status_code == 401573574 s = requests.session()575 s.auth = HTTPDigestAuth('user', 'pass')576 r = s.get(url)577 assert r.status_code == 200578579 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):580 url = httpbin('digest-auth', 'auth', 'user', 'pass')581 auth = HTTPDigestAuth('user', 'pass')582 r = requests.get(url)583 assert r.cookies['fake'] == 'fake_value'584585 r = requests.get(url, auth=auth)586 assert r.status_code == 200587588 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):589 url = httpbin('digest-auth', 'auth', 'user', 'pass')590 auth = HTTPDigestAuth('user', 'pass')591 s = requests.Session()592 s.get(url, auth=auth)593 assert s.cookies['fake'] == 'fake_value'594595 def test_DIGEST_STREAM(self, httpbin):596597 auth = HTTPDigestAuth('user', 'pass')598 url = httpbin('digest-auth', 'auth', 'user', 'pass')599600 r = requests.get(url, auth=auth, stream=True)601 assert r.raw.read() != b''602603 r = requests.get(url, auth=auth, stream=False)604 assert r.raw.read() == b''605606 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):607608 auth = HTTPDigestAuth('user', 'wrongpass')609 url = httpbin('digest-auth', 'auth', 'user', 'pass')610611 r = requests.get(url, auth=auth)612 assert r.status_code == 401613614 r = requests.get(url)615 assert r.status_code == 401616617 s = requests.session()618 s.auth = auth619 r = s.get(url)620 assert r.status_code == 401621622 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):623624 auth = HTTPDigestAuth('user', 'pass')625 url = httpbin('digest-auth', 'auth', 'user', 'pass')626627 r = requests.get(url, auth=auth)628 assert '"auth"' in r.request.headers['Authorization']629630 def test_POSTBIN_GET_POST_FILES(self, httpbin):631632 url = httpbin('post')633 requests.post(url).raise_for_status()634635 post1 = requests.post(url, data={'some': 'data'})636 assert post1.status_code == 200637

fix broken testsKenneth Reitzbefore adoption97b5bc2

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

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 639–697why, one step back
639 post2 = requests.post(url, files={'some': f})
640 assert post2.status_code == 200641642 post4 = requests.post(url, data='[{"some": "json"}]')643 assert post4.status_code == 200644645 with pytest.raises(ValueError):646 requests.post(url, files=['bad file data'])647648 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):649650 class TestStream(object):651 def __init__(self, data):652 self.data = data.encode()653 self.length = len(self.data)654 self.index = 0655656 def __len__(self):657 return self.length658659 def read(self, size=None):660 if size:661 ret = self.data[self.index:self.index + size]662 self.index += size663 else:664 ret = self.data[self.index:]665 self.index = self.length666 return ret667668 def tell(self):669 return self.index670671 def seek(self, offset, where=0):672 if where == 0:673 self.index = offset674 elif where == 1:675 self.index += offset676 elif where == 2:677 self.index = self.length + offset678679 test = TestStream('test')680 post1 = requests.post(httpbin('post'), data=test)681 assert post1.status_code == 200682 assert post1.json()['data'] == 'test'683684 test = TestStream('test')685 test.seek(2)686 post2 = requests.post(httpbin('post'), data=test)687 assert post2.status_code == 200688 assert post2.json()['data'] == 'st'689690 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):691692 url = httpbin('post')693 requests.post(url).raise_for_status()694695 post1 = requests.post(url, data={'some': 'data'})696 assert post1.status_code == 200697

fix broken testsKenneth Reitzbefore adoption97b5bc2

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

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 699–734why, one step back
699 post2 = requests.post(url, data={'some': 'data'}, files={'some': f})
700 assert post2.status_code == 200701702 post4 = requests.post(url, data='[{"some": "json"}]')703 assert post4.status_code == 200704705 with pytest.raises(ValueError):706 requests.post(url, files=['bad file data'])707708 def test_post_with_custom_mapping(self, httpbin):709 class CustomMapping(collections.MutableMapping):710 def __init__(self, *args, **kwargs):711 self.data = dict(*args, **kwargs)712713 def __delitem__(self, key):714 del self.data[key]715716 def __getitem__(self, key):717 return self.data[key]718719 def __setitem__(self, key, value):720 self.data[key] = value721722 def __iter__(self):723 return iter(self.data)724725 def __len__(self):726 return len(self.data)727728 data = CustomMapping({'some': 'data'})729 url = httpbin('post')730 found_json = requests.post(url, data=data).json().get('form')731 assert found_json == {'some': 'data'}732733 def test_conflicting_post_params(self, httpbin):734 url = httpbin('post')

fix broken testsKenneth Reitzbefore adoption97b5bc2

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

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 736–774why, one step back
736 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")
737 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")738739 def test_request_ok_set(self, httpbin):740 r = requests.get(httpbin('status', '404'))741 assert not r.ok742743 def test_status_raising(self, httpbin):744 r = requests.get(httpbin('status', '404'))745 with pytest.raises(requests.exceptions.HTTPError):746 r.raise_for_status()747748 r = requests.get(httpbin('status', '500'))749 assert not r.ok750751 def test_decompress_gzip(self, httpbin):752 r = requests.get(httpbin('gzip'))753 r.content.decode('ascii')754755 @pytest.mark.parametrize(756 'url, params', (757 ('/get', {'foo': 'føø'}),758 ('/get', {'føø': 'føø'}),759 ('/get', {'føø': 'føø'}),760 ('/get', {'foo': 'foo'}),761 ('ø', {'foo': 'foo'}),762 ))763 def test_unicode_get(self, httpbin, url, params):764 requests.get(httpbin(url), params=params)765766 def test_unicode_header_name(self, httpbin):767 requests.put(768 httpbin('put'),769 headers={str('Content-Type'): 'application/octet-stream'},770 data='\xff') # compat.str is unicode.771772 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):773 requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)774

Merge pull request #3927 from bagerard/raise_IOError_invalid_certificate_filesCory Benfieldbefore adoption993cbf5

lines 775–790why, one step back
775 def test_invalid_ca_certificate_path(self, httpbin_secure):
776 INVALID_PATH = '/garbage'777 with pytest.raises(IOError) as e:778 requests.get(httpbin_secure(), verify=INVALID_PATH)779 assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {0}'.format(INVALID_PATH)780781 def test_invalid_ssl_certificate_files(self, httpbin_secure):782 INVALID_PATH = '/garbage'783 with pytest.raises(IOError) as e:784 requests.get(httpbin_secure(), cert=INVALID_PATH)785 assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {0}'.format(INVALID_PATH)786787 with pytest.raises(IOError) as e:788 requests.get(httpbin_secure(), cert=('.', INVALID_PATH))789 assert str(e.value) == 'Could not find the TLS key file, invalid path: {0}'.format(INVALID_PATH)790

Merge branch 'kaptajnen-master'Cory Benfieldbefore adoptionfb3f2a0

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

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 795–1131why, one step back
795 def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):
796 """warnings are emitted with requests.get"""797 if HAS_MODERN_SSL or HAS_PYOPENSSL:798 warnings_expected = ('SubjectAltNameWarning', )799 else:800 warnings_expected = ('SNIMissingWarning',801 'InsecurePlatformWarning',802 'SubjectAltNameWarning', )803804 with pytest.warns(None) as warning_records:805 warnings.simplefilter('always')806 requests.get(httpbin_secure('status', '200'),807 verify=httpbin_ca_bundle)808809 warning_records = [item for item in warning_records810 if item.category.__name__ != 'ResourceWarning']811812 warnings_category = tuple(813 item.category.__name__ for item in warning_records)814 assert warnings_category == warnings_expected815816 def test_urlencoded_get_query_multivalued_param(self, httpbin):817818 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))819 assert r.status_code == 200820 assert r.url == httpbin('get?test=foo&test=baz')821822 def test_different_encodings_dont_break_post(self, httpbin):823 r = requests.post(httpbin('post'),824 data={'stuff': json.dumps({'a': 123})},825 params={'blah': 'asdf1234'},826 files={'file': ('test_requests.py', open(__file__, 'rb'))})827 assert r.status_code == 200828829 @pytest.mark.parametrize(830 'data', (831 {'stuff': u('ëlïxr')},832 {'stuff': u('ëlïxr').encode('utf-8')},833 {'stuff': 'elixr'},834 {'stuff': 'elixr'.encode('utf-8')},835 ))836 def test_unicode_multipart_post(self, httpbin, data):837 r = requests.post(httpbin('post'),838 data=data,839 files={'file': ('test_requests.py', open(__file__, 'rb'))})840 assert r.status_code == 200841842 def test_unicode_multipart_post_fieldnames(self, httpbin):843 filename = os.path.splitext(__file__)[0] + '.py'844 r = requests.Request(845 method='POST', url=httpbin('post'),846 data={'stuff'.encode('utf-8'): 'elixr'},847 files={'file': ('test_requests.py', open(filename, 'rb'))})848 prep = r.prepare()849 assert b'name="stuff"' in prep.body850 assert b'name="b\'stuff\'"' not in prep.body851852 def test_unicode_method_name(self, httpbin):853 files = {'file': open(__file__, 'rb')}854 r = requests.request(855 method=u('POST'), url=httpbin('post'), files=files)856 assert r.status_code == 200857858 def test_unicode_method_name_with_request_object(self, httpbin):859 files = {'file': open(__file__, 'rb')}860 s = requests.Session()861 req = requests.Request(u('POST'), httpbin('post'), files=files)862 prep = s.prepare_request(req)863 assert isinstance(prep.method, builtin_str)864 assert prep.method == 'POST'865866 resp = s.send(prep)867 assert resp.status_code == 200868869 def test_non_prepared_request_error(self):870 s = requests.Session()871 req = requests.Request(u('POST'), '/')872873 with pytest.raises(ValueError) as e:874 s.send(req)875 assert str(e.value) == 'You can only send PreparedRequests.'876877 def test_custom_content_type(self, httpbin):878 r = requests.post(879 httpbin('post'),880 data={'stuff': json.dumps({'a': 123})},881 files={882 'file1': ('test_requests.py', open(__file__, 'rb')),883 'file2': ('test_requests', open(__file__, 'rb'),884 'text/py-content-type')})885 assert r.status_code == 200886 assert b"text/py-content-type" in r.request.body887888 def test_hook_receives_request_arguments(self, httpbin):889 def hook(resp, **kwargs):890 assert resp is not None891 assert kwargs != {}892893 s = requests.Session()894 r = requests.Request('GET', httpbin(), hooks={'response': hook})895 prep = s.prepare_request(r)896 s.send(prep)897898 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):899 hook = lambda x, *args, **kwargs: x900 s = requests.Session()901 s.hooks['response'].append(hook)902 r = requests.Request('GET', httpbin())903 prep = s.prepare_request(r)904 assert prep.hooks['response'] != []905 assert prep.hooks['response'] == [hook]906907 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):908 hook1 = lambda x, *args, **kwargs: x909 hook2 = lambda x, *args, **kwargs: x910 assert hook1 is not hook2911 s = requests.Session()912 s.hooks['response'].append(hook2)913 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})914 prep = s.prepare_request(r)915 assert prep.hooks['response'] == [hook1]916917 def test_prepared_request_hook(self, httpbin):918 def hook(resp, **kwargs):919 resp.hook_working = True920 return resp921922 req = requests.Request('GET', httpbin(), hooks={'response': hook})923 prep = req.prepare()924925 s = requests.Session()926 s.proxies = getproxies()927 resp = s.send(prep)928929 assert hasattr(resp, 'hook_working')930931 def test_prepared_from_session(self, httpbin):932 class DummyAuth(requests.auth.AuthBase):933 def __call__(self, r):934 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'935 return r936937 req = requests.Request('GET', httpbin('headers'))938 assert not req.auth939940 s = requests.Session()941 s.auth = DummyAuth()942943 prep = s.prepare_request(req)944 resp = s.send(prep)945946 assert resp.json()['headers'][947 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'948949 def test_prepare_request_with_bytestring_url(self):950 req = requests.Request('GET', b'https://httpbin.org/')951 s = requests.Session()952 prep = s.prepare_request(req)953 assert prep.url == "https://httpbin.org/"954955 def test_request_with_bytestring_host(self, httpbin):956 s = requests.Session()957 resp = s.request(958 'GET',959 httpbin('cookies/set?cookie=value'),960 allow_redirects=False,961 headers={'Host': b'httpbin.org'}962 )963 assert resp.cookies.get('cookie') == 'value'964965 def test_links(self):966 r = requests.Response()967 r.headers = {968 'cache-control': 'public, max-age=60, s-maxage=60',969 'connection': 'keep-alive',970 'content-encoding': 'gzip',971 'content-type': 'application/json; charset=utf-8',972 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',973 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',974 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',975 'link': ('<https://api.github.com/users/kennethreitz/repos?'976 'page=2&per_page=10>; rel="next", <https://api.github.'977 'com/users/kennethreitz/repos?page=7&per_page=10>; '978 ' rel="last"'),979 'server': 'GitHub.com',980 'status': '200 OK',981 'vary': 'Accept',982 'x-content-type-options': 'nosniff',983 'x-github-media-type': 'github.beta',984 'x-ratelimit-limit': '60',985 'x-ratelimit-remaining': '57'986 }987 assert r.links['next']['rel'] == 'next'988989 def test_cookie_parameters(self):990 key = 'some_cookie'991 value = 'some_value'992 secure = True993 domain = 'test.com'994 rest = {'HttpOnly': True}995996 jar = requests.cookies.RequestsCookieJar()997 jar.set(key, value, secure=secure, domain=domain, rest=rest)998999 assert len(jar) == 11000 assert 'some_cookie' in jar10011002 cookie = list(jar)[0]1003 assert cookie.secure == secure1004 assert cookie.domain == domain1005 assert cookie._rest['HttpOnly'] == rest['HttpOnly']10061007 def test_cookie_as_dict_keeps_len(self):1008 key = 'some_cookie'1009 value = 'some_value'10101011 key1 = 'some_cookie1'1012 value1 = 'some_value1'10131014 jar = requests.cookies.RequestsCookieJar()1015 jar.set(key, value)1016 jar.set(key1, value1)10171018 d1 = dict(jar)1019 d2 = dict(jar.iteritems())1020 d3 = dict(jar.items())10211022 assert len(jar) == 21023 assert len(d1) == 21024 assert len(d2) == 21025 assert len(d3) == 210261027 def test_cookie_as_dict_keeps_items(self):1028 key = 'some_cookie'1029 value = 'some_value'10301031 key1 = 'some_cookie1'1032 value1 = 'some_value1'10331034 jar = requests.cookies.RequestsCookieJar()1035 jar.set(key, value)1036 jar.set(key1, value1)10371038 d1 = dict(jar)1039 d2 = dict(jar.iteritems())1040 d3 = dict(jar.items())10411042 assert d1['some_cookie'] == 'some_value'1043 assert d2['some_cookie'] == 'some_value'1044 assert d3['some_cookie1'] == 'some_value1'10451046 def test_cookie_as_dict_keys(self):1047 key = 'some_cookie'1048 value = 'some_value'10491050 key1 = 'some_cookie1'1051 value1 = 'some_value1'10521053 jar = requests.cookies.RequestsCookieJar()1054 jar.set(key, value)1055 jar.set(key1, value1)10561057 keys = jar.keys()1058 assert keys == list(keys)1059 # make sure one can use keys multiple times1060 assert list(keys) == list(keys)10611062 def test_cookie_as_dict_values(self):1063 key = 'some_cookie'1064 value = 'some_value'10651066 key1 = 'some_cookie1'1067 value1 = 'some_value1'10681069 jar = requests.cookies.RequestsCookieJar()1070 jar.set(key, value)1071 jar.set(key1, value1)10721073 values = jar.values()1074 assert values == list(values)1075 # make sure one can use values multiple times1076 assert list(values) == list(values)10771078 def test_cookie_as_dict_items(self):1079 key = 'some_cookie'1080 value = 'some_value'10811082 key1 = 'some_cookie1'1083 value1 = 'some_value1'10841085 jar = requests.cookies.RequestsCookieJar()1086 jar.set(key, value)1087 jar.set(key1, value1)10881089 items = jar.items()1090 assert items == list(items)1091 # make sure one can use items multiple times1092 assert list(items) == list(items)10931094 def test_cookie_duplicate_names_different_domains(self):1095 key = 'some_cookie'1096 value = 'some_value'1097 domain1 = 'test1.com'1098 domain2 = 'test2.com'10991100 jar = requests.cookies.RequestsCookieJar()1101 jar.set(key, value, domain=domain1)1102 jar.set(key, value, domain=domain2)1103 assert key in jar1104 items = jar.items()1105 assert len(items) == 211061107 # Verify that CookieConflictError is raised if domain is not specified1108 with pytest.raises(requests.cookies.CookieConflictError):1109 jar.get(key)11101111 # Verify that CookieConflictError is not raised if domain is specified1112 cookie = jar.get(key, domain=domain1)1113 assert cookie == value11141115 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):1116 key = 'some_cookie'1117 value = 'some_value'1118 path = 'some_path'11191120 jar = requests.cookies.RequestsCookieJar()1121 jar.set(key, value, path=path)1122 jar.set(key, value)1123 with pytest.raises(requests.cookies.CookieConflictError):1124 jar.get(key)11251126 def test_time_elapsed_blank(self, httpbin):1127 r = requests.get(httpbin('get'))1128 td = r.elapsed1129 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)1130 assert total_seconds > 0.01131

Merge pull request #3718 from nsoranzo/masterCory Benfieldbefore adoption36c9c8c

lines 1132–1135why, one step back
1132 def test_empty_response_has_content_none(self):
1133 r = requests.Response()1134 assert r.content is None1135

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 1136–1571why, one step back
1136 def test_response_is_iterable(self):
1137 r = requests.Response()1138 io = StringIO.StringIO('abc')1139 read_ = io.read11401141 def read_mock(amt, decode_content=None):1142 return read_(amt)1143 setattr(io, 'read', read_mock)1144 r.raw = io1145 assert next(iter(r))1146 io.close()11471148 def test_response_decode_unicode(self):1149 """When called with decode_unicode, Response.iter_content should always1150 return unicode.1151 """1152 r = requests.Response()1153 r._content_consumed = True1154 r._content = b'the content'1155 r.encoding = 'ascii'11561157 chunks = r.iter_content(decode_unicode=True)1158 assert all(isinstance(chunk, str) for chunk in chunks)11591160 # also for streaming1161 r = requests.Response()1162 r.raw = io.BytesIO(b'the content')1163 r.encoding = 'ascii'1164 chunks = r.iter_content(decode_unicode=True)1165 assert all(isinstance(chunk, str) for chunk in chunks)11661167 def test_response_reason_unicode(self):1168 # check for unicode HTTP status1169 r = requests.Response()1170 r.url = u'unicode URL'1171 r.reason = u'Komponenttia ei löydy'.encode('utf-8')1172 r.status_code = 4041173 r.encoding = None1174 assert not r.ok # old behaviour - crashes here11751176 def test_response_reason_unicode_fallback(self):1177 # check raise_status falls back to ISO-8859-11178 r = requests.Response()1179 r.url = 'some url'1180 reason = u'Komponenttia ei löydy'1181 r.reason = reason.encode('latin-1')1182 r.status_code = 5001183 r.encoding = None1184 with pytest.raises(requests.exceptions.HTTPError) as e:1185 r.raise_for_status()1186 assert reason in e.value.args[0]11871188 def test_response_chunk_size_type(self):1189 """Ensure that chunk_size is passed as None or an integer, otherwise1190 raise a TypeError.1191 """1192 r = requests.Response()1193 r.raw = io.BytesIO(b'the content')1194 chunks = r.iter_content(1)1195 assert all(len(chunk) == 1 for chunk in chunks)11961197 r = requests.Response()1198 r.raw = io.BytesIO(b'the content')1199 chunks = r.iter_content(None)1200 assert list(chunks) == [b'the content']12011202 r = requests.Response()1203 r.raw = io.BytesIO(b'the content')1204 with pytest.raises(TypeError):1205 chunks = r.iter_content("1024")12061207 def test_request_and_response_are_pickleable(self, httpbin):1208 r = requests.get(httpbin('get'))12091210 # verify we can pickle the original request1211 assert pickle.loads(pickle.dumps(r.request))12121213 # verify we can pickle the response and that we have access to1214 # the original request.1215 pr = pickle.loads(pickle.dumps(r))1216 assert r.request.url == pr.request.url1217 assert r.request.headers == pr.request.headers12181219 def test_prepared_request_is_pickleable(self, httpbin):1220 p = requests.Request('GET', httpbin('get')).prepare()12211222 # Verify PreparedRequest can be pickled and unpickled1223 r = pickle.loads(pickle.dumps(p))1224 assert r.url == p.url1225 assert r.headers == p.headers1226 assert r.body == p.body12271228 # Verify unpickled PreparedRequest sends properly1229 s = requests.Session()1230 resp = s.send(r)1231 assert resp.status_code == 20012321233 def test_prepared_request_with_file_is_pickleable(self, httpbin):1234 files = {'file': open(__file__, 'rb')}1235 r = requests.Request('POST', httpbin('post'), files=files)1236 p = r.prepare()12371238 # Verify PreparedRequest can be pickled and unpickled1239 r = pickle.loads(pickle.dumps(p))1240 assert r.url == p.url1241 assert r.headers == p.headers1242 assert r.body == p.body12431244 # Verify unpickled PreparedRequest sends properly1245 s = requests.Session()1246 resp = s.send(r)1247 assert resp.status_code == 20012481249 def test_prepared_request_with_hook_is_pickleable(self, httpbin):1250 r = requests.Request('GET', httpbin('get'), hooks=default_hooks())1251 p = r.prepare()12521253 # Verify PreparedRequest can be pickled1254 r = pickle.loads(pickle.dumps(p))1255 assert r.url == p.url1256 assert r.headers == p.headers1257 assert r.body == p.body1258 assert r.hooks == p.hooks12591260 # Verify unpickled PreparedRequest sends properly1261 s = requests.Session()1262 resp = s.send(r)1263 assert resp.status_code == 20012641265 def test_cannot_send_unprepared_requests(self, httpbin):1266 r = requests.Request(url=httpbin())1267 with pytest.raises(ValueError):1268 requests.Session().send(r)12691270 def test_http_error(self):1271 error = requests.exceptions.HTTPError()1272 assert not error.response1273 response = requests.Response()1274 error = requests.exceptions.HTTPError(response=response)1275 assert error.response == response1276 error = requests.exceptions.HTTPError('message', response=response)1277 assert str(error) == 'message'1278 assert error.response == response12791280 def test_session_pickling(self, httpbin):1281 r = requests.Request('GET', httpbin('get'))1282 s = requests.Session()12831284 s = pickle.loads(pickle.dumps(s))1285 s.proxies = getproxies()12861287 r = s.send(r.prepare())1288 assert r.status_code == 20012891290 def test_fixes_1329(self, httpbin):1291 """Ensure that header updates are done case-insensitively."""1292 s = requests.Session()1293 s.headers.update({'ACCEPT': 'BOGUS'})1294 s.headers.update({'accept': 'application/json'})1295 r = s.get(httpbin('get'))1296 headers = r.request.headers1297 assert headers['accept'] == 'application/json'1298 assert headers['Accept'] == 'application/json'1299 assert headers['ACCEPT'] == 'application/json'13001301 def test_uppercase_scheme_redirect(self, httpbin):1302 parts = urlparse(httpbin('html'))1303 url = "HTTP://" + parts.netloc + parts.path1304 r = requests.get(httpbin('redirect-to'), params={'url': url})1305 assert r.status_code == 2001306 assert r.url.lower() == url.lower()13071308 def test_transport_adapter_ordering(self):1309 s = requests.Session()1310 order = ['https://', 'http://']1311 assert order == list(s.adapters)1312 s.mount('http://git', HTTPAdapter())1313 s.mount('http://github', HTTPAdapter())1314 s.mount('http://github.com', HTTPAdapter())1315 s.mount('http://github.com/about/', HTTPAdapter())1316 order = [1317 'http://github.com/about/',1318 'http://github.com',1319 'http://github',1320 'http://git',1321 'https://',1322 'http://',1323 ]1324 assert order == list(s.adapters)1325 s.mount('http://gittip', HTTPAdapter())1326 s.mount('http://gittip.com', HTTPAdapter())1327 s.mount('http://gittip.com/about/', HTTPAdapter())1328 order = [1329 'http://github.com/about/',1330 'http://gittip.com/about/',1331 'http://github.com',1332 'http://gittip.com',1333 'http://github',1334 'http://gittip',1335 'http://git',1336 'https://',1337 'http://',1338 ]1339 assert order == list(s.adapters)1340 s2 = requests.Session()1341 s2.adapters = {'http://': HTTPAdapter()}1342 s2.mount('https://', HTTPAdapter())1343 assert 'http://' in s2.adapters1344 assert 'https://' in s2.adapters13451346 def test_header_remove_is_case_insensitive(self, httpbin):1347 # From issue #13211348 s = requests.Session()1349 s.headers['foo'] = 'bar'1350 r = s.get(httpbin('get'), headers={'FOO': None})1351 assert 'foo' not in r.request.headers13521353 def test_params_are_merged_case_sensitive(self, httpbin):1354 s = requests.Session()1355 s.params['foo'] = 'bar'1356 r = s.get(httpbin('get'), params={'FOO': 'bar'})1357 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}13581359 def test_long_authinfo_in_url(self):1360 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(1361 'E8A3BE87-9E3F-4620-8858-95478E385B5B',1362 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1363 'exactly-------------sixty-----------three------------characters',1364 )1365 r = requests.Request('GET', url).prepare()1366 assert r.url == url13671368 def test_header_keys_are_native(self, httpbin):1369 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1370 r = requests.Request('GET', httpbin('get'), headers=headers)1371 p = r.prepare()13721373 # This is testing that they are builtin strings. A bit weird, but there1374 # we go.1375 assert 'unicode' in p.headers.keys()1376 assert 'byte' in p.headers.keys()13771378 def test_header_validation(self, httpbin):1379 """Ensure prepare_headers regex isn't flagging valid header contents."""1380 headers_ok = {'foo': 'bar baz qux',1381 'bar': u'fbbq'.encode('utf8'),1382 'baz': '',1383 'qux': '1'}1384 r = requests.get(httpbin('get'), headers=headers_ok)1385 assert r.request.headers['foo'] == headers_ok['foo']13861387 def test_header_value_not_str(self, httpbin):1388 """Ensure the header value is of type string or bytes as1389 per discussion in GH issue #33861390 """1391 headers_int = {'foo': 3}1392 headers_dict = {'bar': {'foo': 'bar'}}1393 headers_list = {'baz': ['foo', 'bar']}13941395 # Test for int1396 with pytest.raises(InvalidHeader):1397 r = requests.get(httpbin('get'), headers=headers_int)1398 # Test for dict1399 with pytest.raises(InvalidHeader):1400 r = requests.get(httpbin('get'), headers=headers_dict)1401 # Test for list1402 with pytest.raises(InvalidHeader):1403 r = requests.get(httpbin('get'), headers=headers_list)14041405 def test_header_no_return_chars(self, httpbin):1406 """Ensure that a header containing return character sequences raise an1407 exception. Otherwise, multiple headers are created from single string.1408 """1409 headers_ret = {'foo': 'bar\r\nbaz: qux'}1410 headers_lf = {'foo': 'bar\nbaz: qux'}1411 headers_cr = {'foo': 'bar\rbaz: qux'}14121413 # Test for newline1414 with pytest.raises(InvalidHeader):1415 r = requests.get(httpbin('get'), headers=headers_ret)1416 # Test for line feed1417 with pytest.raises(InvalidHeader):1418 r = requests.get(httpbin('get'), headers=headers_lf)1419 # Test for carriage return1420 with pytest.raises(InvalidHeader):1421 r = requests.get(httpbin('get'), headers=headers_cr)14221423 def test_header_no_leading_space(self, httpbin):1424 """Ensure headers containing leading whitespace raise1425 InvalidHeader Error before sending.1426 """1427 headers_space = {'foo': ' bar'}1428 headers_tab = {'foo': ' bar'}14291430 # Test for whitespace1431 with pytest.raises(InvalidHeader):1432 r = requests.get(httpbin('get'), headers=headers_space)1433 # Test for tab1434 with pytest.raises(InvalidHeader):1435 r = requests.get(httpbin('get'), headers=headers_tab)14361437 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1438 def test_can_send_objects_with_files(self, httpbin, files):1439 data = {'a': 'this is a string'}1440 files = {'b': files}1441 r = requests.Request('POST', httpbin('post'), data=data, files=files)1442 p = r.prepare()1443 assert 'multipart/form-data' in p.headers['Content-Type']14441445 def test_can_send_file_object_with_non_string_filename(self, httpbin):1446 f = io.BytesIO()1447 f.name = 21448 r = requests.Request('POST', httpbin('post'), files={'f': f})1449 p = r.prepare()14501451 assert 'multipart/form-data' in p.headers['Content-Type']14521453 def test_autoset_header_values_are_native(self, httpbin):1454 data = 'this is a string'1455 length = '16'1456 req = requests.Request('POST', httpbin('post'), data=data)1457 p = req.prepare()14581459 assert p.headers['Content-Length'] == length14601461 def test_nonhttp_schemes_dont_check_URLs(self):1462 test_urls = (1463 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1464 'file:///etc/passwd',1465 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1466 )1467 for test_url in test_urls:1468 req = requests.Request('GET', test_url)1469 preq = req.prepare()1470 assert test_url == preq.url14711472 @pytest.mark.xfail(raises=ConnectionError)1473 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1474 r = requests.get(1475 httpbin('redirect-to'),1476 params={'url': 'http://www.google.co.uk'},1477 auth=('user', 'pass'),1478 )1479 assert r.history[0].request.headers['Authorization']1480 assert not r.request.headers.get('Authorization', '')14811482 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1483 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1484 h1 = r.history[0].request.headers['Authorization']1485 h2 = r.request.headers['Authorization']14861487 assert h1 == h214881489 def test_manual_redirect_with_partial_body_read(self, httpbin):1490 s = requests.Session()1491 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1492 assert r1.is_redirect1493 rg = s.resolve_redirects(r1, r1.request, stream=True)14941495 # read only the first eight bytes of the response body,1496 # then follow the redirect1497 r1.iter_content(8)1498 r2 = next(rg)1499 assert r2.is_redirect15001501 # read all of the response via iter_content,1502 # then follow the redirect1503 for _ in r2.iter_content():1504 pass1505 r3 = next(rg)1506 assert not r3.is_redirect15071508 def test_prepare_body_position_non_stream(self):1509 data = b'the data'1510 s = requests.Session()1511 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1512 assert prep._body_position is None15131514 def test_rewind_body(self):1515 data = io.BytesIO(b'the data')1516 s = requests.Session()1517 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1518 assert prep._body_position == 01519 assert prep.body.read() == b'the data'15201521 # the data has all been read1522 assert prep.body.read() == b''15231524 # rewind it back1525 requests.utils.rewind_body(prep)1526 assert prep.body.read() == b'the data'15271528 def test_rewind_partially_read_body(self):1529 data = io.BytesIO(b'the data')1530 s = requests.Session()1531 data.read(4) # read some data1532 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1533 assert prep._body_position == 41534 assert prep.body.read() == b'data'15351536 # the data has all been read1537 assert prep.body.read() == b''15381539 # rewind it back1540 requests.utils.rewind_body(prep)1541 assert prep.body.read() == b'data'15421543 def test_rewind_body_no_seek(self):1544 class BadFileObj:1545 def __init__(self, data):1546 self.data = data15471548 def tell(self):1549 return 015501551 def __iter__(self):1552 return15531554 data = BadFileObj('the data')1555 s = requests.Session()1556 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1557 assert prep._body_position == 015581559 with pytest.raises(UnrewindableBodyError) as e:1560 requests.utils.rewind_body(prep)15611562 assert 'Unable to rewind request body' in str(e)15631564 def test_rewind_body_failed_seek(self):1565 class BadFileObj:1566 def __init__(self, data):1567 self.data = data15681569 def tell(self):1570 return 01571

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

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

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 1573–1585why, one step back
1573 raise OSError()
15741575 def __iter__(self):1576 return15771578 data = BadFileObj('the data')1579 s = requests.Session()1580 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1581 assert prep._body_position == 015821583 with pytest.raises(UnrewindableBodyError) as e:1584 requests.utils.rewind_body(prep)1585

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

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

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 1587–1628why, one step back
1587
1588 def test_rewind_body_failed_tell(self):1589 class BadFileObj:1590 def __init__(self, data):1591 self.data = data15921593 def tell(self):1594 raise OSError()15951596 def __iter__(self):1597 return15981599 data = BadFileObj('the data')1600 s = requests.Session()1601 prep = requests.Request('GET', 'http://example.com', data=data).prepare()1602 assert prep._body_position is not None16031604 with pytest.raises(UnrewindableBodyError) as e:1605 requests.utils.rewind_body(prep)16061607 assert 'Unable to rewind request body' in str(e)16081609 def _patch_adapter_gzipped_redirect(self, session, url):1610 adapter = session.get_adapter(url=url)1611 org_build_response = adapter.build_response1612 self._patched_response = False16131614 def build_response(*args, **kwargs):1615 resp = org_build_response(*args, **kwargs)1616 if not self._patched_response:1617 resp.raw.headers['content-encoding'] = 'gzip'1618 self._patched_response = True1619 return resp16201621 adapter.build_response = build_response16221623 def test_redirect_with_wrong_gzipped_header(self, httpbin):1624 s = requests.Session()1625 url = httpbin('redirect/1')1626 self._patch_adapter_gzipped_redirect(s, url)1627 s.get(url)1628

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

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

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

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

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

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

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 1638–1730why, one step back
1638
1639 def test_requests_history_is_saved(self, httpbin):1640 r = requests.get(httpbin('redirect/5'))1641 total = r.history[-1].history1642 i = 01643 for item in r.history:1644 assert item.history == total[0:i]1645 i += 116461647 def test_json_param_post_content_type_works(self, httpbin):1648 r = requests.post(1649 httpbin('post'),1650 json={'life': 42}1651 )1652 assert r.status_code == 2001653 assert 'application/json' in r.request.headers['Content-Type']1654 assert {'life': 42} == r.json()['json']16551656 def test_json_param_post_should_not_override_data_param(self, httpbin):1657 r = requests.Request(method='POST', url=httpbin('post'),1658 data={'stuff': 'elixr'},1659 json={'music': 'flute'})1660 prep = r.prepare()1661 assert 'stuff=elixr' == prep.body16621663 def test_response_iter_lines(self, httpbin):1664 r = requests.get(httpbin('stream/4'), stream=True)1665 assert r.status_code == 20016661667 it = r.iter_lines()1668 next(it)1669 assert len(list(it)) == 316701671 def test_unconsumed_session_response_closes_connection(self, httpbin):1672 s = requests.session()16731674 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1675 pass16761677 assert response._content_consumed is False1678 assert response.raw.closed16791680 @pytest.mark.xfail1681 def test_response_iter_lines_reentrant(self, httpbin):1682 """Response.iter_lines() is not reentrant safe"""1683 r = requests.get(httpbin('stream/4'), stream=True)1684 assert r.status_code == 20016851686 next(r.iter_lines())1687 assert len(list(r.iter_lines())) == 316881689 def test_session_close_proxy_clear(self, mocker):1690 proxies = {1691 'one': mocker.Mock(),1692 'two': mocker.Mock(),1693 }1694 session = requests.Session()1695 mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1696 session.close()1697 proxies['one'].clear.assert_called_once_with()1698 proxies['two'].clear.assert_called_once_with()16991700 def test_proxy_auth(self, httpbin):1701 adapter = HTTPAdapter()1702 headers = adapter.proxy_headers("http://user:pass@httpbin.org")1703 assert headers == {'Proxy-Authorization': 'Basic dXNlcjpwYXNz'}17041705 def test_proxy_auth_empty_pass(self, httpbin):1706 adapter = HTTPAdapter()1707 headers = adapter.proxy_headers("http://user:@httpbin.org")1708 assert headers == {'Proxy-Authorization': 'Basic dXNlcjo='}17091710 def test_response_json_when_content_is_None(self, httpbin):1711 r = requests.get(httpbin('/status/204'))1712 # Make sure r.content is None1713 r.status_code = 01714 r._content = False1715 r._content_consumed = False17161717 assert r.content is None1718 with pytest.raises(ValueError):1719 r.json()17201721 def test_response_without_release_conn(self):1722 """Test `close` call for non-urllib3-like raw objects.1723 Should work when `release_conn` attr doesn't exist on `response.raw`.1724 """1725 resp = requests.Response()1726 resp.raw = StringIO.StringIO('test')1727 assert not resp.raw.closed1728 resp.close()1729 assert resp.raw.closed1730

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

lines 1731–1765why, one step back
1731 def test_empty_stream_with_auth_does_not_set_content_length_header(self, httpbin):
1732 """Ensure that a byte stream with size 0 will not set both a Content-Length1733 and Transfer-Encoding header.1734 """1735 auth = ('user', 'pass')1736 url = httpbin('post')1737 file_obj = io.BytesIO(b'')1738 r = requests.Request('POST', url, auth=auth, data=file_obj)1739 prepared_request = r.prepare()1740 assert 'Transfer-Encoding' in prepared_request.headers1741 assert 'Content-Length' not in prepared_request.headers17421743 def test_stream_with_auth_does_not_set_transfer_encoding_header(self, httpbin):1744 """Ensure that a byte stream with size > 0 will not set both a Content-Length1745 and Transfer-Encoding header.1746 """1747 auth = ('user', 'pass')1748 url = httpbin('post')1749 file_obj = io.BytesIO(b'test data')1750 r = requests.Request('POST', url, auth=auth, data=file_obj)1751 prepared_request = r.prepare()1752 assert 'Transfer-Encoding' not in prepared_request.headers1753 assert 'Content-Length' in prepared_request.headers17541755 def test_chunked_upload_does_not_set_content_length_header(self, httpbin):1756 """Ensure that requests with a generator body stream using1757 Transfer-Encoding: chunked, not a Content-Length header.1758 """1759 data = (i for i in [b'a', b'b', b'c'])1760 url = httpbin('post')1761 r = requests.Request('POST', url, data=data)1762 prepared_request = r.prepare()1763 assert 'Transfer-Encoding' in prepared_request.headers1764 assert 'Content-Length' not in prepared_request.headers1765

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

lines 1766–1808why, one step back
1766 def test_custom_redirect_mixin(self, httpbin):
1767 """Tests a custom mixin to overwrite ``get_redirect_target``.17681769 Ensures a subclassed ``requests.Session`` can handle a certain type of1770 malformed redirect responses.17711772 1. original request receives a proper response: 302 redirect1773 2. following the redirect, a malformed response is given:1774 status code = HTTP 2001775 location = alternate url1776 3. the custom session catches the edge case and follows the redirect1777 """1778 url_final = httpbin('html')1779 querystring_malformed = urlencode({'location': url_final})1780 url_redirect_malformed = httpbin('response-headers?%s' % querystring_malformed)1781 querystring_redirect = urlencode({'url': url_redirect_malformed})1782 url_redirect = httpbin('redirect-to?%s' % querystring_redirect)1783 urls_test = [url_redirect,1784 url_redirect_malformed,1785 url_final,1786 ]17871788 class CustomRedirectSession(requests.Session):1789 def get_redirect_target(self, resp):1790 # default behavior1791 if resp.is_redirect:1792 return resp.headers['location']1793 # edge case - check to see if 'location' is in headers anyways1794 location = resp.headers.get('location')1795 if location and (location != resp.url):1796 return location1797 return None17981799 session = CustomRedirectSession()1800 r = session.get(urls_test[0])1801 assert len(r.history) == 21802 assert r.status_code == 2001803 assert r.history[0].status_code == 3021804 assert r.history[0].is_redirect1805 assert r.history[1].status_code == 2001806 assert not r.history[1].is_redirect1807 assert r.url == urls_test[2]1808

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

line 1809why, one step back
1809

Merge pull request #3679 from mlissner/patch-2Cory Benfieldbefore adoptione2408fc

lines 1810–2015why, one step back
1810class TestCaseInsensitiveDict:
18111812 @pytest.mark.parametrize(1813 'cid', (1814 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1815 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1816 CaseInsensitiveDict(FOO='foo', BAr='bar'),1817 ))1818 def test_init(self, cid):1819 assert len(cid) == 21820 assert 'foo' in cid1821 assert 'bar' in cid18221823 def test_docstring_example(self):1824 cid = CaseInsensitiveDict()1825 cid['Accept'] = 'application/json'1826 assert cid['aCCEPT'] == 'application/json'1827 assert list(cid) == ['Accept']18281829 def test_len(self):1830 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1831 cid['A'] = 'a'1832 assert len(cid) == 218331834 def test_getitem(self):1835 cid = CaseInsensitiveDict({'Spam': 'blueval'})1836 assert cid['spam'] == 'blueval'1837 assert cid['SPAM'] == 'blueval'18381839 def test_fixes_649(self):1840 """__setitem__ should behave case-insensitively."""1841 cid = CaseInsensitiveDict()1842 cid['spam'] = 'oneval'1843 cid['Spam'] = 'twoval'1844 cid['sPAM'] = 'redval'1845 cid['SPAM'] = 'blueval'1846 assert cid['spam'] == 'blueval'1847 assert cid['SPAM'] == 'blueval'1848 assert list(cid.keys()) == ['SPAM']18491850 def test_delitem(self):1851 cid = CaseInsensitiveDict()1852 cid['Spam'] = 'someval'1853 del cid['sPam']1854 assert 'spam' not in cid1855 assert len(cid) == 018561857 def test_contains(self):1858 cid = CaseInsensitiveDict()1859 cid['Spam'] = 'someval'1860 assert 'Spam' in cid1861 assert 'spam' in cid1862 assert 'SPAM' in cid1863 assert 'sPam' in cid1864 assert 'notspam' not in cid18651866 def test_get(self):1867 cid = CaseInsensitiveDict()1868 cid['spam'] = 'oneval'1869 cid['SPAM'] = 'blueval'1870 assert cid.get('spam') == 'blueval'1871 assert cid.get('SPAM') == 'blueval'1872 assert cid.get('sPam') == 'blueval'1873 assert cid.get('notspam', 'default') == 'default'18741875 def test_update(self):1876 cid = CaseInsensitiveDict()1877 cid['spam'] = 'blueval'1878 cid.update({'sPam': 'notblueval'})1879 assert cid['spam'] == 'notblueval'1880 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1881 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1882 assert len(cid) == 21883 assert cid['foo'] == 'anotherfoo'1884 assert cid['bar'] == 'anotherbar'18851886 def test_update_retains_unchanged(self):1887 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1888 cid.update({'foo': 'newfoo'})1889 assert cid['bar'] == 'bar'18901891 def test_iter(self):1892 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1893 keys = frozenset(['Spam', 'Eggs'])1894 assert frozenset(iter(cid)) == keys18951896 def test_equality(self):1897 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1898 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1899 assert cid == othercid1900 del othercid['spam']1901 assert cid != othercid1902 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1903 assert cid != object()19041905 def test_setdefault(self):1906 cid = CaseInsensitiveDict({'Spam': 'blueval'})1907 assert cid.setdefault('spam', 'notblueval') == 'blueval'1908 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'19091910 def test_lower_items(self):1911 cid = CaseInsensitiveDict({1912 'Accept': 'application/json',1913 'user-Agent': 'requests',1914 })1915 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1916 lowerkeyset = frozenset(['accept', 'user-agent'])1917 assert keyset == lowerkeyset19181919 def test_preserve_key_case(self):1920 cid = CaseInsensitiveDict({1921 'Accept': 'application/json',1922 'user-Agent': 'requests',1923 })1924 keyset = frozenset(['Accept', 'user-Agent'])1925 assert frozenset(i[0] for i in cid.items()) == keyset1926 assert frozenset(cid.keys()) == keyset1927 assert frozenset(cid) == keyset19281929 def test_preserve_last_key_case(self):1930 cid = CaseInsensitiveDict({1931 'Accept': 'application/json',1932 'user-Agent': 'requests',1933 })1934 cid.update({'ACCEPT': 'application/json'})1935 cid['USER-AGENT'] = 'requests'1936 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1937 assert frozenset(i[0] for i in cid.items()) == keyset1938 assert frozenset(cid.keys()) == keyset1939 assert frozenset(cid) == keyset19401941 def test_copy(self):1942 cid = CaseInsensitiveDict({1943 'Accept': 'application/json',1944 'user-Agent': 'requests',1945 })1946 cid_copy = cid.copy()1947 assert cid == cid_copy1948 cid['changed'] = True1949 assert cid != cid_copy195019511952class TestMorselToCookieExpires:1953 """Tests for morsel_to_cookie when morsel contains expires."""19541955 def test_expires_valid_str(self):1956 """Test case where we convert expires from string time."""19571958 morsel = Morsel()1959 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1960 cookie = morsel_to_cookie(morsel)1961 assert cookie.expires == 119621963 @pytest.mark.parametrize(1964 'value, exception', (1965 (100, TypeError),1966 ('woops', ValueError),1967 ))1968 def test_expires_invalid_int(self, value, exception):1969 """Test case where an invalid type is passed for expires."""1970 morsel = Morsel()1971 morsel['expires'] = value1972 with pytest.raises(exception):1973 morsel_to_cookie(morsel)19741975 def test_expires_none(self):1976 """Test case where expires is None."""19771978 morsel = Morsel()1979 morsel['expires'] = None1980 cookie = morsel_to_cookie(morsel)1981 assert cookie.expires is None198219831984class TestMorselToCookieMaxAge:19851986 """Tests for morsel_to_cookie when morsel contains max-age."""19871988 def test_max_age_valid_int(self):1989 """Test case where a valid max age in seconds is passed."""19901991 morsel = Morsel()1992 morsel['max-age'] = 601993 cookie = morsel_to_cookie(morsel)1994 assert isinstance(cookie.expires, int)19951996 def test_max_age_invalid_str(self):1997 """Test case where a invalid max age is passed."""19981999 morsel = Morsel()2000 morsel['max-age'] = 'woops'

The first 2,000 of 2,372 lines.