test_requests.py
This file
Path
tests/test_requests.py
1,627 lines · 55.0 KiB · Python
Last changed by
Merge pull request #3179 from messense/messense-patch-1Cory Benfieldbefore adoption8770410
History of this fileTake it
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import collections11import contextlib1213import io14import requests15import pytest16from requests.adapters import HTTPAdapter17from requests.auth import HTTPDigestAuth, _basic_auth_str18from requests.compat import (19 Morsel, cookielib, getproxies, str, urlparse,20 builtin_str, OrderedDict)21from requests.cookies import cookiejar_from_dict, morsel_to_cookie22from requests.exceptions import (23 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,24 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,25 ProxyError)26from requests.models import PreparedRequest27from requests.structures import CaseInsensitiveDict28from requests.sessions import SessionRedirectMixin29from requests.models import urlencode30from requests.hooks import default_hooks3132from .compat import StringIO, u3334# Requests to this URL should always fail with a connection timeout (nothing35# listening on that port)36TARPIT = 'http://10.255.255.1'373839class TestRequests:4041 def test_entry_points(self):4243 requests.session44 requests.session().get45 requests.session().head46 requests.get47 requests.head48 requests.put49 requests.patch50 requests.post5152 @pytest.mark.parametrize(53 'exception, url', (54 (MissingSchema, 'hiwpefhipowhefopw'),55 (InvalidSchema, 'localhost:3128'),56 (InvalidSchema, 'localhost.localdomain:3128/'),57 (InvalidSchema, '10.122.1.1:3128/'),58 (InvalidURL, 'http://'),59 ))60 def test_invalid_url(self, exception, url):61 with pytest.raises(exception):62 requests.get(url)6364 def test_basic_building(self):65 req = requests.Request()66 req.url = 'http://kennethreitz.org/'67 req.data = {'life': '42'}6869 pr = req.prepare()70 assert pr.url == req.url71 assert pr.body == 'life=42'7273 @pytest.mark.parametrize('method', ('GET', 'HEAD'))74 def test_no_content_length(self, httpbin, method):75 req = requests.Request(method, httpbin(method.lower())).prepare()76 assert 'Content-Length' not in req.headers7778 def test_override_content_length(self, httpbin):79 headers = {80 'Content-Length': 'not zero'81 }82 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()83 assert 'Content-Length' in r.headers84 assert r.headers['Content-Length'] == 'not zero'8586 def test_path_is_not_double_encoded(self):87 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()8889 assert request.path_url == '/get/test%20case'9091 @pytest.mark.parametrize(92 'url, expected', (93 ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),94 ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')95 ))96 def test_params_are_added_before_fragment(self, url, expected):97 request = requests.Request('GET', url, params={"a": "b"}).prepare()98 assert request.url == expected99100 def test_params_original_order_is_preserved_by_default(self):101 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))102 session = requests.Session()103 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)104 prep = session.prepare_request(request)105 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'106107 def test_params_bytes_are_encoded(self):108 request = requests.Request('GET', 'http://example.com',109 params=b'test=foo').prepare()110 assert request.url == 'http://example.com/?test=foo'111112 def test_binary_put(self):113 request = requests.Request('PUT', 'http://example.com',114 data=u"ööö".encode("utf-8")).prepare()115 assert isinstance(request.body, bytes)116117 @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))118 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):119 s = requests.Session()120 s.proxies = getproxies()121 parts = urlparse(httpbin('get'))122 url = scheme + parts.netloc + parts.path123 r = requests.Request('GET', url)124 r = s.send(r.prepare())125 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)126127 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):128 r = requests.Request('GET', httpbin('get'))129 s = requests.Session()130 s.proxies = getproxies()131132 r = s.send(r.prepare())133134 assert r.status_code == 200135136 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):137 r = requests.get(httpbin('redirect', '1'))138 assert r.status_code == 200139 assert r.history[0].status_code == 302140 assert r.history[0].is_redirect141142 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):143 try:144 requests.get(httpbin('relative-redirect', '50'))145 except TooManyRedirects as e:146 url = httpbin('relative-redirect', '20')147 assert e.request.url == url148 assert e.response.url == url149 assert len(e.response.history) == 30150 else:151 pytest.fail('Expected redirect to raise TooManyRedirects but it did not')152153 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):154 s = requests.session()155 s.max_redirects = 5156 try:157 s.get(httpbin('relative-redirect', '50'))158 except TooManyRedirects as e:159 url = httpbin('relative-redirect', '45')160 assert e.request.url == url161 assert e.response.url == url162 assert len(e.response.history) == 5163 else:164 pytest.fail('Expected custom max number of redirects to be respected but was not')165166 def test_http_301_changes_post_to_get(self, httpbin):167 r = requests.post(httpbin('status', '301'))168 assert r.status_code == 200169 assert r.request.method == 'GET'170 assert r.history[0].status_code == 301171 assert r.history[0].is_redirect172173 def test_http_301_doesnt_change_head_to_get(self, httpbin):174 r = requests.head(httpbin('status', '301'), allow_redirects=True)175 print(r.content)176 assert r.status_code == 200177 assert r.request.method == 'HEAD'178 assert r.history[0].status_code == 301179 assert r.history[0].is_redirect180181 def test_http_302_changes_post_to_get(self, httpbin):182 r = requests.post(httpbin('status', '302'))183 assert r.status_code == 200184 assert r.request.method == 'GET'185 assert r.history[0].status_code == 302186 assert r.history[0].is_redirect187188 def test_http_302_doesnt_change_head_to_get(self, httpbin):189 r = requests.head(httpbin('status', '302'), allow_redirects=True)190 assert r.status_code == 200191 assert r.request.method == 'HEAD'192 assert r.history[0].status_code == 302193 assert r.history[0].is_redirect194195 def test_http_303_changes_post_to_get(self, httpbin):196 r = requests.post(httpbin('status', '303'))197 assert r.status_code == 200198 assert r.request.method == 'GET'199 assert r.history[0].status_code == 303200 assert r.history[0].is_redirect201202 def test_http_303_doesnt_change_head_to_get(self, httpbin):203 r = requests.head(httpbin('status', '303'), allow_redirects=True)204 assert r.status_code == 200205 assert r.request.method == 'HEAD'206 assert r.history[0].status_code == 303207 assert r.history[0].is_redirect208209 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):210 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})211 # self.assertEqual(r.status_code, 200)212213 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):214 heads = {'User-agent': 'Mozilla/5.0'}215216 r = requests.get(httpbin('user-agent'), headers=heads)217218 assert heads['User-agent'] in r.text219 assert r.status_code == 200220221 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):222 heads = {'User-agent': 'Mozilla/5.0'}223224 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)225 assert r.status_code == 200226227 def test_set_cookie_on_301(self, httpbin):228 s = requests.session()229 url = httpbin('cookies/set?foo=bar')230 s.get(url)231 assert s.cookies['foo'] == 'bar'232233 def test_cookie_sent_on_redirect(self, httpbin):234 s = requests.session()235 s.get(httpbin('cookies/set?foo=bar'))236 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')237 assert 'Cookie' in r.json()['headers']238239 def test_cookie_removed_on_expire(self, httpbin):240 s = requests.session()241 s.get(httpbin('cookies/set?foo=bar'))242 assert s.cookies['foo'] == 'bar'243 s.get(244 httpbin('response-headers'),245 params={246 'Set-Cookie':247 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'248 }249 )250 assert 'foo' not in s.cookies251252 def test_cookie_quote_wrapped(self, httpbin):253 s = requests.session()254 s.get(httpbin('cookies/set?foo="bar:baz"'))255 assert s.cookies['foo'] == '"bar:baz"'256257 def test_cookie_persists_via_api(self, httpbin):258 s = requests.session()259 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})260 assert 'foo' in r.request.headers['Cookie']261 assert 'foo' in r.history[0].request.headers['Cookie']262263 def test_request_cookie_overrides_session_cookie(self, httpbin):264 s = requests.session()265 s.cookies['foo'] = 'bar'266 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})267 assert r.json()['cookies']['foo'] == 'baz'268 # Session cookie should not be modified269 assert s.cookies['foo'] == 'bar'270271 def test_request_cookies_not_persisted(self, httpbin):272 s = requests.session()273 s.get(httpbin('cookies'), cookies={'foo': 'baz'})274 # Sending a request with cookies should not add cookies to the session275 assert not s.cookies276277 def test_generic_cookiejar_works(self, httpbin):278 cj = cookielib.CookieJar()279 cookiejar_from_dict({'foo': 'bar'}, cj)280 s = requests.session()281 s.cookies = cj282 r = s.get(httpbin('cookies'))283 # Make sure the cookie was sent284 assert r.json()['cookies']['foo'] == 'bar'285 # Make sure the session cj is still the custom one286 assert s.cookies is cj287288 def test_param_cookiejar_works(self, httpbin):289 cj = cookielib.CookieJar()290 cookiejar_from_dict({'foo': 'bar'}, cj)291 s = requests.session()292 r = s.get(httpbin('cookies'), cookies=cj)293 # Make sure the cookie was sent294 assert r.json()['cookies']['foo'] == 'bar'295296 def test_requests_in_history_are_not_overridden(self, httpbin):297 resp = requests.get(httpbin('redirect/3'))298 urls = [r.url for r in resp.history]299 req_urls = [r.request.url for r in resp.history]300 assert urls == req_urls301302 def test_history_is_always_a_list(self, httpbin):303 """Show that even with redirects, Response.history is always a list."""304 resp = requests.get(httpbin('get'))305 assert isinstance(resp.history, list)306 resp = requests.get(httpbin('redirect/1'))307 assert isinstance(resp.history, list)308 assert not isinstance(resp.history, tuple)309310 def test_headers_on_session_with_None_are_not_sent(self, httpbin):311 """Do not send headers in Session.headers with None values."""312 ses = requests.Session()313 ses.headers['Accept-Encoding'] = None314 req = requests.Request('GET', httpbin('get'))315 prep = ses.prepare_request(req)316 assert 'Accept-Encoding' not in prep.headers317318 def test_headers_preserve_order(self, httpbin):319 """Preserve order when headers provided as OrderedDict."""320 ses = requests.Session()321 ses.headers = OrderedDict()322 ses.headers['Accept-Encoding'] = 'identity'323 ses.headers['First'] = '1'324 ses.headers['Second'] = '2'325 headers = OrderedDict([('Third', '3'), ('Fourth', '4')])326 headers['Fifth'] = '5'327 headers['Second'] = '222'328 req = requests.Request('GET', httpbin('get'), headers=headers)329 prep = ses.prepare_request(req)330 items = list(prep.headers.items())331 assert items[0] == ('Accept-Encoding', 'identity')332 assert items[1] == ('First', '1')333 assert items[2] == ('Second', '222')334 assert items[3] == ('Third', '3')335 assert items[4] == ('Fourth', '4')336 assert items[5] == ('Fifth', '5')337338 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))339 def test_user_agent_transfers(self, httpbin, key):340341 heads = {key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'}342343 r = requests.get(httpbin('user-agent'), headers=heads)344 assert heads[key] in r.text345346 def test_HTTP_200_OK_HEAD(self, httpbin):347 r = requests.head(httpbin('get'))348 assert r.status_code == 200349350 def test_HTTP_200_OK_PUT(self, httpbin):351 r = requests.put(httpbin('put'))352 assert r.status_code == 200353354 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):355 auth = ('user', 'pass')356 url = httpbin('basic-auth', 'user', 'pass')357358 r = requests.get(url, auth=auth)359 assert r.status_code == 200360361 r = requests.get(url)362 assert r.status_code == 401363364 s = requests.session()365 s.auth = auth366 r = s.get(url)367 assert r.status_code == 200368369 @pytest.mark.parametrize(370 'url, exception', (371 # Connecting to an unknown domain should raise a ConnectionError372 ('http://doesnotexist.google.com', ConnectionError),373 # Connecting to an invalid port should raise a ConnectionError374 ('http://localhost:1', ConnectionError),375 # Inputing a URL that cannot be parsed should raise an InvalidURL error376 ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)377 ))378 def test_errors(self, url, exception):379 with pytest.raises(exception):380 requests.get(url, timeout=1)381382 def test_proxy_error(self):383 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError384 with pytest.raises(ProxyError):385 requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})386387 def test_basicauth_with_netrc(self, httpbin):388 auth = ('user', 'pass')389 wrong_auth = ('wronguser', 'wrongpass')390 url = httpbin('basic-auth', 'user', 'pass')391392 old_auth = requests.sessions.get_netrc_auth393394 try:395 def get_netrc_auth_mock(url):396 return auth397 requests.sessions.get_netrc_auth = get_netrc_auth_mock398399 # Should use netrc and work.400 r = requests.get(url)401 assert r.status_code == 200402403 # Given auth should override and fail.404 r = requests.get(url, auth=wrong_auth)405 assert r.status_code == 401406407 s = requests.session()408409 # Should use netrc and work.410 r = s.get(url)411 assert r.status_code == 200412413 # Given auth should override and fail.414 s.auth = wrong_auth415 r = s.get(url)416 assert r.status_code == 401417 finally:418 requests.sessions.get_netrc_auth = old_auth419420 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):421422 auth = HTTPDigestAuth('user', 'pass')423 url = httpbin('digest-auth', 'auth', 'user', 'pass')424425 r = requests.get(url, auth=auth)426 assert r.status_code == 200427428 r = requests.get(url)429 assert r.status_code == 401430431 s = requests.session()432 s.auth = HTTPDigestAuth('user', 'pass')433 r = s.get(url)434 assert r.status_code == 200435436 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):437 url = httpbin('digest-auth', 'auth', 'user', 'pass')438 auth = HTTPDigestAuth('user', 'pass')439 r = requests.get(url)440 assert r.cookies['fake'] == 'fake_value'441442 r = requests.get(url, auth=auth)443 assert r.status_code == 200444445 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):446 url = httpbin('digest-auth', 'auth', 'user', 'pass')447 auth = HTTPDigestAuth('user', 'pass')448 s = requests.Session()449 s.get(url, auth=auth)450 assert s.cookies['fake'] == 'fake_value'451452 def test_DIGEST_STREAM(self, httpbin):453454 auth = HTTPDigestAuth('user', 'pass')455 url = httpbin('digest-auth', 'auth', 'user', 'pass')456457 r = requests.get(url, auth=auth, stream=True)458 assert r.raw.read() != b''459460 r = requests.get(url, auth=auth, stream=False)461 assert r.raw.read() == b''462463 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):464465 auth = HTTPDigestAuth('user', 'wrongpass')466 url = httpbin('digest-auth', 'auth', 'user', 'pass')467468 r = requests.get(url, auth=auth)469 assert r.status_code == 401470471 r = requests.get(url)472 assert r.status_code == 401473474 s = requests.session()475 s.auth = auth476 r = s.get(url)477 assert r.status_code == 401478479 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):480481 auth = HTTPDigestAuth('user', 'pass')482 url = httpbin('digest-auth', 'auth', 'user', 'pass')483484 r = requests.get(url, auth=auth)485 assert '"auth"' in r.request.headers['Authorization']486487 def test_POSTBIN_GET_POST_FILES(self, httpbin):488489 url = httpbin('post')490 requests.post(url).raise_for_status()491492 post1 = requests.post(url, data={'some': 'data'})493 assert post1.status_code == 200494495 with open('requirements.txt') as f:496 post2 = requests.post(url, files={'some': f})497 assert post2.status_code == 200498499 post4 = requests.post(url, data='[{"some": "json"}]')500 assert post4.status_code == 200501502 with pytest.raises(ValueError):503 requests.post(url, files=['bad file data'])504505 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):506507 class TestStream(object):508 def __init__(self, data):509 self.data = data.encode()510 self.length = len(self.data)511 self.index = 0512513 def __len__(self):514 return self.length515516 def read(self, size=None):517 if size:518 ret = self.data[self.index:self.index + size]519 self.index += size520 else:521 ret = self.data[self.index:]522 self.index = self.length523 return ret524525 def tell(self):526 return self.index527528 def seek(self, offset, where=0):529 if where == 0:530 self.index = offset531 elif where == 1:532 self.index += offset533 elif where == 2:534 self.index = self.length + offset535536 test = TestStream('test')537 post1 = requests.post(httpbin('post'), data=test)538 assert post1.status_code == 200539 assert post1.json()['data'] == 'test'540541 test = TestStream('test')542 test.seek(2)543 post2 = requests.post(httpbin('post'), data=test)544 assert post2.status_code == 200545 assert post2.json()['data'] == 'st'546547 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):548549 url = httpbin('post')550 requests.post(url).raise_for_status()551552 post1 = requests.post(url, data={'some': 'data'})553 assert post1.status_code == 200554555 with open('requirements.txt') as f:556 post2 = requests.post(url,557 data={'some': 'data'}, files={'some': f})558 assert post2.status_code == 200559560 post4 = requests.post(url, data='[{"some": "json"}]')561 assert post4.status_code == 200562563 with pytest.raises(ValueError):564 requests.post(url, files=['bad file data'])565566 def test_conflicting_post_params(self, httpbin):567 url = httpbin('post')568 with open('requirements.txt') as f:569 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")570 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")571572 def test_request_ok_set(self, httpbin):573 r = requests.get(httpbin('status', '404'))574 assert not r.ok575576 def test_status_raising(self, httpbin):577 r = requests.get(httpbin('status', '404'))578 with pytest.raises(requests.exceptions.HTTPError):579 r.raise_for_status()580581 r = requests.get(httpbin('status', '500'))582 assert not r.ok583584 def test_decompress_gzip(self, httpbin):585 r = requests.get(httpbin('gzip'))586 r.content.decode('ascii')587588 @pytest.mark.parametrize(589 'url, params', (590 ('/get', {'foo': 'føø'}),591 ('/get', {'føø': 'føø'}),592 ('/get', {'føø': 'føø'}),593 ('/get', {'foo': 'foo'}),594 ('ø', {'foo': 'foo'}),595 ))596 def test_unicode_get(self, httpbin, url, params):597 requests.get(httpbin(url), params=params)598599 def test_unicode_header_name(self, httpbin):600 requests.put(601 httpbin('put'),602 headers={str('Content-Type'): 'application/octet-stream'},603 data='\xff') # compat.str is unicode.604605 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):606 requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)607608 def test_urlencoded_get_query_multivalued_param(self, httpbin):609610 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))611 assert r.status_code == 200612 assert r.url == httpbin('get?test=foo&test=baz')613614 def test_different_encodings_dont_break_post(self, httpbin):615 r = requests.post(httpbin('post'),616 data={'stuff': json.dumps({'a': 123})},617 params={'blah': 'asdf1234'},618 files={'file': ('test_requests.py', open(__file__, 'rb'))})619 assert r.status_code == 200620621 @pytest.mark.parametrize(622 'data', (623 {'stuff': u('ëlïxr')},624 {'stuff': u('ëlïxr').encode('utf-8')},625 {'stuff': 'elixr'},626 {'stuff': 'elixr'.encode('utf-8')},627 ))628 def test_unicode_multipart_post(self, httpbin, data):629 r = requests.post(httpbin('post'),630 data=data,631 files={'file': ('test_requests.py', open(__file__, 'rb'))})632 assert r.status_code == 200633634 def test_unicode_multipart_post_fieldnames(self, httpbin):635 filename = os.path.splitext(__file__)[0] + '.py'636 r = requests.Request(637 method='POST', url=httpbin('post'),638 data={'stuff'.encode('utf-8'): 'elixr'},639 files={'file': ('test_requests.py', open(filename, 'rb'))})640 prep = r.prepare()641 assert b'name="stuff"' in prep.body642 assert b'name="b\'stuff\'"' not in prep.body643644 def test_unicode_method_name(self, httpbin):645 files = {'file': open(__file__, 'rb')}646 r = requests.request(647 method=u('POST'), url=httpbin('post'), files=files)648 assert r.status_code == 200649650 def test_unicode_method_name_with_request_object(self, httpbin):651 files = {'file': open(__file__, 'rb')}652 s = requests.Session()653 req = requests.Request(u('POST'), httpbin('post'), files=files)654 prep = s.prepare_request(req)655 assert isinstance(prep.method, builtin_str)656 assert prep.method == 'POST'657658 resp = s.send(prep)659 assert resp.status_code == 200660661 def test_non_prepared_request_error(self):662 s = requests.Session()663 req = requests.Request(u('POST'), '/')664665 with pytest.raises(ValueError) as e:666 s.send(req)667 assert str(e.value) == 'You can only send PreparedRequests.'668669 def test_custom_content_type(self, httpbin):670 r = requests.post(671 httpbin('post'),672 data={'stuff': json.dumps({'a': 123})},673 files={674 'file1': ('test_requests.py', open(__file__, 'rb')),675 'file2': ('test_requests', open(__file__, 'rb'),676 'text/py-content-type')})677 assert r.status_code == 200678 assert b"text/py-content-type" in r.request.body679680 def test_hook_receives_request_arguments(self, httpbin):681 def hook(resp, **kwargs):682 assert resp is not None683 assert kwargs != {}684685 s = requests.Session()686 r = requests.Request('GET', httpbin(), hooks={'response': hook})687 prep = s.prepare_request(r)688 s.send(prep)689690 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):691 hook = lambda x, *args, **kwargs: x692 s = requests.Session()693 s.hooks['response'].append(hook)694 r = requests.Request('GET', httpbin())695 prep = s.prepare_request(r)696 assert prep.hooks['response'] != []697 assert prep.hooks['response'] == [hook]698699 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):700 hook1 = lambda x, *args, **kwargs: x701 hook2 = lambda x, *args, **kwargs: x702 assert hook1 is not hook2703 s = requests.Session()704 s.hooks['response'].append(hook2)705 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})706 prep = s.prepare_request(r)707 assert prep.hooks['response'] == [hook1]708709 def test_prepared_request_hook(self, httpbin):710 def hook(resp, **kwargs):711 resp.hook_working = True712 return resp713714 req = requests.Request('GET', httpbin(), hooks={'response': hook})715 prep = req.prepare()716717 s = requests.Session()718 s.proxies = getproxies()719 resp = s.send(prep)720721 assert hasattr(resp, 'hook_working')722723 def test_prepared_from_session(self, httpbin):724 class DummyAuth(requests.auth.AuthBase):725 def __call__(self, r):726 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'727 return r728729 req = requests.Request('GET', httpbin('headers'))730 assert not req.auth731732 s = requests.Session()733 s.auth = DummyAuth()734735 prep = s.prepare_request(req)736 resp = s.send(prep)737738 assert resp.json()['headers'][739 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'740741 def test_prepare_request_with_bytestring_url(self):742 req = requests.Request('GET', b'https://httpbin.org/')743 s = requests.Session()744 prep = s.prepare_request(req)745 assert prep.url == "https://httpbin.org/"746747 def test_links(self):748 r = requests.Response()749 r.headers = {750 'cache-control': 'public, max-age=60, s-maxage=60',751 'connection': 'keep-alive',752 'content-encoding': 'gzip',753 'content-type': 'application/json; charset=utf-8',754 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',755 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',756 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',757 'link': ('<https://api.github.com/users/kennethreitz/repos?'758 'page=2&per_page=10>; rel="next", <https://api.github.'759 'com/users/kennethreitz/repos?page=7&per_page=10>; '760 ' rel="last"'),761 'server': 'GitHub.com',762 'status': '200 OK',763 'vary': 'Accept',764 'x-content-type-options': 'nosniff',765 'x-github-media-type': 'github.beta',766 'x-ratelimit-limit': '60',767 'x-ratelimit-remaining': '57'768 }769 assert r.links['next']['rel'] == 'next'770771 def test_cookie_parameters(self):772 key = 'some_cookie'773 value = 'some_value'774 secure = True775 domain = 'test.com'776 rest = {'HttpOnly': True}777778 jar = requests.cookies.RequestsCookieJar()779 jar.set(key, value, secure=secure, domain=domain, rest=rest)780781 assert len(jar) == 1782 assert 'some_cookie' in jar783784 cookie = list(jar)[0]785 assert cookie.secure == secure786 assert cookie.domain == domain787 assert cookie._rest['HttpOnly'] == rest['HttpOnly']788789 def test_cookie_as_dict_keeps_len(self):790 key = 'some_cookie'791 value = 'some_value'792793 key1 = 'some_cookie1'794 value1 = 'some_value1'795796 jar = requests.cookies.RequestsCookieJar()797 jar.set(key, value)798 jar.set(key1, value1)799800 d1 = dict(jar)801 d2 = dict(jar.iteritems())802 d3 = dict(jar.items())803804 assert len(jar) == 2805 assert len(d1) == 2806 assert len(d2) == 2807 assert len(d3) == 2808809 def test_cookie_as_dict_keeps_items(self):810 key = 'some_cookie'811 value = 'some_value'812813 key1 = 'some_cookie1'814 value1 = 'some_value1'815816 jar = requests.cookies.RequestsCookieJar()817 jar.set(key, value)818 jar.set(key1, value1)819820 d1 = dict(jar)821 d2 = dict(jar.iteritems())822 d3 = dict(jar.items())823824 assert d1['some_cookie'] == 'some_value'825 assert d2['some_cookie'] == 'some_value'826 assert d3['some_cookie1'] == 'some_value1'827828 def test_cookie_as_dict_keys(self):829 key = 'some_cookie'830 value = 'some_value'831832 key1 = 'some_cookie1'833 value1 = 'some_value1'834835 jar = requests.cookies.RequestsCookieJar()836 jar.set(key, value)837 jar.set(key1, value1)838839 keys = jar.keys()840 assert keys == list(keys)841 # make sure one can use keys multiple times842 assert list(keys) == list(keys)843844 def test_cookie_as_dict_values(self):845 key = 'some_cookie'846 value = 'some_value'847848 key1 = 'some_cookie1'849 value1 = 'some_value1'850851 jar = requests.cookies.RequestsCookieJar()852 jar.set(key, value)853 jar.set(key1, value1)854855 values = jar.values()856 assert values == list(values)857 # make sure one can use values multiple times858 assert list(values) == list(values)859860 def test_cookie_as_dict_items(self):861 key = 'some_cookie'862 value = 'some_value'863864 key1 = 'some_cookie1'865 value1 = 'some_value1'866867 jar = requests.cookies.RequestsCookieJar()868 jar.set(key, value)869 jar.set(key1, value1)870871 items = jar.items()872 assert items == list(items)873 # make sure one can use items multiple times874 assert list(items) == list(items)875876 def test_cookie_duplicate_names_different_domains(self):877 key = 'some_cookie'878 value = 'some_value'879 domain1 = 'test1.com'880 domain2 = 'test2.com'881882 jar = requests.cookies.RequestsCookieJar()883 jar.set(key, value, domain=domain1)884 jar.set(key, value, domain=domain2)885 assert key in jar886 items = jar.items()887 assert len(items) == 2888889 # Verify that CookieConflictError is raised if domain is not specified890 with pytest.raises(requests.cookies.CookieConflictError):891 jar.get(key)892893 # Verify that CookieConflictError is not raised if domain is specified894 cookie = jar.get(key, domain=domain1)895 assert cookie == value896897 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):898 key = 'some_cookie'899 value = 'some_value'900 path = 'some_path'901902 jar = requests.cookies.RequestsCookieJar()903 jar.set(key, value, path=path)904 jar.set(key, value)905 with pytest.raises(requests.cookies.CookieConflictError):906 jar.get(key)907908 def test_time_elapsed_blank(self, httpbin):909 r = requests.get(httpbin('get'))910 td = r.elapsed911 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)912 * 10**6) / 10**6)913 assert total_seconds > 0.0914915 def test_response_is_iterable(self):916 r = requests.Response()917 io = StringIO.StringIO('abc')918 read_ = io.read919920 def read_mock(amt, decode_content=None):921 return read_(amt)922 setattr(io, 'read', read_mock)923 r.raw = io924 assert next(iter(r))925 io.close()926927 def test_response_decode_unicode(self):928 """929 When called with decode_unicode, Response.iter_content should always930 return unicode.931 """932 r = requests.Response()933 r._content_consumed = True934 r._content = b'the content'935 r.encoding = 'ascii'936937 chunks = r.iter_content(decode_unicode=True)938 assert all(isinstance(chunk, str) for chunk in chunks)939940 # also for streaming941 r = requests.Response()942 r.raw = io.BytesIO(b'the content')943 r.encoding = 'ascii'944 chunks = r.iter_content(decode_unicode=True)945 assert all(isinstance(chunk, str) for chunk in chunks)946947 def test_request_and_response_are_pickleable(self, httpbin):948 r = requests.get(httpbin('get'))949950 # verify we can pickle the original request951 assert pickle.loads(pickle.dumps(r.request))952953 # verify we can pickle the response and that we have access to954 # the original request.955 pr = pickle.loads(pickle.dumps(r))956 assert r.request.url == pr.request.url957 assert r.request.headers == pr.request.headers958959 def test_cannot_send_unprepared_requests(self, httpbin):960 r = requests.Request(url=httpbin())961 with pytest.raises(ValueError):962 requests.Session().send(r)963964 def test_http_error(self):965 error = requests.exceptions.HTTPError()966 assert not error.response967 response = requests.Response()968 error = requests.exceptions.HTTPError(response=response)969 assert error.response == response970 error = requests.exceptions.HTTPError('message', response=response)971 assert str(error) == 'message'972 assert error.response == response973974 def test_session_pickling(self, httpbin):975 r = requests.Request('GET', httpbin('get'))976 s = requests.Session()977978 s = pickle.loads(pickle.dumps(s))979 s.proxies = getproxies()980981 r = s.send(r.prepare())982 assert r.status_code == 200983984 def test_fixes_1329(self, httpbin):985 """986 Ensure that header updates are done case-insensitively.987 """988 s = requests.Session()989 s.headers.update({'ACCEPT': 'BOGUS'})990 s.headers.update({'accept': 'application/json'})991 r = s.get(httpbin('get'))992 headers = r.request.headers993 assert headers['accept'] == 'application/json'994 assert headers['Accept'] == 'application/json'995 assert headers['ACCEPT'] == 'application/json'996997 def test_uppercase_scheme_redirect(self, httpbin):998 parts = urlparse(httpbin('html'))999 url = "HTTP://" + parts.netloc + parts.path1000 r = requests.get(httpbin('redirect-to'), params={'url': url})1001 assert r.status_code == 2001002 assert r.url.lower() == url.lower()10031004 def test_transport_adapter_ordering(self):1005 s = requests.Session()1006 order = ['https://', 'http://']1007 assert order == list(s.adapters)1008 s.mount('http://git', HTTPAdapter())1009 s.mount('http://github', HTTPAdapter())1010 s.mount('http://github.com', HTTPAdapter())1011 s.mount('http://github.com/about/', HTTPAdapter())1012 order = [1013 'http://github.com/about/',1014 'http://github.com',1015 'http://github',1016 'http://git',1017 'https://',1018 'http://',1019 ]1020 assert order == list(s.adapters)1021 s.mount('http://gittip', HTTPAdapter())1022 s.mount('http://gittip.com', HTTPAdapter())1023 s.mount('http://gittip.com/about/', HTTPAdapter())1024 order = [1025 'http://github.com/about/',1026 'http://gittip.com/about/',1027 'http://github.com',1028 'http://gittip.com',1029 'http://github',1030 'http://gittip',1031 'http://git',1032 'https://',1033 'http://',1034 ]1035 assert order == list(s.adapters)1036 s2 = requests.Session()1037 s2.adapters = {'http://': HTTPAdapter()}1038 s2.mount('https://', HTTPAdapter())1039 assert 'http://' in s2.adapters1040 assert 'https://' in s2.adapters10411042 def test_header_remove_is_case_insensitive(self, httpbin):1043 # From issue #13211044 s = requests.Session()1045 s.headers['foo'] = 'bar'1046 r = s.get(httpbin('get'), headers={'FOO': None})1047 assert 'foo' not in r.request.headers10481049 def test_params_are_merged_case_sensitive(self, httpbin):1050 s = requests.Session()1051 s.params['foo'] = 'bar'1052 r = s.get(httpbin('get'), params={'FOO': 'bar'})1053 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}10541055 def test_long_authinfo_in_url(self):1056 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(1057 'E8A3BE87-9E3F-4620-8858-95478E385B5B',1058 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1059 'exactly-------------sixty-----------three------------characters',1060 )1061 r = requests.Request('GET', url).prepare()1062 assert r.url == url10631064 def test_header_keys_are_native(self, httpbin):1065 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1066 r = requests.Request('GET', httpbin('get'), headers=headers)1067 p = r.prepare()10681069 # This is testing that they are builtin strings. A bit weird, but there1070 # we go.1071 assert 'unicode' in p.headers.keys()1072 assert 'byte' in p.headers.keys()10731074 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1075 def test_can_send_objects_with_files(self, httpbin, files):1076 data = {'a': 'this is a string'}1077 files = {'b': files}1078 r = requests.Request('POST', httpbin('post'), data=data, files=files)1079 p = r.prepare()1080 assert 'multipart/form-data' in p.headers['Content-Type']10811082 def test_can_send_file_object_with_non_string_filename(self, httpbin):1083 f = io.BytesIO()1084 f.name = 21085 r = requests.Request('POST', httpbin('post'), files={'f': f})1086 p = r.prepare()10871088 assert 'multipart/form-data' in p.headers['Content-Type']10891090 def test_autoset_header_values_are_native(self, httpbin):1091 data = 'this is a string'1092 length = '16'1093 req = requests.Request('POST', httpbin('post'), data=data)1094 p = req.prepare()10951096 assert p.headers['Content-Length'] == length10971098 def test_nonhttp_schemes_dont_check_URLs(self):1099 test_urls = (1100 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1101 'file:///etc/passwd',1102 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1103 )1104 for test_url in test_urls:1105 req = requests.Request('GET', test_url)1106 preq = req.prepare()1107 assert test_url == preq.url11081109 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1110 r = requests.get(1111 httpbin('redirect-to'),1112 params={'url': 'http://www.google.co.uk'},1113 auth=('user', 'pass'),1114 )1115 assert r.history[0].request.headers['Authorization']1116 assert not r.request.headers.get('Authorization', '')11171118 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1119 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1120 h1 = r.history[0].request.headers['Authorization']1121 h2 = r.request.headers['Authorization']11221123 assert h1 == h211241125 def test_manual_redirect_with_partial_body_read(self, httpbin):1126 s = requests.Session()1127 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1128 assert r1.is_redirect1129 rg = s.resolve_redirects(r1, r1.request, stream=True)11301131 # read only the first eight bytes of the response body,1132 # then follow the redirect1133 r1.iter_content(8)1134 r2 = next(rg)1135 assert r2.is_redirect11361137 # read all of the response via iter_content,1138 # then follow the redirect1139 for _ in r2.iter_content():1140 pass1141 r3 = next(rg)1142 assert not r3.is_redirect11431144 def _patch_adapter_gzipped_redirect(self, session, url):1145 adapter = session.get_adapter(url=url)1146 org_build_response = adapter.build_response1147 self._patched_response = False11481149 def build_response(*args, **kwargs):1150 resp = org_build_response(*args, **kwargs)1151 if not self._patched_response:1152 resp.raw.headers['content-encoding'] = 'gzip'1153 self._patched_response = True1154 return resp11551156 adapter.build_response = build_response11571158 def test_redirect_with_wrong_gzipped_header(self, httpbin):1159 s = requests.Session()1160 url = httpbin('redirect/1')1161 self._patch_adapter_gzipped_redirect(s, url)1162 s.get(url)11631164 def test_basic_auth_str_is_always_native(self):1165 s = _basic_auth_str("test", "test")1166 assert isinstance(s, builtin_str)1167 assert s == "Basic dGVzdDp0ZXN0"11681169 def test_requests_history_is_saved(self, httpbin):1170 r = requests.get(httpbin('redirect/5'))1171 total = r.history[-1].history1172 i = 01173 for item in r.history:1174 assert item.history == total[0:i]1175 i += 111761177 def test_json_param_post_content_type_works(self, httpbin):1178 r = requests.post(1179 httpbin('post'),1180 json={'life': 42}1181 )1182 assert r.status_code == 2001183 assert 'application/json' in r.request.headers['Content-Type']1184 assert {'life': 42} == r.json()['json']11851186 def test_json_param_post_should_not_override_data_param(self, httpbin):1187 r = requests.Request(method='POST', url=httpbin('post'),1188 data={'stuff': 'elixr'},1189 json={'music': 'flute'})1190 prep = r.prepare()1191 assert 'stuff=elixr' == prep.body11921193 def test_response_iter_lines(self, httpbin):1194 r = requests.get(httpbin('stream/4'), stream=True)1195 assert r.status_code == 20011961197 it = r.iter_lines()1198 next(it)1199 assert len(list(it)) == 312001201 def test_unconsumed_session_response_closes_connection(self, httpbin):1202 s = requests.session()12031204 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1205 pass12061207 assert response._content_consumed is False1208 assert response.raw.closed12091210 @pytest.mark.xfail1211 def test_response_iter_lines_reentrant(self, httpbin):1212 """Response.iter_lines() is not reentrant safe"""1213 r = requests.get(httpbin('stream/4'), stream=True)1214 assert r.status_code == 20012151216 next(r.iter_lines())1217 assert len(list(r.iter_lines())) == 312181219 def test_session_close_proxy_clear(self, mocker):1220 proxies = {1221 'one': mocker.Mock(),1222 'two': mocker.Mock(),1223 }1224 session = requests.Session()1225 mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1226 session.close()1227 proxies['one'].clear.assert_called_once_with()1228 proxies['two'].clear.assert_called_once_with()12291230 def test_response_json_when_content_is_None(self, httpbin):1231 r = requests.get(httpbin('/status/204'))1232 # Make sure r.content is None1233 r.status_code = 01234 r._content = False1235 r._content_consumed = False12361237 assert r.content is None1238 with pytest.raises(ValueError):1239 r.json()124012411242class TestCaseInsensitiveDict:12431244 @pytest.mark.parametrize(1245 'cid', (1246 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1247 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1248 CaseInsensitiveDict(FOO='foo', BAr='bar'),1249 ))1250 def test_init(self, cid):1251 assert len(cid) == 21252 assert 'foo' in cid1253 assert 'bar' in cid12541255 def test_docstring_example(self):1256 cid = CaseInsensitiveDict()1257 cid['Accept'] = 'application/json'1258 assert cid['aCCEPT'] == 'application/json'1259 assert list(cid) == ['Accept']12601261 def test_len(self):1262 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1263 cid['A'] = 'a'1264 assert len(cid) == 212651266 def test_getitem(self):1267 cid = CaseInsensitiveDict({'Spam': 'blueval'})1268 assert cid['spam'] == 'blueval'1269 assert cid['SPAM'] == 'blueval'12701271 def test_fixes_649(self):1272 """__setitem__ should behave case-insensitively."""1273 cid = CaseInsensitiveDict()1274 cid['spam'] = 'oneval'1275 cid['Spam'] = 'twoval'1276 cid['sPAM'] = 'redval'1277 cid['SPAM'] = 'blueval'1278 assert cid['spam'] == 'blueval'1279 assert cid['SPAM'] == 'blueval'1280 assert list(cid.keys()) == ['SPAM']12811282 def test_delitem(self):1283 cid = CaseInsensitiveDict()1284 cid['Spam'] = 'someval'1285 del cid['sPam']1286 assert 'spam' not in cid1287 assert len(cid) == 012881289 def test_contains(self):1290 cid = CaseInsensitiveDict()1291 cid['Spam'] = 'someval'1292 assert 'Spam' in cid1293 assert 'spam' in cid1294 assert 'SPAM' in cid1295 assert 'sPam' in cid1296 assert 'notspam' not in cid12971298 def test_get(self):1299 cid = CaseInsensitiveDict()1300 cid['spam'] = 'oneval'1301 cid['SPAM'] = 'blueval'1302 assert cid.get('spam') == 'blueval'1303 assert cid.get('SPAM') == 'blueval'1304 assert cid.get('sPam') == 'blueval'1305 assert cid.get('notspam', 'default') == 'default'13061307 def test_update(self):1308 cid = CaseInsensitiveDict()1309 cid['spam'] = 'blueval'1310 cid.update({'sPam': 'notblueval'})1311 assert cid['spam'] == 'notblueval'1312 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1313 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1314 assert len(cid) == 21315 assert cid['foo'] == 'anotherfoo'1316 assert cid['bar'] == 'anotherbar'13171318 def test_update_retains_unchanged(self):1319 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1320 cid.update({'foo': 'newfoo'})1321 assert cid['bar'] == 'bar'13221323 def test_iter(self):1324 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1325 keys = frozenset(['Spam', 'Eggs'])1326 assert frozenset(iter(cid)) == keys13271328 def test_equality(self):1329 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1330 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1331 assert cid == othercid1332 del othercid['spam']1333 assert cid != othercid1334 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1335 assert cid != object()13361337 def test_setdefault(self):1338 cid = CaseInsensitiveDict({'Spam': 'blueval'})1339 assert cid.setdefault('spam', 'notblueval') == 'blueval'1340 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'13411342 def test_lower_items(self):1343 cid = CaseInsensitiveDict({1344 'Accept': 'application/json',1345 'user-Agent': 'requests',1346 })1347 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1348 lowerkeyset = frozenset(['accept', 'user-agent'])1349 assert keyset == lowerkeyset13501351 def test_preserve_key_case(self):1352 cid = CaseInsensitiveDict({1353 'Accept': 'application/json',1354 'user-Agent': 'requests',1355 })1356 keyset = frozenset(['Accept', 'user-Agent'])1357 assert frozenset(i[0] for i in cid.items()) == keyset1358 assert frozenset(cid.keys()) == keyset1359 assert frozenset(cid) == keyset13601361 def test_preserve_last_key_case(self):1362 cid = CaseInsensitiveDict({1363 'Accept': 'application/json',1364 'user-Agent': 'requests',1365 })1366 cid.update({'ACCEPT': 'application/json'})1367 cid['USER-AGENT'] = 'requests'1368 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1369 assert frozenset(i[0] for i in cid.items()) == keyset1370 assert frozenset(cid.keys()) == keyset1371 assert frozenset(cid) == keyset13721373 def test_copy(self):1374 cid = CaseInsensitiveDict({1375 'Accept': 'application/json',1376 'user-Agent': 'requests',1377 })1378 cid_copy = cid.copy()1379 assert cid == cid_copy1380 cid['changed'] = True1381 assert cid != cid_copy138213831384class TestMorselToCookieExpires:1385 """Tests for morsel_to_cookie when morsel contains expires."""13861387 def test_expires_valid_str(self):1388 """Test case where we convert expires from string time."""13891390 morsel = Morsel()1391 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1392 cookie = morsel_to_cookie(morsel)1393 assert cookie.expires == 113941395 @pytest.mark.parametrize(1396 'value, exception', (1397 (100, TypeError),1398 ('woops', ValueError),1399 ))1400 def test_expires_invalid_int(self, value, exception):1401 """Test case where an invalid type is passed for expires."""1402 morsel = Morsel()1403 morsel['expires'] = value1404 with pytest.raises(exception):1405 morsel_to_cookie(morsel)14061407 def test_expires_none(self):1408 """Test case where expires is None."""14091410 morsel = Morsel()1411 morsel['expires'] = None1412 cookie = morsel_to_cookie(morsel)1413 assert cookie.expires is None141414151416class TestMorselToCookieMaxAge:14171418 """Tests for morsel_to_cookie when morsel contains max-age."""14191420 def test_max_age_valid_int(self):1421 """Test case where a valid max age in seconds is passed."""14221423 morsel = Morsel()1424 morsel['max-age'] = 601425 cookie = morsel_to_cookie(morsel)1426 assert isinstance(cookie.expires, int)14271428 def test_max_age_invalid_str(self):1429 """Test case where a invalid max age is passed."""14301431 morsel = Morsel()1432 morsel['max-age'] = 'woops'1433 with pytest.raises(TypeError):1434 morsel_to_cookie(morsel)143514361437class TestTimeout:14381439 def test_stream_timeout(self, httpbin):1440 try:1441 requests.get(httpbin('delay/10'), timeout=2.0)1442 except requests.exceptions.Timeout as e:1443 assert 'Read timed out' in e.args[0].args[0]14441445 @pytest.mark.parametrize(1446 'timeout, error_text', (1447 ((3, 4, 5), '(connect, read)'),1448 ('foo', 'must be an int or float'),1449 ))1450 def test_invalid_timeout(self, httpbin, timeout, error_text):1451 with pytest.raises(ValueError) as e:1452 requests.get(httpbin('get'), timeout=timeout)1453 assert error_text in str(e)14541455 def test_none_timeout(self, httpbin):1456 """ Check that you can set None as a valid timeout value.14571458 To actually test this behavior, we'd want to check that setting the1459 timeout to None actually lets the request block past the system default1460 timeout. However, this would make the test suite unbearably slow.1461 Instead we verify that setting the timeout to None does not prevent the1462 request from succeeding.1463 """1464 r = requests.get(httpbin('get'), timeout=None)1465 assert r.status_code == 20014661467 def test_read_timeout(self, httpbin):1468 try:1469 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1470 pytest.fail('The recv() request should time out.')1471 except ReadTimeout:1472 pass14731474 def test_connect_timeout(self):1475 try:1476 requests.get(TARPIT, timeout=(0.1, None))1477 pytest.fail('The connect() request should time out.')1478 except ConnectTimeout as e:1479 assert isinstance(e, ConnectionError)1480 assert isinstance(e, Timeout)14811482 def test_total_timeout_connect(self):1483 try:1484 requests.get(TARPIT, timeout=(0.1, 0.1))1485 pytest.fail('The connect() request should time out.')1486 except ConnectTimeout:1487 pass14881489 def test_encoded_methods(self, httpbin):1490 """See: https://github.com/kennethreitz/requests/issues/2316"""1491 r = requests.request(b'GET', httpbin('get'))1492 assert r.ok149314941495SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))149614971498class RedirectSession(SessionRedirectMixin):1499 def __init__(self, order_of_redirects):1500 self.redirects = order_of_redirects1501 self.calls = []1502 self.max_redirects = 301503 self.cookies = {}1504 self.trust_env = False15051506 def send(self, *args, **kwargs):1507 self.calls.append(SendCall(args, kwargs))1508 return self.build_response()15091510 def build_response(self):1511 request = self.calls[-1].args[0]1512 r = requests.Response()15131514 try:1515 r.status_code = int(self.redirects.pop(0))1516 except IndexError:1517 r.status_code = 20015181519 r.headers = CaseInsensitiveDict({'Location': '/'})1520 r.raw = self._build_raw()1521 r.request = request1522 return r15231524 def _build_raw(self):1525 string = StringIO.StringIO('')1526 setattr(string, 'release_conn', lambda *args: args)1527 return string152815291530def test_requests_are_updated_each_time(httpbin):1531 session = RedirectSession([303, 307])1532 prep = requests.Request('POST', httpbin('post')).prepare()1533 r0 = session.send(prep)1534 assert r0.request.method == 'POST'1535 assert session.calls[-1] == SendCall((r0.request,), {})1536 redirect_generator = session.resolve_redirects(r0, prep)1537 default_keyword_args = {1538 'stream': False,1539 'verify': True,1540 'cert': None,1541 'timeout': None,1542 'allow_redirects': False,1543 'proxies': {},1544 }1545 for response in redirect_generator:1546 assert response.request.method == 'GET'1547 send_call = SendCall((response.request,), default_keyword_args)1548 assert session.calls[-1] == send_call154915501551@pytest.mark.parametrize(1552 'data', (1553 (('a', 'b'), ('c', 'd')),1554 (('c', 'd'), ('a', 'b')),1555 (('a', 'b'), ('c', 'd'), ('e', 'f')),1556 ))1557def test_data_argument_accepts_tuples(data):1558 """Ensure that the data argument will accept tuples of strings1559 and properly encode them.1560 """1561 p = PreparedRequest()1562 p.prepare(1563 method='GET',1564 url='http://www.example.com',1565 data=data,1566 hooks=default_hooks()1567 )1568 assert p.body == urlencode(data)156915701571@pytest.mark.parametrize(1572 'kwargs', (1573 None,1574 {1575 'method': 'GET',1576 'url': 'http://www.example.com',1577 'data': 'foo=bar',1578 'hooks': default_hooks()1579 },1580 {1581 'method': 'GET',1582 'url': 'http://www.example.com',1583 'data': 'foo=bar',1584 'hooks': default_hooks(),1585 'cookies': {'foo': 'bar'}1586 },1587 {1588 'method': 'GET',1589 'url': u('http://www.example.com/üniçø∂é')1590 },1591 ))1592def test_prepared_copy(kwargs):1593 p = PreparedRequest()1594 if kwargs:1595 p.prepare(**kwargs)1596 copy = p.copy()1597 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1598 assert getattr(p, attr) == getattr(copy, attr)159916001601def test_urllib3_retries(httpbin):1602 from requests.packages.urllib3.util import Retry1603 s = requests.Session()1604 s.mount('http://', HTTPAdapter(max_retries=Retry(1605 total=2, status_forcelist=[500]1606 )))16071608 with pytest.raises(RetryError):1609 s.get(httpbin('status/500'))161016111612def test_urllib3_pool_connection_closed(httpbin):1613 s = requests.Session()1614 s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))16151616 try:1617 s.get(httpbin('status/200'))1618 except ConnectionError as e:1619 assert u"Pool is closed." in str(e)162016211622def test_vendor_aliases():1623 from requests.packages import urllib31624 from requests.packages import chardet16251626 with pytest.raises(ImportError):1627 from requests.packages import webbrowser