test_requests.py
This file
Path
test_requests.py
1,648 lines · 55.2 KiB · Python
Last changed by
Merge branch 'colindickson-master'Cory Benfieldbefore adoption8b5e457
History of this fileTake it
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import unittest11import collections12import contextlib1314import io15import requests16import pytest17from requests.adapters import HTTPAdapter18from requests.auth import HTTPDigestAuth, _basic_auth_str19from requests.compat import (20 Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3, builtin_str)21from requests.cookies import cookiejar_from_dict, morsel_to_cookie22from requests.exceptions import (ConnectionError, ConnectTimeout,23 InvalidSchema, InvalidURL, MissingSchema,24 ReadTimeout, Timeout, RetryError)25from requests.models import PreparedRequest26from requests.structures import CaseInsensitiveDict27from requests.sessions import SessionRedirectMixin28from requests.models import urlencode29from requests.hooks import default_hooks3031try:32 import StringIO33except ImportError:34 import io as StringIO3536if is_py3:37 def u(s):38 return s39else:40 def u(s):41 return s.decode('unicode-escape')424344# Requests to this URL should always fail with a connection timeout (nothing45# listening on that port)46TARPIT = "http://10.255.255.1"47HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')48# Issue #1483: Make sure the URL always has a trailing slash49HTTPBIN = HTTPBIN.rstrip('/') + '/'505152def httpbin(*suffix):53 """Returns url for HTTPBIN resource."""54 return urljoin(HTTPBIN, '/'.join(suffix))555657class RequestsTestCase(unittest.TestCase):5859 _multiprocess_can_split_ = True6061 def setUp(self):62 """Create simple data set with headers."""63 pass6465 def tearDown(self):66 """Teardown."""67 pass6869 def test_entry_points(self):7071 requests.session72 requests.session().get73 requests.session().head74 requests.get75 requests.head76 requests.put77 requests.patch78 requests.post7980 def test_invalid_url(self):81 with pytest.raises(MissingSchema):82 requests.get('hiwpefhipowhefopw')83 with pytest.raises(InvalidSchema):84 requests.get('localhost:3128')85 with pytest.raises(InvalidSchema):86 requests.get('localhost.localdomain:3128/')87 with pytest.raises(InvalidSchema):88 requests.get('10.122.1.1:3128/')89 with pytest.raises(InvalidURL):90 requests.get('http://')9192 def test_basic_building(self):93 req = requests.Request()94 req.url = 'http://kennethreitz.org/'95 req.data = {'life': '42'}9697 pr = req.prepare()98 assert pr.url == req.url99 assert pr.body == 'life=42'100101 def test_no_content_length(self):102 get_req = requests.Request('GET', httpbin('get')).prepare()103 assert 'Content-Length' not in get_req.headers104 head_req = requests.Request('HEAD', httpbin('head')).prepare()105 assert 'Content-Length' not in head_req.headers106107 def test_override_content_length(self):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 def test_params_are_added_before_fragment(self):121 request = requests.Request('GET',122 "http://example.com/path#fragment", params={"a": "b"}).prepare()123 assert request.url == "http://example.com/path?a=b#fragment"124 request = requests.Request('GET',125 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()126 assert request.url == "http://example.com/path?key=value&a=b#fragment"127128 def test_mixed_case_scheme_acceptable(self):129 s = requests.Session()130 s.proxies = getproxies()131 parts = urlparse(httpbin('get'))132 schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',133 'https://', 'HTTPS://', 'hTTps://', 'HttPs://']134 for scheme in schemes:135 url = scheme + parts.netloc + parts.path136 r = requests.Request('GET', url)137 r = s.send(r.prepare())138 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)139140 def test_HTTP_200_OK_GET_ALTERNATIVE(self):141 r = requests.Request('GET', httpbin('get'))142 s = requests.Session()143 s.proxies = getproxies()144145 r = s.send(r.prepare())146147 assert r.status_code == 200148149 def test_HTTP_302_ALLOW_REDIRECT_GET(self):150 r = requests.get(httpbin('redirect', '1'))151 assert r.status_code == 200152 assert r.history[0].status_code == 302153 assert r.history[0].is_redirect154155 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):156 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})157 # self.assertEqual(r.status_code, 200)158159 def test_HTTP_200_OK_GET_WITH_PARAMS(self):160 heads = {'User-agent': 'Mozilla/5.0'}161162 r = requests.get(httpbin('user-agent'), headers=heads)163164 assert heads['User-agent'] in r.text165 assert r.status_code == 200166167 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):168 heads = {'User-agent': 'Mozilla/5.0'}169170 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)171 assert r.status_code == 200172173 def test_set_cookie_on_301(self):174 s = requests.session()175 url = httpbin('cookies/set?foo=bar')176 s.get(url)177 assert s.cookies['foo'] == 'bar'178179 def test_cookie_sent_on_redirect(self):180 s = requests.session()181 s.get(httpbin('cookies/set?foo=bar'))182 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')183 assert 'Cookie' in r.json()['headers']184185 def test_cookie_removed_on_expire(self):186 s = requests.session()187 s.get(httpbin('cookies/set?foo=bar'))188 assert s.cookies['foo'] == 'bar'189 s.get(190 httpbin('response-headers'),191 params={192 'Set-Cookie':193 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'194 }195 )196 assert 'foo' not in s.cookies197198 def test_cookie_quote_wrapped(self):199 s = requests.session()200 s.get(httpbin('cookies/set?foo="bar:baz"'))201 assert s.cookies['foo'] == '"bar:baz"'202203 def test_cookie_persists_via_api(self):204 s = requests.session()205 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})206 assert 'foo' in r.request.headers['Cookie']207 assert 'foo' in r.history[0].request.headers['Cookie']208209 def test_request_cookie_overrides_session_cookie(self):210 s = requests.session()211 s.cookies['foo'] = 'bar'212 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})213 assert r.json()['cookies']['foo'] == 'baz'214 # Session cookie should not be modified215 assert s.cookies['foo'] == 'bar'216217 def test_request_cookies_not_persisted(self):218 s = requests.session()219 s.get(httpbin('cookies'), cookies={'foo': 'baz'})220 # Sending a request with cookies should not add cookies to the session221 assert not s.cookies222223 def test_generic_cookiejar_works(self):224 cj = cookielib.CookieJar()225 cookiejar_from_dict({'foo': 'bar'}, cj)226 s = requests.session()227 s.cookies = cj228 r = s.get(httpbin('cookies'))229 # Make sure the cookie was sent230 assert r.json()['cookies']['foo'] == 'bar'231 # Make sure the session cj is still the custom one232 assert s.cookies is cj233234 def test_param_cookiejar_works(self):235 cj = cookielib.CookieJar()236 cookiejar_from_dict({'foo': 'bar'}, cj)237 s = requests.session()238 r = s.get(httpbin('cookies'), cookies=cj)239 # Make sure the cookie was sent240 assert r.json()['cookies']['foo'] == 'bar'241242 def test_requests_in_history_are_not_overridden(self):243 resp = requests.get(httpbin('redirect/3'))244 urls = [r.url for r in resp.history]245 req_urls = [r.request.url for r in resp.history]246 assert urls == req_urls247248 def test_history_is_always_a_list(self):249 """250 Show that even with redirects, Response.history is always a list.251 """252 resp = requests.get(httpbin('get'))253 assert isinstance(resp.history, list)254 resp = requests.get(httpbin('redirect/1'))255 assert isinstance(resp.history, list)256 assert not isinstance(resp.history, tuple)257258 def test_headers_on_session_with_None_are_not_sent(self):259 """Do not send headers in Session.headers with None values."""260 ses = requests.Session()261 ses.headers['Accept-Encoding'] = None262 req = requests.Request('GET', httpbin('get'))263 prep = ses.prepare_request(req)264 assert 'Accept-Encoding' not in prep.headers265266 def test_user_agent_transfers(self):267268 heads = {269 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'270 }271272 r = requests.get(httpbin('user-agent'), headers=heads)273 assert heads['User-agent'] in r.text274275 heads = {276 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'277 }278279 r = requests.get(httpbin('user-agent'), headers=heads)280 assert heads['user-agent'] in r.text281282 def test_HTTP_200_OK_HEAD(self):283 r = requests.head(httpbin('get'))284 assert r.status_code == 200285286 def test_HTTP_200_OK_PUT(self):287 r = requests.put(httpbin('put'))288 assert r.status_code == 200289290 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):291 auth = ('user', 'pass')292 url = httpbin('basic-auth', 'user', 'pass')293294 r = requests.get(url, auth=auth)295 assert r.status_code == 200296297 r = requests.get(url)298 assert r.status_code == 401299300 s = requests.session()301 s.auth = auth302 r = s.get(url)303 assert r.status_code == 200304305 def test_connection_error_invalid_domain(self):306 """Connecting to an unknown domain should raise a ConnectionError"""307 with pytest.raises(ConnectionError):308 requests.get("http://doesnotexist.google.com")309310 def test_connection_error_invalid_port(self):311 """Connecting to an invalid port should raise a ConnectionError"""312 with pytest.raises(ConnectionError):313 requests.get("http://httpbin.org:1", timeout=1)314315 def test_LocationParseError(self):316 """Inputing a URL that cannot be parsed should raise an InvalidURL error"""317 with pytest.raises(InvalidURL):318 requests.get("http://fe80::5054:ff:fe5a:fc0")319320 def test_basicauth_with_netrc(self):321 auth = ('user', 'pass')322 wrong_auth = ('wronguser', 'wrongpass')323 url = httpbin('basic-auth', 'user', 'pass')324325 def get_netrc_auth_mock(url):326 return auth327 requests.sessions.get_netrc_auth = get_netrc_auth_mock328329 # Should use netrc and work.330 r = requests.get(url)331 assert r.status_code == 200332333 # Given auth should override and fail.334 r = requests.get(url, auth=wrong_auth)335 assert r.status_code == 401336337 s = requests.session()338339 # Should use netrc and work.340 r = s.get(url)341 assert r.status_code == 200342343 # Given auth should override and fail.344 s.auth = wrong_auth345 r = s.get(url)346 assert r.status_code == 401347348 def test_DIGEST_HTTP_200_OK_GET(self):349350 auth = HTTPDigestAuth('user', 'pass')351 url = httpbin('digest-auth', 'auth', 'user', 'pass')352353 r = requests.get(url, auth=auth)354 assert r.status_code == 200355356 r = requests.get(url)357 assert r.status_code == 401358359 s = requests.session()360 s.auth = HTTPDigestAuth('user', 'pass')361 r = s.get(url)362 assert r.status_code == 200363364 def test_DIGEST_AUTH_RETURNS_COOKIE(self):365 url = httpbin('digest-auth', 'auth', 'user', 'pass')366 auth = HTTPDigestAuth('user', 'pass')367 r = requests.get(url)368 assert r.cookies['fake'] == 'fake_value'369370 r = requests.get(url, auth=auth)371 assert r.status_code == 200372373 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):374 url = httpbin('digest-auth', 'auth', 'user', 'pass')375 auth = HTTPDigestAuth('user', 'pass')376 s = requests.Session()377 s.get(url, auth=auth)378 assert s.cookies['fake'] == 'fake_value'379380 def test_DIGEST_STREAM(self):381382 auth = HTTPDigestAuth('user', 'pass')383 url = httpbin('digest-auth', 'auth', 'user', 'pass')384385 r = requests.get(url, auth=auth, stream=True)386 assert r.raw.read() != b''387388 r = requests.get(url, auth=auth, stream=False)389 assert r.raw.read() == b''390391 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):392393 auth = HTTPDigestAuth('user', 'wrongpass')394 url = httpbin('digest-auth', 'auth', 'user', 'pass')395396 r = requests.get(url, auth=auth)397 assert r.status_code == 401398399 r = requests.get(url)400 assert r.status_code == 401401402 s = requests.session()403 s.auth = auth404 r = s.get(url)405 assert r.status_code == 401406407 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):408409 auth = HTTPDigestAuth('user', 'pass')410 url = httpbin('digest-auth', 'auth', 'user', 'pass')411412 r = requests.get(url, auth=auth)413 assert '"auth"' in r.request.headers['Authorization']414415 def test_POSTBIN_GET_POST_FILES(self):416417 url = httpbin('post')418 post1 = requests.post(url).raise_for_status()419420 post1 = requests.post(url, data={'some': 'data'})421 assert post1.status_code == 200422423 with open('requirements.txt') as f:424 post2 = requests.post(url, files={'some': f})425 assert post2.status_code == 200426427 post4 = requests.post(url, data='[{"some": "json"}]')428 assert post4.status_code == 200429430 with pytest.raises(ValueError):431 requests.post(url, files=['bad file data'])432433 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):434435 url = httpbin('post')436 post1 = requests.post(url).raise_for_status()437438 post1 = requests.post(url, data={'some': 'data'})439 assert post1.status_code == 200440441 with open('requirements.txt') as f:442 post2 = requests.post(url,443 data={'some': 'data'}, files={'some': f})444 assert post2.status_code == 200445446 post4 = requests.post(url, data='[{"some": "json"}]')447 assert post4.status_code == 200448449 with pytest.raises(ValueError):450 requests.post(url, files=['bad file data'])451452 def test_conflicting_post_params(self):453 url = httpbin('post')454 with open('requirements.txt') as f:455 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")456 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")457458 def test_request_ok_set(self):459 r = requests.get(httpbin('status', '404'))460 assert not r.ok461462 def test_status_raising(self):463 r = requests.get(httpbin('status', '404'))464 with pytest.raises(requests.exceptions.HTTPError):465 r.raise_for_status()466467 r = requests.get(httpbin('status', '500'))468 assert not r.ok469470 def test_decompress_gzip(self):471 r = requests.get(httpbin('gzip'))472 r.content.decode('ascii')473474 def test_unicode_get(self):475 url = httpbin('/get')476 requests.get(url, params={'foo': 'føø'})477 requests.get(url, params={'føø': 'føø'})478 requests.get(url, params={'føø': 'føø'})479 requests.get(url, params={'foo': 'foo'})480 requests.get(httpbin('ø'), params={'foo': 'foo'})481482 def test_unicode_header_name(self):483 requests.put(484 httpbin('put'),485 headers={str('Content-Type'): 'application/octet-stream'},486 data='\xff') # compat.str is unicode.487488 def test_pyopenssl_redirect(self):489 requests.get('https://httpbin.org/status/301')490491 def test_urlencoded_get_query_multivalued_param(self):492493 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))494 assert r.status_code == 200495 assert r.url == httpbin('get?test=foo&test=baz')496497 def test_different_encodings_dont_break_post(self):498 r = requests.post(httpbin('post'),499 data={'stuff': json.dumps({'a': 123})},500 params={'blah': 'asdf1234'},501 files={'file': ('test_requests.py', open(__file__, 'rb'))})502 assert r.status_code == 200503504 def test_unicode_multipart_post(self):505 r = requests.post(httpbin('post'),506 data={'stuff': u('ëlïxr')},507 files={'file': ('test_requests.py', open(__file__, 'rb'))})508 assert r.status_code == 200509510 r = requests.post(httpbin('post'),511 data={'stuff': u('ëlïxr').encode('utf-8')},512 files={'file': ('test_requests.py', open(__file__, 'rb'))})513 assert r.status_code == 200514515 r = requests.post(httpbin('post'),516 data={'stuff': 'elixr'},517 files={'file': ('test_requests.py', open(__file__, 'rb'))})518 assert r.status_code == 200519520 r = requests.post(httpbin('post'),521 data={'stuff': 'elixr'.encode('utf-8')},522 files={'file': ('test_requests.py', open(__file__, 'rb'))})523 assert r.status_code == 200524525 def test_unicode_multipart_post_fieldnames(self):526 filename = os.path.splitext(__file__)[0] + '.py'527 r = requests.Request(method='POST',528 url=httpbin('post'),529 data={'stuff'.encode('utf-8'): 'elixr'},530 files={'file': ('test_requests.py',531 open(filename, 'rb'))})532 prep = r.prepare()533 assert b'name="stuff"' in prep.body534 assert b'name="b\'stuff\'"' not in prep.body535536 def test_unicode_method_name(self):537 files = {'file': open('test_requests.py', 'rb')}538 r = requests.request(539 method=u('POST'), url=httpbin('post'), files=files)540 assert r.status_code == 200541542 def test_custom_content_type(self):543 r = requests.post(544 httpbin('post'),545 data={'stuff': json.dumps({'a': 123})},546 files={'file1': ('test_requests.py', open(__file__, 'rb')),547 'file2': ('test_requests', open(__file__, 'rb'),548 'text/py-content-type')})549 assert r.status_code == 200550 assert b"text/py-content-type" in r.request.body551552 def test_hook_receives_request_arguments(self):553 def hook(resp, **kwargs):554 assert resp is not None555 assert kwargs != {}556557 requests.Request('GET', HTTPBIN, hooks={'response': hook})558559 def test_session_hooks_are_used_with_no_request_hooks(self):560 hook = lambda x, *args, **kwargs: x561 s = requests.Session()562 s.hooks['response'].append(hook)563 r = requests.Request('GET', HTTPBIN)564 prep = s.prepare_request(r)565 assert prep.hooks['response'] != []566 assert prep.hooks['response'] == [hook]567568 def test_session_hooks_are_overriden_by_request_hooks(self):569 hook1 = lambda x, *args, **kwargs: x570 hook2 = lambda x, *args, **kwargs: x571 assert hook1 is not hook2572 s = requests.Session()573 s.hooks['response'].append(hook2)574 r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})575 prep = s.prepare_request(r)576 assert prep.hooks['response'] == [hook1]577578 def test_prepared_request_hook(self):579 def hook(resp, **kwargs):580 resp.hook_working = True581 return resp582583 req = requests.Request('GET', HTTPBIN, hooks={'response': hook})584 prep = req.prepare()585586 s = requests.Session()587 s.proxies = getproxies()588 resp = s.send(prep)589590 assert hasattr(resp, 'hook_working')591592 def test_prepared_from_session(self):593 class DummyAuth(requests.auth.AuthBase):594 def __call__(self, r):595 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'596 return r597598 req = requests.Request('GET', httpbin('headers'))599 assert not req.auth600601 s = requests.Session()602 s.auth = DummyAuth()603604 prep = s.prepare_request(req)605 resp = s.send(prep)606607 assert resp.json()['headers'][608 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'609610 def test_prepare_request_with_bytestring_url(self):611 req = requests.Request('GET', b'https://httpbin.org/')612 s = requests.Session()613 prep = s.prepare_request(req)614 assert prep.url == "https://httpbin.org/"615616 def test_links(self):617 r = requests.Response()618 r.headers = {619 'cache-control': 'public, max-age=60, s-maxage=60',620 'connection': 'keep-alive',621 'content-encoding': 'gzip',622 'content-type': 'application/json; charset=utf-8',623 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',624 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',625 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',626 'link': ('<https://api.github.com/users/kennethreitz/repos?'627 'page=2&per_page=10>; rel="next", <https://api.github.'628 'com/users/kennethreitz/repos?page=7&per_page=10>; '629 ' rel="last"'),630 'server': 'GitHub.com',631 'status': '200 OK',632 'vary': 'Accept',633 'x-content-type-options': 'nosniff',634 'x-github-media-type': 'github.beta',635 'x-ratelimit-limit': '60',636 'x-ratelimit-remaining': '57'637 }638 assert r.links['next']['rel'] == 'next'639640 def test_cookie_parameters(self):641 key = 'some_cookie'642 value = 'some_value'643 secure = True644 domain = 'test.com'645 rest = {'HttpOnly': True}646647 jar = requests.cookies.RequestsCookieJar()648 jar.set(key, value, secure=secure, domain=domain, rest=rest)649650 assert len(jar) == 1651 assert 'some_cookie' in jar652653 cookie = list(jar)[0]654 assert cookie.secure == secure655 assert cookie.domain == domain656 assert cookie._rest['HttpOnly'] == rest['HttpOnly']657658 def test_cookie_as_dict_keeps_len(self):659 key = 'some_cookie'660 value = 'some_value'661662 key1 = 'some_cookie1'663 value1 = 'some_value1'664665 jar = requests.cookies.RequestsCookieJar()666 jar.set(key, value)667 jar.set(key1, value1)668669 d1 = dict(jar)670 d2 = dict(jar.iteritems())671 d3 = dict(jar.items())672673 assert len(jar) == 2674 assert len(d1) == 2675 assert len(d2) == 2676 assert len(d3) == 2677678 def test_cookie_as_dict_keeps_items(self):679 key = 'some_cookie'680 value = 'some_value'681682 key1 = 'some_cookie1'683 value1 = 'some_value1'684685 jar = requests.cookies.RequestsCookieJar()686 jar.set(key, value)687 jar.set(key1, value1)688689 d1 = dict(jar)690 d2 = dict(jar.iteritems())691 d3 = dict(jar.items())692693 assert d1['some_cookie'] == 'some_value'694 assert d2['some_cookie'] == 'some_value'695 assert d3['some_cookie1'] == 'some_value1'696697 def test_cookie_as_dict_keys(self):698 key = 'some_cookie'699 value = 'some_value'700701 key1 = 'some_cookie1'702 value1 = 'some_value1'703704 jar = requests.cookies.RequestsCookieJar()705 jar.set(key, value)706 jar.set(key1, value1)707708 keys = jar.keys()709 assert keys == list(keys)710 # make sure one can use keys multiple times711 assert list(keys) == list(keys)712713 def test_cookie_as_dict_values(self):714 key = 'some_cookie'715 value = 'some_value'716717 key1 = 'some_cookie1'718 value1 = 'some_value1'719720 jar = requests.cookies.RequestsCookieJar()721 jar.set(key, value)722 jar.set(key1, value1)723724 values = jar.values()725 assert values == list(values)726 # make sure one can use values multiple times727 assert list(values) == list(values)728729 def test_cookie_as_dict_items(self):730 key = 'some_cookie'731 value = 'some_value'732733 key1 = 'some_cookie1'734 value1 = 'some_value1'735736 jar = requests.cookies.RequestsCookieJar()737 jar.set(key, value)738 jar.set(key1, value1)739740 items = jar.items()741 assert items == list(items)742 # make sure one can use items multiple times743 assert list(items) == list(items)744745 def test_time_elapsed_blank(self):746 r = requests.get(httpbin('get'))747 td = r.elapsed748 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)749 * 10**6) / 10**6)750 assert total_seconds > 0.0751752 def test_response_is_iterable(self):753 r = requests.Response()754 io = StringIO.StringIO('abc')755 read_ = io.read756757 def read_mock(amt, decode_content=None):758 return read_(amt)759 setattr(io, 'read', read_mock)760 r.raw = io761 assert next(iter(r))762 io.close()763764 def test_response_decode_unicode(self):765 """766 When called with decode_unicode, Response.iter_content should always767 return unicode.768 """769 r = requests.Response()770 r._content_consumed = True771 r._content = b'the content'772 r.encoding = 'ascii'773774 chunks = r.iter_content(decode_unicode=True)775 assert all(isinstance(chunk, str) for chunk in chunks)776777 # also for streaming778 r = requests.Response()779 r.raw = io.BytesIO(b'the content')780 r.encoding = 'ascii'781 chunks = r.iter_content(decode_unicode=True)782 assert all(isinstance(chunk, str) for chunk in chunks)783784 def test_request_and_response_are_pickleable(self):785 r = requests.get(httpbin('get'))786787 # verify we can pickle the original request788 assert pickle.loads(pickle.dumps(r.request))789790 # verify we can pickle the response and that we have access to791 # the original request.792 pr = pickle.loads(pickle.dumps(r))793 assert r.request.url == pr.request.url794 assert r.request.headers == pr.request.headers795796 def test_get_auth_from_url(self):797 url = 'http://user:pass@complex.url.com/path?query=yes'798 assert ('user', 'pass') == requests.utils.get_auth_from_url(url)799800 def test_get_auth_from_url_encoded_spaces(self):801 url = 'http://user:pass%20pass@complex.url.com/path?query=yes'802 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)803804 def test_get_auth_from_url_not_encoded_spaces(self):805 url = 'http://user:pass pass@complex.url.com/path?query=yes'806 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)807808 def test_get_auth_from_url_percent_chars(self):809 url = 'http://user%25user:pass@complex.url.com/path?query=yes'810 assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)811812 def test_get_auth_from_url_encoded_hashes(self):813 url = 'http://user:pass%23pass@complex.url.com/path?query=yes'814 assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)815816 def test_cannot_send_unprepared_requests(self):817 r = requests.Request(url=HTTPBIN)818 with pytest.raises(ValueError):819 requests.Session().send(r)820821 def test_http_error(self):822 error = requests.exceptions.HTTPError()823 assert not error.response824 response = requests.Response()825 error = requests.exceptions.HTTPError(response=response)826 assert error.response == response827 error = requests.exceptions.HTTPError('message', response=response)828 assert str(error) == 'message'829 assert error.response == response830831 def test_session_pickling(self):832 r = requests.Request('GET', httpbin('get'))833 s = requests.Session()834835 s = pickle.loads(pickle.dumps(s))836 s.proxies = getproxies()837838 r = s.send(r.prepare())839 assert r.status_code == 200840841 def test_fixes_1329(self):842 """843 Ensure that header updates are done case-insensitively.844 """845 s = requests.Session()846 s.headers.update({'ACCEPT': 'BOGUS'})847 s.headers.update({'accept': 'application/json'})848 r = s.get(httpbin('get'))849 headers = r.request.headers850 assert headers['accept'] == 'application/json'851 assert headers['Accept'] == 'application/json'852 assert headers['ACCEPT'] == 'application/json'853854 def test_uppercase_scheme_redirect(self):855 parts = urlparse(httpbin('html'))856 url = "HTTP://" + parts.netloc + parts.path857 r = requests.get(httpbin('redirect-to'), params={'url': url})858 assert r.status_code == 200859 assert r.url.lower() == url.lower()860861 def test_transport_adapter_ordering(self):862 s = requests.Session()863 order = ['https://', 'http://']864 assert order == list(s.adapters)865 s.mount('http://git', HTTPAdapter())866 s.mount('http://github', HTTPAdapter())867 s.mount('http://github.com', HTTPAdapter())868 s.mount('http://github.com/about/', HTTPAdapter())869 order = [870 'http://github.com/about/',871 'http://github.com',872 'http://github',873 'http://git',874 'https://',875 'http://',876 ]877 assert order == list(s.adapters)878 s.mount('http://gittip', HTTPAdapter())879 s.mount('http://gittip.com', HTTPAdapter())880 s.mount('http://gittip.com/about/', HTTPAdapter())881 order = [882 'http://github.com/about/',883 'http://gittip.com/about/',884 'http://github.com',885 'http://gittip.com',886 'http://github',887 'http://gittip',888 'http://git',889 'https://',890 'http://',891 ]892 assert order == list(s.adapters)893 s2 = requests.Session()894 s2.adapters = {'http://': HTTPAdapter()}895 s2.mount('https://', HTTPAdapter())896 assert 'http://' in s2.adapters897 assert 'https://' in s2.adapters898899 def test_header_remove_is_case_insensitive(self):900 # From issue #1321901 s = requests.Session()902 s.headers['foo'] = 'bar'903 r = s.get(httpbin('get'), headers={'FOO': None})904 assert 'foo' not in r.request.headers905906 def test_params_are_merged_case_sensitive(self):907 s = requests.Session()908 s.params['foo'] = 'bar'909 r = s.get(httpbin('get'), params={'FOO': 'bar'})910 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}911912 def test_long_authinfo_in_url(self):913 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(914 'E8A3BE87-9E3F-4620-8858-95478E385B5B',915 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',916 'exactly-------------sixty-----------three------------characters',917 )918 r = requests.Request('GET', url).prepare()919 assert r.url == url920921 def test_header_keys_are_native(self):922 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}923 r = requests.Request('GET', httpbin('get'), headers=headers)924 p = r.prepare()925926 # This is testing that they are builtin strings. A bit weird, but there927 # we go.928 assert 'unicode' in p.headers.keys()929 assert 'byte' in p.headers.keys()930931 def test_can_send_nonstring_objects_with_files(self):932 data = {'a': 0.0}933 files = {'b': 'foo'}934 r = requests.Request('POST', httpbin('post'), data=data, files=files)935 p = r.prepare()936937 assert 'multipart/form-data' in p.headers['Content-Type']938939 def test_can_send_bytes_bytearray_objects_with_files(self):940 # Test bytes:941 data = {'a': 'this is a string'}942 files = {'b': b'foo'}943 r = requests.Request('POST', httpbin('post'), data=data, files=files)944 p = r.prepare()945 assert 'multipart/form-data' in p.headers['Content-Type']946 # Test bytearrays:947 files = {'b': bytearray(b'foo')}948 r = requests.Request('POST', httpbin('post'), data=data, files=files)949 p = r.prepare()950 assert 'multipart/form-data' in p.headers['Content-Type']951952 def test_can_send_file_object_with_non_string_filename(self):953 f = io.BytesIO()954 f.name = 2955 r = requests.Request('POST', httpbin('post'), files={'f': f})956 p = r.prepare()957958 assert 'multipart/form-data' in p.headers['Content-Type']959960 def test_autoset_header_values_are_native(self):961 data = 'this is a string'962 length = '16'963 req = requests.Request('POST', httpbin('post'), data=data)964 p = req.prepare()965966 assert p.headers['Content-Length'] == length967968 def test_nonhttp_schemes_dont_check_URLs(self):969 test_urls = (970 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',971 'file:///etc/passwd',972 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',973 )974 for test_url in test_urls:975 req = requests.Request('GET', test_url)976 preq = req.prepare()977 assert test_url == preq.url978979 def test_auth_is_stripped_on_redirect_off_host(self):980 r = requests.get(981 httpbin('redirect-to'),982 params={'url': 'http://www.google.co.uk'},983 auth=('user', 'pass'),984 )985 assert r.history[0].request.headers['Authorization']986 assert not r.request.headers.get('Authorization', '')987988 def test_auth_is_retained_for_redirect_on_host(self):989 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))990 h1 = r.history[0].request.headers['Authorization']991 h2 = r.request.headers['Authorization']992993 assert h1 == h2994995 def test_manual_redirect_with_partial_body_read(self):996 s = requests.Session()997 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)998 assert r1.is_redirect999 rg = s.resolve_redirects(r1, r1.request, stream=True)10001001 # read only the first eight bytes of the response body,1002 # then follow the redirect1003 r1.iter_content(8)1004 r2 = next(rg)1005 assert r2.is_redirect10061007 # read all of the response via iter_content,1008 # then follow the redirect1009 for _ in r2.iter_content():1010 pass1011 r3 = next(rg)1012 assert not r3.is_redirect10131014 def _patch_adapter_gzipped_redirect(self, session, url):1015 adapter = session.get_adapter(url=url)1016 org_build_response = adapter.build_response1017 self._patched_response = False10181019 def build_response(*args, **kwargs):1020 resp = org_build_response(*args, **kwargs)1021 if not self._patched_response:1022 resp.raw.headers['content-encoding'] = 'gzip'1023 self._patched_response = True1024 return resp10251026 adapter.build_response = build_response10271028 def test_redirect_with_wrong_gzipped_header(self):1029 s = requests.Session()1030 url = httpbin('redirect/1')1031 self._patch_adapter_gzipped_redirect(s, url)1032 s.get(url)10331034 def test_basic_auth_str_is_always_native(self):1035 s = _basic_auth_str("test", "test")1036 assert isinstance(s, builtin_str)1037 assert s == "Basic dGVzdDp0ZXN0"10381039 def test_requests_history_is_saved(self):1040 r = requests.get(httpbin('redirect/5'))1041 total = r.history[-1].history1042 i = 01043 for item in r.history:1044 assert item.history == total[0:i]1045 i = i + 110461047 def test_json_param_post_content_type_works(self):1048 r = requests.post(1049 httpbin('post'),1050 json={'life': 42}1051 )1052 assert r.status_code == 2001053 assert 'application/json' in r.request.headers['Content-Type']1054 assert {'life': 42} == r.json()['json']10551056 def test_response_iter_lines(self):1057 r = requests.get(httpbin('stream/4'), stream=True)1058 assert r.status_code == 20010591060 it = r.iter_lines()1061 next(it)1062 assert len(list(it)) == 310631064 def test_unconsumed_session_response_closes_connection(self):1065 s = requests.session()10661067 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1068 pass10691070 self.assertFalse(response._content_consumed)1071 self.assertTrue(response.raw.closed)10721073 @pytest.mark.xfail1074 def test_response_iter_lines_reentrant(self):1075 """Response.iter_lines() is not reentrant safe"""1076 r = requests.get(httpbin('stream/4'), stream=True)1077 assert r.status_code == 20010781079 next(r.iter_lines())1080 assert len(list(r.iter_lines())) == 3108110821083class TestContentEncodingDetection(unittest.TestCase):10841085 def test_none(self):1086 encodings = requests.utils.get_encodings_from_content('')1087 assert not len(encodings)10881089 def test_html_charset(self):1090 """HTML5 meta charset attribute"""1091 content = '<meta charset="UTF-8">'1092 encodings = requests.utils.get_encodings_from_content(content)1093 assert len(encodings) == 11094 assert encodings[0] == 'UTF-8'10951096 def test_html4_pragma(self):1097 """HTML4 pragma directive"""1098 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'1099 encodings = requests.utils.get_encodings_from_content(content)1100 assert len(encodings) == 11101 assert encodings[0] == 'UTF-8'11021103 def test_xhtml_pragma(self):1104 """XHTML 1.x served with text/html MIME type"""1105 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'1106 encodings = requests.utils.get_encodings_from_content(content)1107 assert len(encodings) == 11108 assert encodings[0] == 'UTF-8'11091110 def test_xml(self):1111 """XHTML 1.x served as XML"""1112 content = '<?xml version="1.0" encoding="UTF-8"?>'1113 encodings = requests.utils.get_encodings_from_content(content)1114 assert len(encodings) == 11115 assert encodings[0] == 'UTF-8'11161117 def test_precedence(self):1118 content = '''1119 <?xml version="1.0" encoding="XML"?>1120 <meta charset="HTML5">1121 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1122 '''.strip()1123 encodings = requests.utils.get_encodings_from_content(content)1124 assert encodings == ['HTML5', 'HTML4', 'XML']112511261127class TestCaseInsensitiveDict(unittest.TestCase):11281129 def test_mapping_init(self):1130 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1131 assert len(cid) == 21132 assert 'foo' in cid1133 assert 'bar' in cid11341135 def test_iterable_init(self):1136 cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1137 assert len(cid) == 21138 assert 'foo' in cid1139 assert 'bar' in cid11401141 def test_kwargs_init(self):1142 cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1143 assert len(cid) == 21144 assert 'foo' in cid1145 assert 'bar' in cid11461147 def test_docstring_example(self):1148 cid = CaseInsensitiveDict()1149 cid['Accept'] = 'application/json'1150 assert cid['aCCEPT'] == 'application/json'1151 assert list(cid) == ['Accept']11521153 def test_len(self):1154 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1155 cid['A'] = 'a'1156 assert len(cid) == 211571158 def test_getitem(self):1159 cid = CaseInsensitiveDict({'Spam': 'blueval'})1160 assert cid['spam'] == 'blueval'1161 assert cid['SPAM'] == 'blueval'11621163 def test_fixes_649(self):1164 """__setitem__ should behave case-insensitively."""1165 cid = CaseInsensitiveDict()1166 cid['spam'] = 'oneval'1167 cid['Spam'] = 'twoval'1168 cid['sPAM'] = 'redval'1169 cid['SPAM'] = 'blueval'1170 assert cid['spam'] == 'blueval'1171 assert cid['SPAM'] == 'blueval'1172 assert list(cid.keys()) == ['SPAM']11731174 def test_delitem(self):1175 cid = CaseInsensitiveDict()1176 cid['Spam'] = 'someval'1177 del cid['sPam']1178 assert 'spam' not in cid1179 assert len(cid) == 011801181 def test_contains(self):1182 cid = CaseInsensitiveDict()1183 cid['Spam'] = 'someval'1184 assert 'Spam' in cid1185 assert 'spam' in cid1186 assert 'SPAM' in cid1187 assert 'sPam' in cid1188 assert 'notspam' not in cid11891190 def test_get(self):1191 cid = CaseInsensitiveDict()1192 cid['spam'] = 'oneval'1193 cid['SPAM'] = 'blueval'1194 assert cid.get('spam') == 'blueval'1195 assert cid.get('SPAM') == 'blueval'1196 assert cid.get('sPam') == 'blueval'1197 assert cid.get('notspam', 'default') == 'default'11981199 def test_update(self):1200 cid = CaseInsensitiveDict()1201 cid['spam'] = 'blueval'1202 cid.update({'sPam': 'notblueval'})1203 assert cid['spam'] == 'notblueval'1204 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1205 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1206 assert len(cid) == 21207 assert cid['foo'] == 'anotherfoo'1208 assert cid['bar'] == 'anotherbar'12091210 def test_update_retains_unchanged(self):1211 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1212 cid.update({'foo': 'newfoo'})1213 assert cid['bar'] == 'bar'12141215 def test_iter(self):1216 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1217 keys = frozenset(['Spam', 'Eggs'])1218 assert frozenset(iter(cid)) == keys12191220 def test_equality(self):1221 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1222 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1223 assert cid == othercid1224 del othercid['spam']1225 assert cid != othercid1226 assert cid == {'spam': 'blueval', 'eggs': 'redval'}12271228 def test_setdefault(self):1229 cid = CaseInsensitiveDict({'Spam': 'blueval'})1230 assert cid.setdefault('spam', 'notblueval') == 'blueval'1231 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'12321233 def test_lower_items(self):1234 cid = CaseInsensitiveDict({1235 'Accept': 'application/json',1236 'user-Agent': 'requests',1237 })1238 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1239 lowerkeyset = frozenset(['accept', 'user-agent'])1240 assert keyset == lowerkeyset12411242 def test_preserve_key_case(self):1243 cid = CaseInsensitiveDict({1244 'Accept': 'application/json',1245 'user-Agent': 'requests',1246 })1247 keyset = frozenset(['Accept', 'user-Agent'])1248 assert frozenset(i[0] for i in cid.items()) == keyset1249 assert frozenset(cid.keys()) == keyset1250 assert frozenset(cid) == keyset12511252 def test_preserve_last_key_case(self):1253 cid = CaseInsensitiveDict({1254 'Accept': 'application/json',1255 'user-Agent': 'requests',1256 })1257 cid.update({'ACCEPT': 'application/json'})1258 cid['USER-AGENT'] = 'requests'1259 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1260 assert frozenset(i[0] for i in cid.items()) == keyset1261 assert frozenset(cid.keys()) == keyset1262 assert frozenset(cid) == keyset126312641265class UtilsTestCase(unittest.TestCase):12661267 def test_super_len_io_streams(self):1268 """ Ensures that we properly deal with different kinds of IO streams. """1269 # uses StringIO or io.StringIO (see import above)1270 from io import BytesIO1271 from requests.utils import super_len12721273 assert super_len(StringIO.StringIO()) == 01274 assert super_len(1275 StringIO.StringIO('with so much drama in the LBC')) == 2912761277 assert super_len(BytesIO()) == 01278 assert super_len(1279 BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 4012801281 try:1282 import cStringIO1283 except ImportError:1284 pass1285 else:1286 assert super_len(1287 cStringIO.StringIO('but some how, some way...')) == 2512881289 def test_get_environ_proxies_ip_ranges(self):1290 """Ensures that IP addresses are correctly matches with ranges1291 in no_proxy variable."""1292 from requests.utils import get_environ_proxies1293 os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1294 assert get_environ_proxies('http://192.168.0.1:5000/') == {}1295 assert get_environ_proxies('http://192.168.0.1/') == {}1296 assert get_environ_proxies('http://172.16.1.1/') == {}1297 assert get_environ_proxies('http://172.16.1.1:5000/') == {}1298 assert get_environ_proxies('http://192.168.1.1:5000/') != {}1299 assert get_environ_proxies('http://192.168.1.1/') != {}13001301 def test_get_environ_proxies(self):1302 """Ensures that IP addresses are correctly matches with ranges1303 in no_proxy variable."""1304 from requests.utils import get_environ_proxies1305 os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1306 assert get_environ_proxies(1307 'http://localhost.localdomain:5000/v1.0/') == {}1308 assert get_environ_proxies('http://www.requests.com/') != {}13091310 def test_guess_filename_when_int(self):1311 from requests.utils import guess_filename1312 assert None is guess_filename(1)13131314 def test_guess_filename_when_filename_is_an_int(self):1315 from requests.utils import guess_filename1316 fake = type('Fake', (object,), {'name': 1})()1317 assert None is guess_filename(fake)13181319 def test_guess_filename_with_file_like_obj(self):1320 from requests.utils import guess_filename1321 from requests import compat1322 fake = type('Fake', (object,), {'name': b'value'})()1323 guessed_name = guess_filename(fake)1324 assert b'value' == guessed_name1325 assert isinstance(guessed_name, compat.bytes)13261327 def test_guess_filename_with_unicode_name(self):1328 from requests.utils import guess_filename1329 from requests import compat1330 filename = b'value'.decode('utf-8')1331 fake = type('Fake', (object,), {'name': filename})()1332 guessed_name = guess_filename(fake)1333 assert filename == guessed_name1334 assert isinstance(guessed_name, compat.str)13351336 def test_is_ipv4_address(self):1337 from requests.utils import is_ipv4_address1338 assert is_ipv4_address('8.8.8.8')1339 assert not is_ipv4_address('8.8.8.8.8')1340 assert not is_ipv4_address('localhost.localdomain')13411342 def test_is_valid_cidr(self):1343 from requests.utils import is_valid_cidr1344 assert not is_valid_cidr('8.8.8.8')1345 assert is_valid_cidr('192.168.1.0/24')13461347 def test_dotted_netmask(self):1348 from requests.utils import dotted_netmask1349 assert dotted_netmask(8) == '255.0.0.0'1350 assert dotted_netmask(24) == '255.255.255.0'1351 assert dotted_netmask(25) == '255.255.255.128'13521353 def test_address_in_network(self):1354 from requests.utils import address_in_network1355 assert address_in_network('192.168.1.1', '192.168.1.0/24')1356 assert not address_in_network('172.16.0.1', '192.168.1.0/24')13571358 def test_get_auth_from_url(self):1359 """Ensures that username and password in well-encoded URI as per1360 RFC 3986 are correclty extracted."""1361 from requests.utils import get_auth_from_url1362 from requests.compat import quote1363 percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1364 url_address = "request.com/url.html#test"1365 url = "http://" + quote(1366 percent_encoding_test_chars, '') + ':' + quote(1367 percent_encoding_test_chars, '') + '@' + url_address1368 (username, password) = get_auth_from_url(url)1369 assert username == percent_encoding_test_chars1370 assert password == percent_encoding_test_chars13711372 def test_requote_uri_with_unquoted_percents(self):1373 """Ensure we handle unquoted percent signs in redirects.13741375 See: https://github.com/kennethreitz/requests/issues/23561376 """1377 from requests.utils import requote_uri1378 bad_uri = 'http://example.com/fiz?buz=%ppicture'1379 quoted = 'http://example.com/fiz?buz=%25ppicture'1380 assert quoted == requote_uri(bad_uri)13811382 def test_requote_uri_properly_requotes(self):1383 """Ensure requoting doesn't break expectations."""1384 from requests.utils import requote_uri1385 quoted = 'http://example.com/fiz?buz=%25ppicture'1386 assert quoted == requote_uri(quoted)138713881389class TestMorselToCookieExpires(unittest.TestCase):13901391 """Tests for morsel_to_cookie when morsel contains expires."""13921393 def test_expires_valid_str(self):1394 """Test case where we convert expires from string time."""13951396 morsel = Morsel()1397 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1398 cookie = morsel_to_cookie(morsel)1399 assert cookie.expires == 114001401 def test_expires_invalid_int(self):1402 """Test case where an invalid type is passed for expires."""14031404 morsel = Morsel()1405 morsel['expires'] = 1001406 with pytest.raises(TypeError):1407 morsel_to_cookie(morsel)14081409 def test_expires_invalid_str(self):1410 """Test case where an invalid string is input."""14111412 morsel = Morsel()1413 morsel['expires'] = 'woops'1414 with pytest.raises(ValueError):1415 morsel_to_cookie(morsel)14161417 def test_expires_none(self):1418 """Test case where expires is None."""14191420 morsel = Morsel()1421 morsel['expires'] = None1422 cookie = morsel_to_cookie(morsel)1423 assert cookie.expires is None142414251426class TestMorselToCookieMaxAge(unittest.TestCase):14271428 """Tests for morsel_to_cookie when morsel contains max-age."""14291430 def test_max_age_valid_int(self):1431 """Test case where a valid max age in seconds is passed."""14321433 morsel = Morsel()1434 morsel['max-age'] = 601435 cookie = morsel_to_cookie(morsel)1436 assert isinstance(cookie.expires, int)14371438 def test_max_age_invalid_str(self):1439 """Test case where a invalid max age is passed."""14401441 morsel = Morsel()1442 morsel['max-age'] = 'woops'1443 with pytest.raises(TypeError):1444 morsel_to_cookie(morsel)144514461447class TestTimeout:1448 def test_stream_timeout(self):1449 try:1450 requests.get(httpbin('delay/10'), timeout=2.0)1451 except requests.exceptions.Timeout as e:1452 assert 'Read timed out' in e.args[0].args[0]14531454 def test_invalid_timeout(self):1455 with pytest.raises(ValueError) as e:1456 requests.get(httpbin('get'), timeout=(3, 4, 5))1457 assert '(connect, read)' in str(e)14581459 with pytest.raises(ValueError) as e:1460 requests.get(httpbin('get'), timeout="foo")1461 assert 'must be an int or float' in str(e)14621463 def test_none_timeout(self):1464 """ Check that you can set None as a valid timeout value.14651466 To actually test this behavior, we'd want to check that setting the1467 timeout to None actually lets the request block past the system default1468 timeout. However, this would make the test suite unbearably slow.1469 Instead we verify that setting the timeout to None does not prevent the1470 request from succeeding.1471 """1472 r = requests.get(httpbin('get'), timeout=None)1473 assert r.status_code == 20014741475 def test_read_timeout(self):1476 try:1477 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1478 assert False, "The recv() request should time out."1479 except ReadTimeout:1480 pass14811482 def test_connect_timeout(self):1483 try:1484 requests.get(TARPIT, timeout=(0.1, None))1485 assert False, "The connect() request should time out."1486 except ConnectTimeout as e:1487 assert isinstance(e, ConnectionError)1488 assert isinstance(e, Timeout)14891490 def test_total_timeout_connect(self):1491 try:1492 requests.get(TARPIT, timeout=(0.1, 0.1))1493 assert False, "The connect() request should time out."1494 except ConnectTimeout:1495 pass14961497 def test_encoded_methods(self):1498 """See: https://github.com/kennethreitz/requests/issues/2316"""1499 r = requests.request(b'GET', httpbin('get'))1500 assert r.ok150115021503SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))150415051506class RedirectSession(SessionRedirectMixin):1507 def __init__(self, order_of_redirects):1508 self.redirects = order_of_redirects1509 self.calls = []1510 self.max_redirects = 301511 self.cookies = {}1512 self.trust_env = False15131514 def send(self, *args, **kwargs):1515 self.calls.append(SendCall(args, kwargs))1516 return self.build_response()15171518 def build_response(self):1519 request = self.calls[-1].args[0]1520 r = requests.Response()15211522 try:1523 r.status_code = int(self.redirects.pop(0))1524 except IndexError:1525 r.status_code = 20015261527 r.headers = CaseInsensitiveDict({'Location': '/'})1528 r.raw = self._build_raw()1529 r.request = request1530 return r15311532 def _build_raw(self):1533 string = StringIO.StringIO('')1534 setattr(string, 'release_conn', lambda *args: args)1535 return string153615371538class TestRedirects:1539 default_keyword_args = {1540 'stream': False,1541 'verify': True,1542 'cert': None,1543 'timeout': None,1544 'allow_redirects': False,1545 'proxies': {},1546 }15471548 def test_requests_are_updated_each_time(self):1549 session = RedirectSession([303, 307])1550 prep = requests.Request('POST', httpbin('post')).prepare()1551 r0 = session.send(prep)1552 assert r0.request.method == 'POST'1553 assert session.calls[-1] == SendCall((r0.request,), {})1554 redirect_generator = session.resolve_redirects(r0, prep)1555 for response in redirect_generator:1556 assert response.request.method == 'GET'1557 send_call = SendCall((response.request,),1558 TestRedirects.default_keyword_args)1559 assert session.calls[-1] == send_call1560156115621563@pytest.fixture1564def list_of_tuples():1565 return [1566 (('a', 'b'), ('c', 'd')),1567 (('c', 'd'), ('a', 'b')),1568 (('a', 'b'), ('c', 'd'), ('e', 'f')),1569 ]157015711572def test_data_argument_accepts_tuples(list_of_tuples):1573 """1574 Ensure that the data argument will accept tuples of strings1575 and properly encode them.1576 """1577 for data in list_of_tuples:1578 p = PreparedRequest()1579 p.prepare(1580 method='GET',1581 url='http://www.example.com',1582 data=data,1583 hooks=default_hooks()1584 )1585 assert p.body == urlencode(data)158615871588def assert_copy(p, p_copy):1589 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1590 assert getattr(p, attr) == getattr(p_copy, attr)159115921593def test_prepared_request_empty_copy():1594 p = PreparedRequest()1595 assert_copy(p, p.copy())159615971598def test_prepared_request_no_cookies_copy():1599 p = PreparedRequest()1600 p.prepare(1601 method='GET',1602 url='http://www.example.com',1603 data='foo=bar',1604 hooks=default_hooks()1605 )1606 assert_copy(p, p.copy())160716081609def test_prepared_request_complete_copy():1610 p = PreparedRequest()1611 p.prepare(1612 method='GET',1613 url='http://www.example.com',1614 data='foo=bar',1615 hooks=default_hooks(),1616 cookies={'foo': 'bar'}1617 )1618 assert_copy(p, p.copy())161916201621def test_prepare_unicode_url():1622 p = PreparedRequest()1623 p.prepare(1624 method='GET',1625 url=u('http://www.example.com/üniçø∂é'),1626 )1627 assert_copy(p, p.copy())162816291630def test_urllib3_retries():1631 from requests.packages.urllib3.util import Retry1632 s = requests.Session()1633 s.mount('http://', HTTPAdapter(max_retries=Retry(1634 total=2, status_forcelist=[500]1635 )))16361637 with pytest.raises(RetryError):1638 s.get(httpbin('status/500'))16391640def test_vendor_aliases():1641 from requests.packages import urllib31642 from requests.packages import chardet16431644 with pytest.raises(ImportError):1645 from requests.packages import webbrowser16461647if __name__ == '__main__':1648 unittest.main()