Added tests module.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Dmitry Dygalo · committed by Dmitry Dygalo · parent 6143b7e · Browse files · 7 files·+1755 added−1727 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+1755 added−1727 removed
- tests:+1753 added−0 removed
- other:+2 added−1727 removed
Provenance
- Commit
18b26d2- Tree
03daa67- Author
Dmitry Dygalo <dadygalo@gmail.com>- Committer
Dmitry Dygalo <dadygalo@gmail.com>- Parent
6143b7e
7 files changed+1755 added−1727 removed
added:tests/__init__.py+1 added
1+# coding: utf-8added:tests/compat.py+20 added
1+# coding: utf-82+from requests.compat import is_py33+4+5+try:6+ import StringIO7+except ImportError:8+ import io as StringIO9+10+try:11+ from cStringIO import StringIO as cStringIO12+except ImportError:13+ cStringIO = None14+15+if is_py3:16+ def u(s):17+ return s18+else:19+ def u(s):20+ return s.decode('unicode-escape')added:tests/conftest.py+23 added
1+# coding: utf-82+import pytest3+from requests.compat import urljoin4+5+6+def prepare_url(value):7+ # Issue #1483: Make sure the URL always has a trailing slash8+ httpbin_url = value.url.rstrip('/') + '/'9+10+ def inner(*suffix):11+ return urljoin(httpbin_url, '/'.join(suffix))12+13+ return inner14+15+16+@pytest.fixture17+def httpbin(httpbin):18+ return prepare_url(httpbin)19+20+21+@pytest.fixture22+def httpbin_secure(httpbin_secure):23+ return prepare_url(httpbin_secure)added:tests/test_requests.py+1467 added
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+4+"""Tests for Requests."""5+6+from __future__ import division7+import json8+import os9+import pickle10+import collections11+import contextlib12+13+import io14+import requests15+import pytest16+from requests.adapters import HTTPAdapter17+from requests.auth import HTTPDigestAuth, _basic_auth_str18+from requests.compat import (19+ Morsel, cookielib, getproxies, str, urlparse,20+ builtin_str, OrderedDict)21+from requests.cookies import cookiejar_from_dict, morsel_to_cookie22+from requests.exceptions import (23+ ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,24+ MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects)25+from requests.models import PreparedRequest26+from requests.structures import CaseInsensitiveDict27+from requests.sessions import SessionRedirectMixin28+from requests.models import urlencode29+from requests.hooks import default_hooks30+31+from .compat import StringIO, u32+33+# Requests to this URL should always fail with a connection timeout (nothing34+# listening on that port)35+TARPIT = "http://10.255.255.1"36+37+38+class TestRequests:39+40+ def test_entry_points(self):41+42+ requests.session43+ requests.session().get44+ requests.session().head45+ requests.get46+ requests.head47+ requests.put48+ requests.patch49+ requests.post50+51+ @pytest.mark.parametrize('exception, url',52+ (53+ (MissingSchema, 'hiwpefhipowhefopw'),54+ (InvalidSchema, 'localhost:3128'),55+ (InvalidSchema, 'localhost.localdomain:3128/'),56+ (InvalidSchema, '10.122.1.1:3128/'),57+ (InvalidURL, 'http://'),58+ )59+ )60+ def test_invalid_url(self, exception, url):61+ with pytest.raises(exception):62+ requests.get(url)63+64+ def test_basic_building(self):65+ req = requests.Request()66+ req.url = 'http://kennethreitz.org/'67+ req.data = {'life': '42'}68+69+ pr = req.prepare()70+ assert pr.url == req.url71+ assert pr.body == 'life=42'72+73+ @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.headers77+78+ 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'85+86+ def test_path_is_not_double_encoded(self):87+ request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()88+89+ assert request.path_url == '/get/test%20case'90+91+ @pytest.mark.parametrize('url, expected',92+ (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+ )97+ def test_params_are_added_before_fragment(self, url, expected):98+ request = requests.Request('GET', url, params={"a": "b"}).prepare()99+ assert request.url == expected100+101+ def test_params_original_order_is_preserved_by_default(self):102+ param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))103+ session = requests.Session()104+ request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)105+ prep = session.prepare_request(request)106+ assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'107+108+ def test_params_bytes_are_encoded(self):109+ request = requests.Request('GET', 'http://example.com',110+ params=b'test=foo').prepare()111+ assert request.url == 'http://example.com/?test=foo'112+113+ def test_binary_put(self):114+ request = requests.Request('PUT', 'http://example.com',115+ data=u"ööö".encode("utf-8")).prepare()116+ assert isinstance(request.body, bytes)117+118+ @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))119+ def test_mixed_case_scheme_acceptable(self, httpbin, scheme):120+ s = requests.Session()121+ s.proxies = getproxies()122+ parts = urlparse(httpbin('get'))123+ url = scheme + parts.netloc + parts.path124+ r = requests.Request('GET', url)125+ r = s.send(r.prepare())126+ assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)127+128+ def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):129+ r = requests.Request('GET', httpbin('get'))130+ s = requests.Session()131+ s.proxies = getproxies()132+133+ r = s.send(r.prepare())134+135+ assert r.status_code == 200136+137+ def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):138+ r = requests.get(httpbin('redirect', '1'))139+ assert r.status_code == 200140+ assert r.history[0].status_code == 302141+ assert r.history[0].is_redirect142+143+ def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):144+ try:145+ requests.get(httpbin('relative-redirect', '50'))146+ except TooManyRedirects as e:147+ url = httpbin('relative-redirect', '20')148+ assert e.request.url == url149+ assert e.response.url == url150+ assert len(e.response.history) == 30151+ else:152+ pytest.fail('Expected redirect to raise TooManyRedirects but it did not')153+154+ def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):155+ s = requests.session()156+ s.max_redirects = 5157+ try:158+ s.get(httpbin('relative-redirect', '50'))159+ except TooManyRedirects as e:160+ url = httpbin('relative-redirect', '45')161+ assert e.request.url == url162+ assert e.response.url == url163+ assert len(e.response.history) == 5164+ else:165+ pytest.fail('Expected custom max number of redirects to be respected but was not')166+167+ # def test_HTTP_302_ALLOW_REDIRECT_POST(self):168+ # r = requests.post(httpbin('status', '302'), data={'some': 'data'})169+ # self.assertEqual(r.status_code, 200)170+171+ def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):172+ heads = {'User-agent': 'Mozilla/5.0'}173+174+ r = requests.get(httpbin('user-agent'), headers=heads)175+176+ assert heads['User-agent'] in r.text177+ assert r.status_code == 200178+179+ def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):180+ heads = {'User-agent': 'Mozilla/5.0'}181+182+ r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)183+ assert r.status_code == 200184+185+ def test_set_cookie_on_301(self, httpbin):186+ s = requests.session()187+ url = httpbin('cookies/set?foo=bar')188+ s.get(url)189+ assert s.cookies['foo'] == 'bar'190+191+ def test_cookie_sent_on_redirect(self, httpbin):192+ s = requests.session()193+ s.get(httpbin('cookies/set?foo=bar'))194+ r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')195+ assert 'Cookie' in r.json()['headers']196+197+ def test_cookie_removed_on_expire(self, httpbin):198+ s = requests.session()199+ s.get(httpbin('cookies/set?foo=bar'))200+ assert s.cookies['foo'] == 'bar'201+ s.get(202+ httpbin('response-headers'),203+ params={204+ 'Set-Cookie':205+ 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'206+ }207+ )208+ assert 'foo' not in s.cookies209+210+ def test_cookie_quote_wrapped(self, httpbin):211+ s = requests.session()212+ s.get(httpbin('cookies/set?foo="bar:baz"'))213+ assert s.cookies['foo'] == '"bar:baz"'214+215+ def test_cookie_persists_via_api(self, httpbin):216+ s = requests.session()217+ r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})218+ assert 'foo' in r.request.headers['Cookie']219+ assert 'foo' in r.history[0].request.headers['Cookie']220+221+ def test_request_cookie_overrides_session_cookie(self, httpbin):222+ s = requests.session()223+ s.cookies['foo'] = 'bar'224+ r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})225+ assert r.json()['cookies']['foo'] == 'baz'226+ # Session cookie should not be modified227+ assert s.cookies['foo'] == 'bar'228+229+ def test_request_cookies_not_persisted(self, httpbin):230+ s = requests.session()231+ s.get(httpbin('cookies'), cookies={'foo': 'baz'})232+ # Sending a request with cookies should not add cookies to the session233+ assert not s.cookies234+235+ def test_generic_cookiejar_works(self, httpbin):236+ cj = cookielib.CookieJar()237+ cookiejar_from_dict({'foo': 'bar'}, cj)238+ s = requests.session()239+ s.cookies = cj240+ r = s.get(httpbin('cookies'))241+ # Make sure the cookie was sent242+ assert r.json()['cookies']['foo'] == 'bar'243+ # Make sure the session cj is still the custom one244+ assert s.cookies is cj245+246+ def test_param_cookiejar_works(self, httpbin):247+ cj = cookielib.CookieJar()248+ cookiejar_from_dict({'foo': 'bar'}, cj)249+ s = requests.session()250+ r = s.get(httpbin('cookies'), cookies=cj)251+ # Make sure the cookie was sent252+ assert r.json()['cookies']['foo'] == 'bar'253+254+ def test_requests_in_history_are_not_overridden(self, httpbin):255+ resp = requests.get(httpbin('redirect/3'))256+ urls = [r.url for r in resp.history]257+ req_urls = [r.request.url for r in resp.history]258+ assert urls == req_urls259+260+ def test_history_is_always_a_list(self, httpbin):261+ """Show that even with redirects, Response.history is always a list."""262+ resp = requests.get(httpbin('get'))263+ assert isinstance(resp.history, list)264+ resp = requests.get(httpbin('redirect/1'))265+ assert isinstance(resp.history, list)266+ assert not isinstance(resp.history, tuple)267+268+ def test_headers_on_session_with_None_are_not_sent(self, httpbin):269+ """Do not send headers in Session.headers with None values."""270+ ses = requests.Session()271+ ses.headers['Accept-Encoding'] = None272+ req = requests.Request('GET', httpbin('get'))273+ prep = ses.prepare_request(req)274+ assert 'Accept-Encoding' not in prep.headers275+276+ @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))277+ def test_user_agent_transfers(self, httpbin, key):278+279+ heads = {280+ key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'281+ }282+283+ r = requests.get(httpbin('user-agent'), headers=heads)284+ assert heads[key] in r.text285+286+ def test_HTTP_200_OK_HEAD(self, httpbin):287+ r = requests.head(httpbin('get'))288+ assert r.status_code == 200289+290+ def test_HTTP_200_OK_PUT(self, httpbin):291+ r = requests.put(httpbin('put'))292+ assert r.status_code == 200293+294+ def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):295+ auth = ('user', 'pass')296+ url = httpbin('basic-auth', 'user', 'pass')297+298+ r = requests.get(url, auth=auth)299+ assert r.status_code == 200300+301+ r = requests.get(url)302+ assert r.status_code == 401303+304+ s = requests.session()305+ s.auth = auth306+ r = s.get(url)307+ assert r.status_code == 200308+309+ @pytest.mark.parametrize(310+ 'url, exception', (311+ # Connecting to an unknown domain should raise a ConnectionError312+ ('http://doesnotexist.google.com', ConnectionError),313+ # Connecting to an invalid port should raise a ConnectionError314+ ('http://localhost:1', ConnectionError),315+ # Inputing a URL that cannot be parsed should raise an InvalidURL error316+ ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)317+ )318+ )319+ def test_errors(self, url, exception):320+ with pytest.raises(exception):321+ requests.get(url, timeout=1)322+323+ def test_basicauth_with_netrc(self, httpbin):324+ auth = ('user', 'pass')325+ wrong_auth = ('wronguser', 'wrongpass')326+ url = httpbin('basic-auth', 'user', 'pass')327+328+ old_auth = requests.sessions.get_netrc_auth329+330+ try:331+ def get_netrc_auth_mock(url):332+ return auth333+ requests.sessions.get_netrc_auth = get_netrc_auth_mock334+335+ # Should use netrc and work.336+ r = requests.get(url)337+ assert r.status_code == 200338+339+ # Given auth should override and fail.340+ r = requests.get(url, auth=wrong_auth)341+ assert r.status_code == 401342+343+ s = requests.session()344+345+ # Should use netrc and work.346+ r = s.get(url)347+ assert r.status_code == 200348+349+ # Given auth should override and fail.350+ s.auth = wrong_auth351+ r = s.get(url)352+ assert r.status_code == 401353+ finally:354+ requests.sessions.get_netrc_auth = old_auth355+356+ def test_DIGEST_HTTP_200_OK_GET(self, httpbin):357+358+ auth = HTTPDigestAuth('user', 'pass')359+ url = httpbin('digest-auth', 'auth', 'user', 'pass')360+361+ r = requests.get(url, auth=auth)362+ assert r.status_code == 200363+364+ r = requests.get(url)365+ assert r.status_code == 401366+367+ s = requests.session()368+ s.auth = HTTPDigestAuth('user', 'pass')369+ r = s.get(url)370+ assert r.status_code == 200371+372+ def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):373+ url = httpbin('digest-auth', 'auth', 'user', 'pass')374+ auth = HTTPDigestAuth('user', 'pass')375+ r = requests.get(url)376+ assert r.cookies['fake'] == 'fake_value'377+378+ r = requests.get(url, auth=auth)379+ assert r.status_code == 200380+381+ def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):382+ url = httpbin('digest-auth', 'auth', 'user', 'pass')383+ auth = HTTPDigestAuth('user', 'pass')384+ s = requests.Session()385+ s.get(url, auth=auth)386+ assert s.cookies['fake'] == 'fake_value'387+388+ def test_DIGEST_STREAM(self, httpbin):389+390+ auth = HTTPDigestAuth('user', 'pass')391+ url = httpbin('digest-auth', 'auth', 'user', 'pass')392+393+ r = requests.get(url, auth=auth, stream=True)394+ assert r.raw.read() != b''395+396+ r = requests.get(url, auth=auth, stream=False)397+ assert r.raw.read() == b''398+399+ def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):400+401+ auth = HTTPDigestAuth('user', 'wrongpass')402+ url = httpbin('digest-auth', 'auth', 'user', 'pass')403+404+ r = requests.get(url, auth=auth)405+ assert r.status_code == 401406+407+ r = requests.get(url)408+ assert r.status_code == 401409+410+ s = requests.session()411+ s.auth = auth412+ r = s.get(url)413+ assert r.status_code == 401414+415+ def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):416+417+ auth = HTTPDigestAuth('user', 'pass')418+ url = httpbin('digest-auth', 'auth', 'user', 'pass')419+420+ r = requests.get(url, auth=auth)421+ assert '"auth"' in r.request.headers['Authorization']422+423+ def test_POSTBIN_GET_POST_FILES(self, httpbin):424+425+ url = httpbin('post')426+ requests.post(url).raise_for_status()427+428+ post1 = requests.post(url, data={'some': 'data'})429+ assert post1.status_code == 200430+431+ with open('requirements.txt') as f:432+ post2 = requests.post(url, files={'some': f})433+ assert post2.status_code == 200434+435+ post4 = requests.post(url, data='[{"some": "json"}]')436+ assert post4.status_code == 200437+438+ with pytest.raises(ValueError):439+ requests.post(url, files=['bad file data'])440+441+ def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):442+443+ url = httpbin('post')444+ requests.post(url).raise_for_status()445+446+ post1 = requests.post(url, data={'some': 'data'})447+ assert post1.status_code == 200448+449+ with open('requirements.txt') as f:450+ post2 = requests.post(url,451+ data={'some': 'data'}, files={'some': f})452+ assert post2.status_code == 200453+454+ post4 = requests.post(url, data='[{"some": "json"}]')455+ assert post4.status_code == 200456+457+ with pytest.raises(ValueError):458+ requests.post(url, files=['bad file data'])459+460+ def test_conflicting_post_params(self, httpbin):461+ url = httpbin('post')462+ with open('requirements.txt') as f:463+ pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")464+ pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")465+466+ def test_request_ok_set(self, httpbin):467+ r = requests.get(httpbin('status', '404'))468+ assert not r.ok469+470+ def test_status_raising(self, httpbin):471+ r = requests.get(httpbin('status', '404'))472+ with pytest.raises(requests.exceptions.HTTPError):473+ r.raise_for_status()474+475+ r = requests.get(httpbin('status', '500'))476+ assert not r.ok477+478+ def test_decompress_gzip(self, httpbin):479+ r = requests.get(httpbin('gzip'))480+ r.content.decode('ascii')481+482+ @pytest.mark.parametrize(483+ 'url, params',484+ (485+ ('/get', {'foo': 'føø'}),486+ ('/get', {'føø': 'føø'}),487+ ('/get', {'føø': 'føø'}),488+ ('/get', {'foo': 'foo'}),489+ ('ø', {'foo': 'foo'}),490+ )491+ )492+ def test_unicode_get(self, httpbin, url, params):493+ requests.get(httpbin(url), params=params)494+495+ def test_unicode_header_name(self, httpbin):496+ requests.put(497+ httpbin('put'),498+ headers={str('Content-Type'): 'application/octet-stream'},499+ data='\xff') # compat.str is unicode.500+501+ def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):502+ requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)503+504+ def test_urlencoded_get_query_multivalued_param(self, httpbin):505+506+ r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))507+ assert r.status_code == 200508+ assert r.url == httpbin('get?test=foo&test=baz')509+510+ def test_different_encodings_dont_break_post(self, httpbin):511+ r = requests.post(httpbin('post'),512+ data={'stuff': json.dumps({'a': 123})},513+ params={'blah': 'asdf1234'},514+ files={'file': ('test_requests.py', open(__file__, 'rb'))})515+ assert r.status_code == 200516+517+ @pytest.mark.parametrize(518+ 'data', (519+ {'stuff': u('ëlïxr')},520+ {'stuff': u('ëlïxr').encode('utf-8')},521+ {'stuff': 'elixr'},522+ {'stuff': 'elixr'.encode('utf-8')},523+ )524+ )525+ def test_unicode_multipart_post(self, httpbin, data):526+ r = requests.post(httpbin('post'),527+ data=data,528+ files={'file': ('test_requests.py', open(__file__, 'rb'))})529+ assert r.status_code == 200530+531+ def test_unicode_multipart_post_fieldnames(self, httpbin):532+ filename = os.path.splitext(__file__)[0] + '.py'533+ r = requests.Request(method='POST',534+ url=httpbin('post'),535+ data={'stuff'.encode('utf-8'): 'elixr'},536+ files={'file': ('test_requests.py',537+ open(filename, 'rb'))})538+ prep = r.prepare()539+ assert b'name="stuff"' in prep.body540+ assert b'name="b\'stuff\'"' not in prep.body541+542+ def test_unicode_method_name(self, httpbin):543+ files = {'file': open(__file__, 'rb')}544+ r = requests.request(545+ method=u('POST'), url=httpbin('post'), files=files)546+ assert r.status_code == 200547+548+ def test_unicode_method_name_with_request_object(self, httpbin):549+ files = {'file': open(__file__, 'rb')}550+ s = requests.Session()551+ req = requests.Request(u("POST"), httpbin('post'), files=files)552+ prep = s.prepare_request(req)553+ assert isinstance(prep.method, builtin_str)554+ assert prep.method == "POST"555+556+ resp = s.send(prep)557+ assert resp.status_code == 200558+559+ def test_custom_content_type(self, httpbin):560+ r = requests.post(561+ httpbin('post'),562+ data={'stuff': json.dumps({'a': 123})},563+ files={'file1': ('test_requests.py', open(__file__, 'rb')),564+ 'file2': ('test_requests', open(__file__, 'rb'),565+ 'text/py-content-type')})566+ assert r.status_code == 200567+ assert b"text/py-content-type" in r.request.body568+569+ def test_hook_receives_request_arguments(self, httpbin):570+ def hook(resp, **kwargs):571+ assert resp is not None572+ assert kwargs != {}573+574+ s = requests.Session()575+ r = requests.Request('GET', httpbin(), hooks={'response': hook})576+ prep = s.prepare_request(r)577+ s.send(prep)578+579+ def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):580+ hook = lambda x, *args, **kwargs: x581+ s = requests.Session()582+ s.hooks['response'].append(hook)583+ r = requests.Request('GET', httpbin())584+ prep = s.prepare_request(r)585+ assert prep.hooks['response'] != []586+ assert prep.hooks['response'] == [hook]587+588+ def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):589+ hook1 = lambda x, *args, **kwargs: x590+ hook2 = lambda x, *args, **kwargs: x591+ assert hook1 is not hook2592+ s = requests.Session()593+ s.hooks['response'].append(hook2)594+ r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})595+ prep = s.prepare_request(r)596+ assert prep.hooks['response'] == [hook1]597+598+ def test_prepared_request_hook(self, httpbin):599+ def hook(resp, **kwargs):600+ resp.hook_working = True601+ return resp602+603+ req = requests.Request('GET', httpbin(), hooks={'response': hook})604+ prep = req.prepare()605+606+ s = requests.Session()607+ s.proxies = getproxies()608+ resp = s.send(prep)609+610+ assert hasattr(resp, 'hook_working')611+612+ def test_prepared_from_session(self, httpbin):613+ class DummyAuth(requests.auth.AuthBase):614+ def __call__(self, r):615+ r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'616+ return r617+618+ req = requests.Request('GET', httpbin('headers'))619+ assert not req.auth620+621+ s = requests.Session()622+ s.auth = DummyAuth()623+624+ prep = s.prepare_request(req)625+ resp = s.send(prep)626+627+ assert resp.json()['headers'][628+ 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'629+630+ def test_prepare_request_with_bytestring_url(self):631+ req = requests.Request('GET', b'https://httpbin.org/')632+ s = requests.Session()633+ prep = s.prepare_request(req)634+ assert prep.url == "https://httpbin.org/"635+636+ def test_links(self):637+ r = requests.Response()638+ r.headers = {639+ 'cache-control': 'public, max-age=60, s-maxage=60',640+ 'connection': 'keep-alive',641+ 'content-encoding': 'gzip',642+ 'content-type': 'application/json; charset=utf-8',643+ 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',644+ 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',645+ 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',646+ 'link': ('<https://api.github.com/users/kennethreitz/repos?'647+ 'page=2&per_page=10>; rel="next", <https://api.github.'648+ 'com/users/kennethreitz/repos?page=7&per_page=10>; '649+ ' rel="last"'),650+ 'server': 'GitHub.com',651+ 'status': '200 OK',652+ 'vary': 'Accept',653+ 'x-content-type-options': 'nosniff',654+ 'x-github-media-type': 'github.beta',655+ 'x-ratelimit-limit': '60',656+ 'x-ratelimit-remaining': '57'657+ }658+ assert r.links['next']['rel'] == 'next'659+660+ def test_cookie_parameters(self):661+ key = 'some_cookie'662+ value = 'some_value'663+ secure = True664+ domain = 'test.com'665+ rest = {'HttpOnly': True}666+667+ jar = requests.cookies.RequestsCookieJar()668+ jar.set(key, value, secure=secure, domain=domain, rest=rest)669+670+ assert len(jar) == 1671+ assert 'some_cookie' in jar672+673+ cookie = list(jar)[0]674+ assert cookie.secure == secure675+ assert cookie.domain == domain676+ assert cookie._rest['HttpOnly'] == rest['HttpOnly']677+678+ def test_cookie_as_dict_keeps_len(self):679+ key = 'some_cookie'680+ value = 'some_value'681+682+ key1 = 'some_cookie1'683+ value1 = 'some_value1'684+685+ jar = requests.cookies.RequestsCookieJar()686+ jar.set(key, value)687+ jar.set(key1, value1)688+689+ d1 = dict(jar)690+ d2 = dict(jar.iteritems())691+ d3 = dict(jar.items())692+693+ assert len(jar) == 2694+ assert len(d1) == 2695+ assert len(d2) == 2696+ assert len(d3) == 2697+698+ def test_cookie_as_dict_keeps_items(self):699+ key = 'some_cookie'700+ value = 'some_value'701+702+ key1 = 'some_cookie1'703+ value1 = 'some_value1'704+705+ jar = requests.cookies.RequestsCookieJar()706+ jar.set(key, value)707+ jar.set(key1, value1)708+709+ d1 = dict(jar)710+ d2 = dict(jar.iteritems())711+ d3 = dict(jar.items())712+713+ assert d1['some_cookie'] == 'some_value'714+ assert d2['some_cookie'] == 'some_value'715+ assert d3['some_cookie1'] == 'some_value1'716+717+ def test_cookie_as_dict_keys(self):718+ key = 'some_cookie'719+ value = 'some_value'720+721+ key1 = 'some_cookie1'722+ value1 = 'some_value1'723+724+ jar = requests.cookies.RequestsCookieJar()725+ jar.set(key, value)726+ jar.set(key1, value1)727+728+ keys = jar.keys()729+ assert keys == list(keys)730+ # make sure one can use keys multiple times731+ assert list(keys) == list(keys)732+733+ def test_cookie_as_dict_values(self):734+ key = 'some_cookie'735+ value = 'some_value'736+737+ key1 = 'some_cookie1'738+ value1 = 'some_value1'739+740+ jar = requests.cookies.RequestsCookieJar()741+ jar.set(key, value)742+ jar.set(key1, value1)743+744+ values = jar.values()745+ assert values == list(values)746+ # make sure one can use values multiple times747+ assert list(values) == list(values)748+749+ def test_cookie_as_dict_items(self):750+ key = 'some_cookie'751+ value = 'some_value'752+753+ key1 = 'some_cookie1'754+ value1 = 'some_value1'755+756+ jar = requests.cookies.RequestsCookieJar()757+ jar.set(key, value)758+ jar.set(key1, value1)759+760+ items = jar.items()761+ assert items == list(items)762+ # make sure one can use items multiple times763+ assert list(items) == list(items)764+765+ def test_time_elapsed_blank(self, httpbin):766+ r = requests.get(httpbin('get'))767+ td = r.elapsed768+ total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)769+ * 10**6) / 10**6)770+ assert total_seconds > 0.0771+772+ def test_response_is_iterable(self):773+ r = requests.Response()774+ io = StringIO.StringIO('abc')775+ read_ = io.read776+777+ def read_mock(amt, decode_content=None):778+ return read_(amt)779+ setattr(io, 'read', read_mock)780+ r.raw = io781+ assert next(iter(r))782+ io.close()783+784+ def test_response_decode_unicode(self):785+ """786+ When called with decode_unicode, Response.iter_content should always787+ return unicode.788+ """789+ r = requests.Response()790+ r._content_consumed = True791+ r._content = b'the content'792+ r.encoding = 'ascii'793+794+ chunks = r.iter_content(decode_unicode=True)795+ assert all(isinstance(chunk, str) for chunk in chunks)796+797+ # also for streaming798+ r = requests.Response()799+ r.raw = io.BytesIO(b'the content')800+ r.encoding = 'ascii'801+ chunks = r.iter_content(decode_unicode=True)802+ assert all(isinstance(chunk, str) for chunk in chunks)803+804+ def test_request_and_response_are_pickleable(self, httpbin):805+ r = requests.get(httpbin('get'))806+807+ # verify we can pickle the original request808+ assert pickle.loads(pickle.dumps(r.request))809+810+ # verify we can pickle the response and that we have access to811+ # the original request.812+ pr = pickle.loads(pickle.dumps(r))813+ assert r.request.url == pr.request.url814+ assert r.request.headers == pr.request.headers815+816+ def test_cannot_send_unprepared_requests(self, httpbin):817+ r = requests.Request(url=httpbin())818+ with pytest.raises(ValueError):819+ requests.Session().send(r)820+821+ 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 == response830+831+ def test_session_pickling(self, httpbin):832+ r = requests.Request('GET', httpbin('get'))833+ s = requests.Session()834+835+ s = pickle.loads(pickle.dumps(s))836+ s.proxies = getproxies()837+838+ r = s.send(r.prepare())839+ assert r.status_code == 200840+841+ def test_fixes_1329(self, httpbin):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'853+854+ def test_uppercase_scheme_redirect(self, httpbin):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()860+861+ 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.adapters898+899+ def test_header_remove_is_case_insensitive(self, httpbin):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.headers905+906+ def test_params_are_merged_case_sensitive(self, httpbin):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'}911+912+ 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 == url920+921+ def test_header_keys_are_native(self, httpbin):922+ headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}923+ r = requests.Request('GET', httpbin('get'), headers=headers)924+ p = r.prepare()925+926+ # 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()930+931+ @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))932+ def test_can_send_objects_with_files(self, httpbin, files):933+ data = {'a': 'this is a string'}934+ files = {'b': files}935+ r = requests.Request('POST', httpbin('post'), data=data, files=files)936+ p = r.prepare()937+ assert 'multipart/form-data' in p.headers['Content-Type']938+939+ def test_can_send_file_object_with_non_string_filename(self, httpbin):940+ f = io.BytesIO()941+ f.name = 2942+ r = requests.Request('POST', httpbin('post'), files={'f': f})943+ p = r.prepare()944+945+ assert 'multipart/form-data' in p.headers['Content-Type']946+947+ def test_autoset_header_values_are_native(self, httpbin):948+ data = 'this is a string'949+ length = '16'950+ req = requests.Request('POST', httpbin('post'), data=data)951+ p = req.prepare()952+953+ assert p.headers['Content-Length'] == length954+955+ def test_nonhttp_schemes_dont_check_URLs(self):956+ test_urls = (957+ 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',958+ 'file:///etc/passwd',959+ 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',960+ )961+ for test_url in test_urls:962+ req = requests.Request('GET', test_url)963+ preq = req.prepare()964+ assert test_url == preq.url965+966+ def test_auth_is_stripped_on_redirect_off_host(self, httpbin):967+ r = requests.get(968+ httpbin('redirect-to'),969+ params={'url': 'http://www.google.co.uk'},970+ auth=('user', 'pass'),971+ )972+ assert r.history[0].request.headers['Authorization']973+ assert not r.request.headers.get('Authorization', '')974+975+ def test_auth_is_retained_for_redirect_on_host(self, httpbin):976+ r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))977+ h1 = r.history[0].request.headers['Authorization']978+ h2 = r.request.headers['Authorization']979+980+ assert h1 == h2981+982+ def test_manual_redirect_with_partial_body_read(self, httpbin):983+ s = requests.Session()984+ r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)985+ assert r1.is_redirect986+ rg = s.resolve_redirects(r1, r1.request, stream=True)987+988+ # read only the first eight bytes of the response body,989+ # then follow the redirect990+ r1.iter_content(8)991+ r2 = next(rg)992+ assert r2.is_redirect993+994+ # read all of the response via iter_content,995+ # then follow the redirect996+ for _ in r2.iter_content():997+ pass998+ r3 = next(rg)999+ assert not r3.is_redirect1000+1001+ def _patch_adapter_gzipped_redirect(self, session, url):1002+ adapter = session.get_adapter(url=url)1003+ org_build_response = adapter.build_response1004+ self._patched_response = False1005+1006+ def build_response(*args, **kwargs):1007+ resp = org_build_response(*args, **kwargs)1008+ if not self._patched_response:1009+ resp.raw.headers['content-encoding'] = 'gzip'1010+ self._patched_response = True1011+ return resp1012+1013+ adapter.build_response = build_response1014+1015+ def test_redirect_with_wrong_gzipped_header(self, httpbin):1016+ s = requests.Session()1017+ url = httpbin('redirect/1')1018+ self._patch_adapter_gzipped_redirect(s, url)1019+ s.get(url)1020+1021+ def test_basic_auth_str_is_always_native(self):1022+ s = _basic_auth_str("test", "test")1023+ assert isinstance(s, builtin_str)1024+ assert s == "Basic dGVzdDp0ZXN0"1025+1026+ def test_requests_history_is_saved(self, httpbin):1027+ r = requests.get(httpbin('redirect/5'))1028+ total = r.history[-1].history1029+ i = 01030+ for item in r.history:1031+ assert item.history == total[0:i]1032+ i += 11033+1034+ def test_json_param_post_content_type_works(self, httpbin):1035+ r = requests.post(1036+ httpbin('post'),1037+ json={'life': 42}1038+ )1039+ assert r.status_code == 2001040+ assert 'application/json' in r.request.headers['Content-Type']1041+ assert {'life': 42} == r.json()['json']1042+1043+ def test_json_param_post_should_not_override_data_param(self, httpbin):1044+ r = requests.Request(method='POST', url=httpbin('post'),1045+ data={'stuff': 'elixr'},1046+ json={'music': 'flute'})1047+ prep = r.prepare()1048+ assert 'stuff=elixr' == prep.body1049+1050+ def test_response_iter_lines(self, httpbin):1051+ r = requests.get(httpbin('stream/4'), stream=True)1052+ assert r.status_code == 2001053+1054+ it = r.iter_lines()1055+ next(it)1056+ assert len(list(it)) == 31057+1058+ def test_unconsumed_session_response_closes_connection(self, httpbin):1059+ s = requests.session()1060+1061+ with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1062+ pass1063+1064+ assert response._content_consumed is False1065+ assert response.raw.closed1066+1067+ @pytest.mark.xfail1068+ def test_response_iter_lines_reentrant(self, httpbin):1069+ """Response.iter_lines() is not reentrant safe"""1070+ r = requests.get(httpbin('stream/4'), stream=True)1071+ assert r.status_code == 2001072+1073+ next(r.iter_lines())1074+ assert len(list(r.iter_lines())) == 31075+1076+1077+class TestCaseInsensitiveDict:1078+1079+ @pytest.mark.parametrize(1080+ 'cid', (1081+ CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1082+ CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1083+ CaseInsensitiveDict(FOO='foo', BAr='bar'),1084+ )1085+ )1086+ def test_init(self, cid):1087+ assert len(cid) == 21088+ assert 'foo' in cid1089+ assert 'bar' in cid1090+1091+ def test_docstring_example(self):1092+ cid = CaseInsensitiveDict()1093+ cid['Accept'] = 'application/json'1094+ assert cid['aCCEPT'] == 'application/json'1095+ assert list(cid) == ['Accept']1096+1097+ def test_len(self):1098+ cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1099+ cid['A'] = 'a'1100+ assert len(cid) == 21101+1102+ def test_getitem(self):1103+ cid = CaseInsensitiveDict({'Spam': 'blueval'})1104+ assert cid['spam'] == 'blueval'1105+ assert cid['SPAM'] == 'blueval'1106+1107+ def test_fixes_649(self):1108+ """__setitem__ should behave case-insensitively."""1109+ cid = CaseInsensitiveDict()1110+ cid['spam'] = 'oneval'1111+ cid['Spam'] = 'twoval'1112+ cid['sPAM'] = 'redval'1113+ cid['SPAM'] = 'blueval'1114+ assert cid['spam'] == 'blueval'1115+ assert cid['SPAM'] == 'blueval'1116+ assert list(cid.keys()) == ['SPAM']1117+1118+ def test_delitem(self):1119+ cid = CaseInsensitiveDict()1120+ cid['Spam'] = 'someval'1121+ del cid['sPam']1122+ assert 'spam' not in cid1123+ assert len(cid) == 01124+1125+ def test_contains(self):1126+ cid = CaseInsensitiveDict()1127+ cid['Spam'] = 'someval'1128+ assert 'Spam' in cid1129+ assert 'spam' in cid1130+ assert 'SPAM' in cid1131+ assert 'sPam' in cid1132+ assert 'notspam' not in cid1133+1134+ def test_get(self):1135+ cid = CaseInsensitiveDict()1136+ cid['spam'] = 'oneval'1137+ cid['SPAM'] = 'blueval'1138+ assert cid.get('spam') == 'blueval'1139+ assert cid.get('SPAM') == 'blueval'1140+ assert cid.get('sPam') == 'blueval'1141+ assert cid.get('notspam', 'default') == 'default'1142+1143+ def test_update(self):1144+ cid = CaseInsensitiveDict()1145+ cid['spam'] = 'blueval'1146+ cid.update({'sPam': 'notblueval'})1147+ assert cid['spam'] == 'notblueval'1148+ cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1149+ cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1150+ assert len(cid) == 21151+ assert cid['foo'] == 'anotherfoo'1152+ assert cid['bar'] == 'anotherbar'1153+1154+ def test_update_retains_unchanged(self):1155+ cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1156+ cid.update({'foo': 'newfoo'})1157+ assert cid['bar'] == 'bar'1158+1159+ def test_iter(self):1160+ cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1161+ keys = frozenset(['Spam', 'Eggs'])1162+ assert frozenset(iter(cid)) == keys1163+1164+ def test_equality(self):1165+ cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1166+ othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1167+ assert cid == othercid1168+ del othercid['spam']1169+ assert cid != othercid1170+ assert cid == {'spam': 'blueval', 'eggs': 'redval'}1171+ assert cid != object()1172+1173+ def test_setdefault(self):1174+ cid = CaseInsensitiveDict({'Spam': 'blueval'})1175+ assert cid.setdefault('spam', 'notblueval') == 'blueval'1176+ assert cid.setdefault('notspam', 'notblueval') == 'notblueval'1177+1178+ def test_lower_items(self):1179+ cid = CaseInsensitiveDict({1180+ 'Accept': 'application/json',1181+ 'user-Agent': 'requests',1182+ })1183+ keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1184+ lowerkeyset = frozenset(['accept', 'user-agent'])1185+ assert keyset == lowerkeyset1186+1187+ def test_preserve_key_case(self):1188+ cid = CaseInsensitiveDict({1189+ 'Accept': 'application/json',1190+ 'user-Agent': 'requests',1191+ })1192+ keyset = frozenset(['Accept', 'user-Agent'])1193+ assert frozenset(i[0] for i in cid.items()) == keyset1194+ assert frozenset(cid.keys()) == keyset1195+ assert frozenset(cid) == keyset1196+1197+ def test_preserve_last_key_case(self):1198+ cid = CaseInsensitiveDict({1199+ 'Accept': 'application/json',1200+ 'user-Agent': 'requests',1201+ })1202+ cid.update({'ACCEPT': 'application/json'})1203+ cid['USER-AGENT'] = 'requests'1204+ keyset = frozenset(['ACCEPT', 'USER-AGENT'])1205+ assert frozenset(i[0] for i in cid.items()) == keyset1206+ assert frozenset(cid.keys()) == keyset1207+ assert frozenset(cid) == keyset1208+1209+ def test_copy(self):1210+ cid = CaseInsensitiveDict({1211+ 'Accept': 'application/json',1212+ 'user-Agent': 'requests',1213+ })1214+ cid_copy = cid.copy()1215+ assert cid == cid_copy1216+ cid['changed'] = True1217+ assert cid != cid_copy1218+1219+1220+class TestMorselToCookieExpires:1221+ """Tests for morsel_to_cookie when morsel contains expires."""1222+1223+ def test_expires_valid_str(self):1224+ """Test case where we convert expires from string time."""1225+1226+ morsel = Morsel()1227+ morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1228+ cookie = morsel_to_cookie(morsel)1229+ assert cookie.expires == 11230+1231+ @pytest.mark.parametrize(1232+ 'value, exception', (1233+ (100, TypeError),1234+ ('woops', ValueError),1235+ )1236+ )1237+ def test_expires_invalid_int(self, value, exception):1238+ """Test case where an invalid type is passed for expires."""1239+ morsel = Morsel()1240+ morsel['expires'] = value1241+ with pytest.raises(exception):1242+ morsel_to_cookie(morsel)1243+1244+ def test_expires_none(self):1245+ """Test case where expires is None."""1246+1247+ morsel = Morsel()1248+ morsel['expires'] = None1249+ cookie = morsel_to_cookie(morsel)1250+ assert cookie.expires is None1251+1252+1253+class TestMorselToCookieMaxAge:1254+1255+ """Tests for morsel_to_cookie when morsel contains max-age."""1256+1257+ def test_max_age_valid_int(self):1258+ """Test case where a valid max age in seconds is passed."""1259+1260+ morsel = Morsel()1261+ morsel['max-age'] = 601262+ cookie = morsel_to_cookie(morsel)1263+ assert isinstance(cookie.expires, int)1264+1265+ def test_max_age_invalid_str(self):1266+ """Test case where a invalid max age is passed."""1267+1268+ morsel = Morsel()1269+ morsel['max-age'] = 'woops'1270+ with pytest.raises(TypeError):1271+ morsel_to_cookie(morsel)1272+1273+1274+class TestTimeout:1275+1276+ def test_stream_timeout(self, httpbin):1277+ try:1278+ requests.get(httpbin('delay/10'), timeout=2.0)1279+ except requests.exceptions.Timeout as e:1280+ assert 'Read timed out' in e.args[0].args[0]1281+1282+ @pytest.mark.parametrize(1283+ 'timeout, error_text', (1284+ ((3, 4, 5), '(connect, read)'),1285+ ('foo', 'must be an int or float'),1286+ )1287+ )1288+ def test_invalid_timeout(self, httpbin, timeout, error_text):1289+ with pytest.raises(ValueError) as e:1290+ requests.get(httpbin('get'), timeout=timeout)1291+ assert error_text in str(e)1292+1293+ def test_none_timeout(self, httpbin):1294+ """ Check that you can set None as a valid timeout value.1295+1296+ To actually test this behavior, we'd want to check that setting the1297+ timeout to None actually lets the request block past the system default1298+ timeout. However, this would make the test suite unbearably slow.1299+ Instead we verify that setting the timeout to None does not prevent the1300+ request from succeeding.1301+ """1302+ r = requests.get(httpbin('get'), timeout=None)1303+ assert r.status_code == 2001304+1305+ def test_read_timeout(self, httpbin):1306+ try:1307+ requests.get(httpbin('delay/10'), timeout=(None, 0.1))1308+ pytest.fail('The recv() request should time out.')1309+ except ReadTimeout:1310+ pass1311+1312+ def test_connect_timeout(self):1313+ try:1314+ requests.get(TARPIT, timeout=(0.1, None))1315+ pytest.fail('The connect() request should time out.')1316+ except ConnectTimeout as e:1317+ assert isinstance(e, ConnectionError)1318+ assert isinstance(e, Timeout)1319+1320+ def test_total_timeout_connect(self):1321+ try:1322+ requests.get(TARPIT, timeout=(0.1, 0.1))1323+ pytest.fail('The connect() request should time out.')1324+ except ConnectTimeout:1325+ pass1326+1327+ def test_encoded_methods(self, httpbin):1328+ """See: https://github.com/kennethreitz/requests/issues/2316"""1329+ r = requests.request(b'GET', httpbin('get'))1330+ assert r.ok1331+1332+1333+SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))1334+1335+1336+class RedirectSession(SessionRedirectMixin):1337+ def __init__(self, order_of_redirects):1338+ self.redirects = order_of_redirects1339+ self.calls = []1340+ self.max_redirects = 301341+ self.cookies = {}1342+ self.trust_env = False1343+1344+ def send(self, *args, **kwargs):1345+ self.calls.append(SendCall(args, kwargs))1346+ return self.build_response()1347+1348+ def build_response(self):1349+ request = self.calls[-1].args[0]1350+ r = requests.Response()1351+1352+ try:1353+ r.status_code = int(self.redirects.pop(0))1354+ except IndexError:1355+ r.status_code = 2001356+1357+ r.headers = CaseInsensitiveDict({'Location': '/'})1358+ r.raw = self._build_raw()1359+ r.request = request1360+ return r1361+1362+ def _build_raw(self):1363+ string = StringIO.StringIO('')1364+ setattr(string, 'release_conn', lambda *args: args)1365+ return string1366+1367+1368+def test_requests_are_updated_each_time(httpbin):1369+ session = RedirectSession([303, 307])1370+ prep = requests.Request('POST', httpbin('post')).prepare()1371+ r0 = session.send(prep)1372+ assert r0.request.method == 'POST'1373+ assert session.calls[-1] == SendCall((r0.request,), {})1374+ redirect_generator = session.resolve_redirects(r0, prep)1375+ default_keyword_args = {1376+ 'stream': False,1377+ 'verify': True,1378+ 'cert': None,1379+ 'timeout': None,1380+ 'allow_redirects': False,1381+ 'proxies': {},1382+ }1383+ for response in redirect_generator:1384+ assert response.request.method == 'GET'1385+ send_call = SendCall((response.request,), default_keyword_args)1386+ assert session.calls[-1] == send_call1387+1388+1389+@pytest.mark.parametrize(1390+ 'data', (1391+ (('a', 'b'), ('c', 'd')),1392+ (('c', 'd'), ('a', 'b')),1393+ (('a', 'b'), ('c', 'd'), ('e', 'f')),1394+ )1395+)1396+def test_data_argument_accepts_tuples(data):1397+ """Ensure that the data argument will accept tuples of strings1398+ and properly encode them.1399+ """1400+ p = PreparedRequest()1401+ p.prepare(1402+ method='GET',1403+ url='http://www.example.com',1404+ data=data,1405+ hooks=default_hooks()1406+ )1407+ assert p.body == urlencode(data)1408+1409+1410+@pytest.mark.parametrize(1411+ 'kwargs', (1412+ None,1413+ {1414+ 'method': 'GET',1415+ 'url': 'http://www.example.com',1416+ 'data': 'foo=bar',1417+ 'hooks': default_hooks()1418+ },1419+ {1420+ 'method': 'GET',1421+ 'url': 'http://www.example.com',1422+ 'data': 'foo=bar',1423+ 'hooks': default_hooks(),1424+ 'cookies': {'foo': 'bar'}1425+ },1426+ {1427+ 'method': 'GET',1428+ 'url': u('http://www.example.com/üniçø∂é')1429+ },1430+ )1431+)1432+def test_prepared_copy(kwargs):1433+ p = PreparedRequest()1434+ if kwargs:1435+ p.prepare(**kwargs)1436+ copy = p.copy()1437+ for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1438+ assert getattr(p, attr) == getattr(copy, attr)1439+1440+1441+def test_urllib3_retries(httpbin):1442+ from requests.packages.urllib3.util import Retry1443+ s = requests.Session()1444+ s.mount('http://', HTTPAdapter(max_retries=Retry(1445+ total=2, status_forcelist=[500]1446+ )))1447+1448+ with pytest.raises(RetryError):1449+ s.get(httpbin('status/500'))1450+1451+1452+def test_urllib3_pool_connection_closed(httpbin):1453+ s = requests.Session()1454+ s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))1455+1456+ try:1457+ s.get(httpbin('status/200'))1458+ except ConnectionError as e:1459+ assert u"Pool is closed." in str(e)1460+1461+1462+def test_vendor_aliases():1463+ from requests.packages import urllib31464+ from requests.packages import chardet1465+1466+ with pytest.raises(ImportError):1467+ from requests.packages import webbrowseradded:tests/test_utils.py+242 added
1+# coding: utf-82+import os3+from io import BytesIO4+5+import pytest6+from requests import compat7+from requests.utils import (8+ address_in_network, dotted_netmask,9+ get_auth_from_url, get_encodings_from_content,10+ get_environ_proxies, guess_filename,11+ is_ipv4_address, is_valid_cidr, requote_uri,12+ select_proxy, super_len)13+14+from .compat import StringIO, cStringIO15+16+17+class TestSuperLen:18+19+ @pytest.mark.parametrize(20+ 'stream, value', (21+ (StringIO.StringIO, 'Test'),22+ (BytesIO, b'Test'),23+ pytest.mark.skipif('cStringIO is None')(24+ (cStringIO, 'Test')25+ ),26+ ))27+ def test_io_streams(self, stream, value):28+ """ Ensures that we properly deal with different kinds of IO streams. """29+ assert super_len(stream()) == 030+ assert super_len(stream(value)) == 431+32+ def test_super_len_correctly_calculates_len_of_partially_read_file(self):33+ """Ensure that we handle partially consumed file like objects."""34+ s = StringIO.StringIO()35+ s.write('foobarbogus')36+ assert super_len(s) == 037+38+39+class TestGetEnvironProxies:40+ """Ensures that IP addresses are correctly matches with ranges41+ in no_proxy variable."""42+43+ @pytest.yield_fixture(scope='class', autouse=True, params=['no_proxy', 'NO_PROXY'])44+ def no_proxy(self, request):45+ os.environ[request.param] = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'46+ yield47+ del os.environ[request.param]48+49+ @pytest.mark.parametrize(50+ 'url', (51+ 'http://192.168.0.1:5000/',52+ 'http://192.168.0.1/',53+ 'http://172.16.1.1/',54+ 'http://172.16.1.1:5000/',55+ 'http://localhost.localdomain:5000/v1.0/',56+ )57+ )58+ def test_bypass(self, url):59+ assert get_environ_proxies(url) == {}60+61+ @pytest.mark.parametrize(62+ 'url', (63+ 'http://192.168.1.1:5000/',64+ 'http://192.168.1.1/',65+ 'http://www.requests.com/',66+ )67+ )68+ def test_not_bypass(self, url):69+ assert get_environ_proxies(url) != {}70+71+72+class TestIsIPv4Address:73+74+ def test_valid(self):75+ assert is_ipv4_address('8.8.8.8')76+77+ @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))78+ def test_invalid(self, value):79+ assert not is_ipv4_address(value)80+81+82+class TestIsValidCIDR:83+84+ def test_valid(self):85+ assert is_valid_cidr('192.168.1.0/24')86+87+ @pytest.mark.parametrize(88+ 'value', (89+ '8.8.8.8',90+ '192.168.1.0/a',91+ '192.168.1.0/128',92+ '192.168.1.0/-1',93+ '192.168.1.999/24',94+ )95+ )96+ def test_invalid(self, value):97+ assert not is_valid_cidr(value)98+99+100+class TestAddressInNetwork:101+102+ def test_valid(self):103+ assert address_in_network('192.168.1.1', '192.168.1.0/24')104+105+ def test_invalid(self):106+ assert not address_in_network('172.16.0.1', '192.168.1.0/24')107+108+109+class TestGuessFilename:110+111+ @pytest.mark.parametrize(112+ 'value', (1, type('Fake', (object,), {'name': 1})()),113+ )114+ def test_guess_filename_invalid(self, value):115+ assert guess_filename(value) is None116+117+ @pytest.mark.parametrize(118+ 'value, expected_type', (119+ (b'value', compat.bytes),120+ (b'value'.decode('utf-8'), compat.str)121+ )122+ )123+ def test_guess_filename_valid(self, value, expected_type):124+ obj = type('Fake', (object,), {'name': value})()125+ result = guess_filename(obj)126+ assert result == value127+ assert isinstance(result, expected_type)128+129+130+class TestContentEncodingDetection:131+132+ def test_none(self):133+ encodings = get_encodings_from_content('')134+ assert not len(encodings)135+136+ @pytest.mark.parametrize(137+ 'content', (138+ # HTML5 meta charset attribute139+ '<meta charset="UTF-8">',140+ # HTML4 pragma directive141+ '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',142+ # XHTML 1.x served with text/html MIME type143+ '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',144+ # XHTML 1.x served as XML145+ '<?xml version="1.0" encoding="UTF-8"?>',146+ )147+ )148+ def test_pragmas(self, content):149+ encodings = get_encodings_from_content(content)150+ assert len(encodings) == 1151+ assert encodings[0] == 'UTF-8'152+153+ def test_precedence(self):154+ content = '''155+ <?xml version="1.0" encoding="XML"?>156+ <meta charset="HTML5">157+ <meta http-equiv="Content-type" content="text/html;charset=HTML4" />158+ '''.strip()159+ assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']160+161+162+USER = PASSWORD = "%!*'();:@&=+$,/?#[] "163+ENCODED_USER = compat.quote(USER, '')164+ENCODED_PASSWORD = compat.quote(PASSWORD, '')165+166+167+@pytest.mark.parametrize(168+ 'url, auth', (169+ (170+ 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +171+ 'request.com/url.html#test',172+ (USER, PASSWORD)173+ ),174+ (175+ 'http://user:pass@complex.url.com/path?query=yes',176+ ('user', 'pass')177+ ),178+ (179+ 'http://user:pass%20pass@complex.url.com/path?query=yes',180+ ('user', 'pass pass')181+ ),182+ (183+ 'http://user:pass pass@complex.url.com/path?query=yes',184+ ('user', 'pass pass')185+ ),186+ (187+ 'http://user%25user:pass@complex.url.com/path?query=yes',188+ ('user%user', 'pass')189+ ),190+ (191+ 'http://user:pass%23pass@complex.url.com/path?query=yes',192+ ('user', 'pass#pass')193+ ),194+ )195+)196+def test_get_auth_from_url(url, auth):197+ assert get_auth_from_url(url) == auth198+199+200+@pytest.mark.parametrize(201+ 'uri, expected', (202+ (203+ # Ensure requoting doesn't break expectations204+ 'http://example.com/fiz?buz=%25ppicture',205+ 'http://example.com/fiz?buz=%25ppicture',206+ ),207+ (208+ # Ensure we handle unquoted percent signs in redirects209+ 'http://example.com/fiz?buz=%ppicture',210+ 'http://example.com/fiz?buz=%25ppicture',211+ ),212+ )213+)214+def test_requote_uri_with_unquoted_percents(uri, expected):215+ """See: https://github.com/kennethreitz/requests/issues/2356216+ """217+ assert requote_uri(uri) == expected218+219+220+@pytest.mark.parametrize(221+ 'mask, expected', (222+ (8, '255.0.0.0'),223+ (24, '255.255.255.0'),224+ (25, '255.255.255.128'),225+ )226+)227+def test_dotted_netmask(mask, expected):228+ assert dotted_netmask(mask) == expected229+230+231+@pytest.mark.parametrize(232+ 'url, expected', (233+ ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy'),234+ ('hTTp://u:p@Other.Host/path', 'http://http.proxy'),235+ ('hTTps://Other.Host', None),236+ )237+)238+def test_select_proxies(url, expected):239+ """Make sure we can select per-host proxies correctly."""240+ proxies = {'http': 'http://http.proxy',241+ 'http://some.host': 'http://some.host.proxy'}242+ assert select_proxy(url, proxies) == expectedmodified:Makefile+2 added-2 removed
4 unmodified lines5 6 test:7 # This runs all of the tests. To run an individual test, run py.test with8 # the -k flag, like "py.test -k test_path_is_not_double_encoded"9- py.test test_requests.py9+ py.test tests10 11 coverage:12- py.test --verbose --cov-report term --cov=requests test_requests.py12+ py.test --verbose --cov-report term --cov=requests tests13 14 ci: init15 py.test --junitxml=junit.xml16 23 unmodified linesdeleted:test_requests.py-1725 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-4-"""Tests for Requests."""5-6-from __future__ import division7-import json8-import os9-import pickle10-import collections11-import contextlib12-13-import io14-import requests15-import pytest16-from requests.adapters import HTTPAdapter17-from requests.auth import HTTPDigestAuth, _basic_auth_str18-from requests.compat import (19- Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3,20- builtin_str, OrderedDict)21-from requests.cookies import cookiejar_from_dict, morsel_to_cookie22-from requests.exceptions import (23- ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,24- MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects)25-from requests.models import PreparedRequest26-from requests.structures import CaseInsensitiveDict27-from requests.sessions import SessionRedirectMixin28-from requests.models import urlencode29-from requests.hooks import default_hooks30-31-try:32- import StringIO33-except ImportError:34- import io as StringIO35-36-try:37- from multiprocessing.pool import ThreadPool38-except ImportError:39- ThreadPool = None40-41-if is_py3:42- def u(s):43- return s44-else:45- def u(s):46- return s.decode('unicode-escape')47-48-49-@pytest.fixture50-def httpbin(httpbin):51- # Issue #1483: Make sure the URL always has a trailing slash52- httpbin_url = httpbin.url.rstrip('/') + '/'53-54- def inner(*suffix):55- return urljoin(httpbin_url, '/'.join(suffix))56-57- return inner58-59-60-@pytest.fixture61-def httpsbin_url(httpbin_secure):62- # Issue #1483: Make sure the URL always has a trailing slash63- httpbin_url = httpbin_secure.url.rstrip('/') + '/'64-65- def inner(*suffix):66- return urljoin(httpbin_url, '/'.join(suffix))67-68- return inner69-70-71-# Requests to this URL should always fail with a connection timeout (nothing72-# listening on that port)73-TARPIT = "http://10.255.255.1"74-75-76-class TestRequests:77-78- def test_entry_points(self):79-80- requests.session81- requests.session().get82- requests.session().head83- requests.get84- requests.head85- requests.put86- requests.patch87- requests.post88-89- @pytest.mark.parametrize('exception, url',90- (91- (MissingSchema, 'hiwpefhipowhefopw'),92- (InvalidSchema, 'localhost:3128'),93- (InvalidSchema, 'localhost.localdomain:3128/'),94- (InvalidSchema, '10.122.1.1:3128/'),95- (InvalidURL, 'http://'),96- )97- )98- def test_invalid_url(self, exception, url):99- with pytest.raises(exception):100- requests.get(url)101-102- def test_basic_building(self):103- req = requests.Request()104- req.url = 'http://kennethreitz.org/'105- req.data = {'life': '42'}106-107- pr = req.prepare()108- assert pr.url == req.url109- assert pr.body == 'life=42'110-111- @pytest.mark.parametrize('method', ('GET', 'HEAD'))112- def test_no_content_length(self, httpbin, method):113- req = requests.Request(method, httpbin(method.lower())).prepare()114- assert 'Content-Length' not in req.headers115-116- def test_override_content_length(self, httpbin):117- headers = {118- 'Content-Length': 'not zero'119- }120- r = requests.Request('POST', httpbin('post'), headers=headers).prepare()121- assert 'Content-Length' in r.headers122- assert r.headers['Content-Length'] == 'not zero'123-124- def test_path_is_not_double_encoded(self):125- request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()126-127- assert request.path_url == '/get/test%20case'128-129- @pytest.mark.parametrize('url, expected',130- (131- ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),132- ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')133- )134- )135- def test_params_are_added_before_fragment(self, url, expected):136- request = requests.Request('GET', url, params={"a": "b"}).prepare()137- assert request.url == expected138-139- def test_params_original_order_is_preserved_by_default(self):140- param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))141- session = requests.Session()142- request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)143- prep = session.prepare_request(request)144- assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'145-146- def test_params_bytes_are_encoded(self):147- request = requests.Request('GET', 'http://example.com',148- params=b'test=foo').prepare()149- assert request.url == 'http://example.com/?test=foo'150-151- def test_binary_put(self):152- request = requests.Request('PUT', 'http://example.com',153- data=u"ööö".encode("utf-8")).prepare()154- assert isinstance(request.body, bytes)155-156- @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))157- def test_mixed_case_scheme_acceptable(self, httpbin, scheme):158- s = requests.Session()159- s.proxies = getproxies()160- parts = urlparse(httpbin('get'))161- url = scheme + parts.netloc + parts.path162- r = requests.Request('GET', url)163- r = s.send(r.prepare())164- assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)165-166- def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):167- r = requests.Request('GET', httpbin('get'))168- s = requests.Session()169- s.proxies = getproxies()170-171- r = s.send(r.prepare())172-173- assert r.status_code == 200174-175- def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):176- r = requests.get(httpbin('redirect', '1'))177- assert r.status_code == 200178- assert r.history[0].status_code == 302179- assert r.history[0].is_redirect180-181- def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):182- try:183- requests.get(httpbin('relative-redirect', '50'))184- except TooManyRedirects as e:185- url = httpbin('relative-redirect', '20')186- assert e.request.url == url187- assert e.response.url == url188- assert len(e.response.history) == 30189- else:190- pytest.fail('Expected redirect to raise TooManyRedirects but it did not')191-192- def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):193- s = requests.session()194- s.max_redirects = 5195- try:196- s.get(httpbin('relative-redirect', '50'))197- except TooManyRedirects as e:198- url = httpbin('relative-redirect', '45')199- assert e.request.url == url200- assert e.response.url == url201- assert len(e.response.history) == 5202- else:203- pytest.fail('Expected custom max number of redirects to be respected but was not')204-205- # def test_HTTP_302_ALLOW_REDIRECT_POST(self):206- # r = requests.post(httpbin('status', '302'), data={'some': 'data'})207- # self.assertEqual(r.status_code, 200)208-209- def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):210- heads = {'User-agent': 'Mozilla/5.0'}211-212- r = requests.get(httpbin('user-agent'), headers=heads)213-214- assert heads['User-agent'] in r.text215- assert r.status_code == 200216-217- def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):218- heads = {'User-agent': 'Mozilla/5.0'}219-220- r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)221- assert r.status_code == 200222-223- def test_set_cookie_on_301(self, httpbin):224- s = requests.session()225- url = httpbin('cookies/set?foo=bar')226- s.get(url)227- assert s.cookies['foo'] == 'bar'228-229- def test_cookie_sent_on_redirect(self, httpbin):230- s = requests.session()231- s.get(httpbin('cookies/set?foo=bar'))232- r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')233- assert 'Cookie' in r.json()['headers']234-235- def test_cookie_removed_on_expire(self, httpbin):236- s = requests.session()237- s.get(httpbin('cookies/set?foo=bar'))238- assert s.cookies['foo'] == 'bar'239- s.get(240- httpbin('response-headers'),241- params={242- 'Set-Cookie':243- 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'244- }245- )246- assert 'foo' not in s.cookies247-248- def test_cookie_quote_wrapped(self, httpbin):249- s = requests.session()250- s.get(httpbin('cookies/set?foo="bar:baz"'))251- assert s.cookies['foo'] == '"bar:baz"'252-253- def test_cookie_persists_via_api(self, httpbin):254- s = requests.session()255- r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})256- assert 'foo' in r.request.headers['Cookie']257- assert 'foo' in r.history[0].request.headers['Cookie']258-259- def test_request_cookie_overrides_session_cookie(self, httpbin):260- s = requests.session()261- s.cookies['foo'] = 'bar'262- r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})263- assert r.json()['cookies']['foo'] == 'baz'264- # Session cookie should not be modified265- assert s.cookies['foo'] == 'bar'266-267- def test_request_cookies_not_persisted(self, httpbin):268- s = requests.session()269- s.get(httpbin('cookies'), cookies={'foo': 'baz'})270- # Sending a request with cookies should not add cookies to the session271- assert not s.cookies272-273- def test_generic_cookiejar_works(self, httpbin):274- cj = cookielib.CookieJar()275- cookiejar_from_dict({'foo': 'bar'}, cj)276- s = requests.session()277- s.cookies = cj278- r = s.get(httpbin('cookies'))279- # Make sure the cookie was sent280- assert r.json()['cookies']['foo'] == 'bar'281- # Make sure the session cj is still the custom one282- assert s.cookies is cj283-284- def test_param_cookiejar_works(self, httpbin):285- cj = cookielib.CookieJar()286- cookiejar_from_dict({'foo': 'bar'}, cj)287- s = requests.session()288- r = s.get(httpbin('cookies'), cookies=cj)289- # Make sure the cookie was sent290- assert r.json()['cookies']['foo'] == 'bar'291-292- def test_requests_in_history_are_not_overridden(self, httpbin):293- resp = requests.get(httpbin('redirect/3'))294- urls = [r.url for r in resp.history]295- req_urls = [r.request.url for r in resp.history]296- assert urls == req_urls297-298- def test_history_is_always_a_list(self, httpbin):299- """Show that even with redirects, Response.history is always a list."""300- resp = requests.get(httpbin('get'))301- assert isinstance(resp.history, list)302- resp = requests.get(httpbin('redirect/1'))303- assert isinstance(resp.history, list)304- assert not isinstance(resp.history, tuple)305-306- def test_headers_on_session_with_None_are_not_sent(self, httpbin):307- """Do not send headers in Session.headers with None values."""308- ses = requests.Session()309- ses.headers['Accept-Encoding'] = None310- req = requests.Request('GET', httpbin('get'))311- prep = ses.prepare_request(req)312- assert 'Accept-Encoding' not in prep.headers313-314- @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))315- def test_user_agent_transfers(self, httpbin, key):316-317- heads = {318- key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'319- }320-321- r = requests.get(httpbin('user-agent'), headers=heads)322- assert heads[key] in r.text323-324- def test_HTTP_200_OK_HEAD(self, httpbin):325- r = requests.head(httpbin('get'))326- assert r.status_code == 200327-328- def test_HTTP_200_OK_PUT(self, httpbin):329- r = requests.put(httpbin('put'))330- assert r.status_code == 200331-332- def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):333- auth = ('user', 'pass')334- url = httpbin('basic-auth', 'user', 'pass')335-336- r = requests.get(url, auth=auth)337- assert r.status_code == 200338-339- r = requests.get(url)340- assert r.status_code == 401341-342- s = requests.session()343- s.auth = auth344- r = s.get(url)345- assert r.status_code == 200346-347- @pytest.mark.parametrize('url, exception',348- (349- # Connecting to an unknown domain should raise a ConnectionError350- ('http://doesnotexist.google.com', ConnectionError),351- # Connecting to an invalid port should raise a ConnectionError352- ('http://localhost:1', ConnectionError),353- # Inputing a URL that cannot be parsed should raise an InvalidURL error354- ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)355- )356- )357- def test_errors(self, url, exception):358- with pytest.raises(exception):359- requests.get(url, timeout=1)360-361- def test_basicauth_with_netrc(self, httpbin):362- auth = ('user', 'pass')363- wrong_auth = ('wronguser', 'wrongpass')364- url = httpbin('basic-auth', 'user', 'pass')365-366- old_auth = requests.sessions.get_netrc_auth367-368- try:369- def get_netrc_auth_mock(url):370- return auth371- requests.sessions.get_netrc_auth = get_netrc_auth_mock372-373- # Should use netrc and work.374- r = requests.get(url)375- assert r.status_code == 200376-377- # Given auth should override and fail.378- r = requests.get(url, auth=wrong_auth)379- assert r.status_code == 401380-381- s = requests.session()382-383- # Should use netrc and work.384- r = s.get(url)385- assert r.status_code == 200386-387- # Given auth should override and fail.388- s.auth = wrong_auth389- r = s.get(url)390- assert r.status_code == 401391- finally:392- requests.sessions.get_netrc_auth = old_auth393-394- def test_DIGEST_HTTP_200_OK_GET(self, httpbin):395-396- auth = HTTPDigestAuth('user', 'pass')397- url = httpbin('digest-auth', 'auth', 'user', 'pass')398-399- r = requests.get(url, auth=auth)400- assert r.status_code == 200401-402- r = requests.get(url)403- assert r.status_code == 401404-405- s = requests.session()406- s.auth = HTTPDigestAuth('user', 'pass')407- r = s.get(url)408- assert r.status_code == 200409-410- def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):411- url = httpbin('digest-auth', 'auth', 'user', 'pass')412- auth = HTTPDigestAuth('user', 'pass')413- r = requests.get(url)414- assert r.cookies['fake'] == 'fake_value'415-416- r = requests.get(url, auth=auth)417- assert r.status_code == 200418-419- def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):420- url = httpbin('digest-auth', 'auth', 'user', 'pass')421- auth = HTTPDigestAuth('user', 'pass')422- s = requests.Session()423- s.get(url, auth=auth)424- assert s.cookies['fake'] == 'fake_value'425-426- def test_DIGEST_STREAM(self, httpbin):427-428- auth = HTTPDigestAuth('user', 'pass')429- url = httpbin('digest-auth', 'auth', 'user', 'pass')430-431- r = requests.get(url, auth=auth, stream=True)432- assert r.raw.read() != b''433-434- r = requests.get(url, auth=auth, stream=False)435- assert r.raw.read() == b''436-437- def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):438-439- auth = HTTPDigestAuth('user', 'wrongpass')440- url = httpbin('digest-auth', 'auth', 'user', 'pass')441-442- r = requests.get(url, auth=auth)443- assert r.status_code == 401444-445- r = requests.get(url)446- assert r.status_code == 401447-448- s = requests.session()449- s.auth = auth450- r = s.get(url)451- assert r.status_code == 401452-453- def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):454-455- auth = HTTPDigestAuth('user', 'pass')456- url = httpbin('digest-auth', 'auth', 'user', 'pass')457-458- r = requests.get(url, auth=auth)459- assert '"auth"' in r.request.headers['Authorization']460-461- def test_POSTBIN_GET_POST_FILES(self, httpbin):462-463- url = httpbin('post')464- requests.post(url).raise_for_status()465-466- post1 = requests.post(url, data={'some': 'data'})467- assert post1.status_code == 200468-469- with open('requirements.txt') as f:470- post2 = requests.post(url, files={'some': f})471- assert post2.status_code == 200472-473- post4 = requests.post(url, data='[{"some": "json"}]')474- assert post4.status_code == 200475-476- with pytest.raises(ValueError):477- requests.post(url, files=['bad file data'])478-479- def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):480-481- url = httpbin('post')482- requests.post(url).raise_for_status()483-484- post1 = requests.post(url, data={'some': 'data'})485- assert post1.status_code == 200486-487- with open('requirements.txt') as f:488- post2 = requests.post(url,489- data={'some': 'data'}, files={'some': f})490- assert post2.status_code == 200491-492- post4 = requests.post(url, data='[{"some": "json"}]')493- assert post4.status_code == 200494-495- with pytest.raises(ValueError):496- requests.post(url, files=['bad file data'])497-498- def test_conflicting_post_params(self, httpbin):499- url = httpbin('post')500- with open('requirements.txt') as f:501- pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")502- pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")503-504- def test_request_ok_set(self, httpbin):505- r = requests.get(httpbin('status', '404'))506- assert not r.ok507-508- def test_status_raising(self, httpbin):509- r = requests.get(httpbin('status', '404'))510- with pytest.raises(requests.exceptions.HTTPError):511- r.raise_for_status()512-513- r = requests.get(httpbin('status', '500'))514- assert not r.ok515-516- def test_decompress_gzip(self, httpbin):517- r = requests.get(httpbin('gzip'))518- r.content.decode('ascii')519-520- @pytest.mark.parametrize(521- 'url, params',522- (523- ('/get', {'foo': 'føø'}),524- ('/get', {'føø': 'føø'}),525- ('/get', {'føø': 'føø'}),526- ('/get', {'foo': 'foo'}),527- ('ø', {'foo': 'foo'}),528- )529- )530- def test_unicode_get(self, httpbin, url, params):531- requests.get(httpbin(url), params=params)532-533- def test_unicode_header_name(self, httpbin):534- requests.put(535- httpbin('put'),536- headers={str('Content-Type'): 'application/octet-stream'},537- data='\xff') # compat.str is unicode.538-539- def test_pyopenssl_redirect(self, httpsbin_url, httpbin_ca_bundle):540- requests.get(httpsbin_url('status', '301'), verify=httpbin_ca_bundle)541-542- def test_urlencoded_get_query_multivalued_param(self, httpbin):543-544- r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))545- assert r.status_code == 200546- assert r.url == httpbin('get?test=foo&test=baz')547-548- def test_different_encodings_dont_break_post(self, httpbin):549- r = requests.post(httpbin('post'),550- data={'stuff': json.dumps({'a': 123})},551- params={'blah': 'asdf1234'},552- files={'file': ('test_requests.py', open(__file__, 'rb'))})553- assert r.status_code == 200554-555- @pytest.mark.parametrize(556- 'data', (557- {'stuff': u('ëlïxr')},558- {'stuff': u('ëlïxr').encode('utf-8')},559- {'stuff': 'elixr'},560- {'stuff': 'elixr'.encode('utf-8')},561- )562- )563- def test_unicode_multipart_post(self, httpbin, data):564- r = requests.post(httpbin('post'),565- data=data,566- files={'file': ('test_requests.py', open(__file__, 'rb'))})567- assert r.status_code == 200568-569- def test_unicode_multipart_post_fieldnames(self, httpbin):570- filename = os.path.splitext(__file__)[0] + '.py'571- r = requests.Request(method='POST',572- url=httpbin('post'),573- data={'stuff'.encode('utf-8'): 'elixr'},574- files={'file': ('test_requests.py',575- open(filename, 'rb'))})576- prep = r.prepare()577- assert b'name="stuff"' in prep.body578- assert b'name="b\'stuff\'"' not in prep.body579-580- def test_unicode_method_name(self, httpbin):581- files = {'file': open('test_requests.py', 'rb')}582- r = requests.request(583- method=u('POST'), url=httpbin('post'), files=files)584- assert r.status_code == 200585-586- def test_unicode_method_name_with_request_object(self, httpbin):587- files = {'file': open('test_requests.py', 'rb')}588- s = requests.Session()589- req = requests.Request(u("POST"), httpbin('post'), files=files)590- prep = s.prepare_request(req)591- assert isinstance(prep.method, builtin_str)592- assert prep.method == "POST"593-594- resp = s.send(prep)595- assert resp.status_code == 200596-597- def test_custom_content_type(self, httpbin):598- r = requests.post(599- httpbin('post'),600- data={'stuff': json.dumps({'a': 123})},601- files={'file1': ('test_requests.py', open(__file__, 'rb')),602- 'file2': ('test_requests', open(__file__, 'rb'),603- 'text/py-content-type')})604- assert r.status_code == 200605- assert b"text/py-content-type" in r.request.body606-607- def test_hook_receives_request_arguments(self, httpbin):608- def hook(resp, **kwargs):609- assert resp is not None610- assert kwargs != {}611-612- s = requests.Session()613- r = requests.Request('GET', httpbin(), hooks={'response': hook})614- prep = s.prepare_request(r)615- s.send(prep)616-617- def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):618- hook = lambda x, *args, **kwargs: x619- s = requests.Session()620- s.hooks['response'].append(hook)621- r = requests.Request('GET', httpbin())622- prep = s.prepare_request(r)623- assert prep.hooks['response'] != []624- assert prep.hooks['response'] == [hook]625-626- def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):627- hook1 = lambda x, *args, **kwargs: x628- hook2 = lambda x, *args, **kwargs: x629- assert hook1 is not hook2630- s = requests.Session()631- s.hooks['response'].append(hook2)632- r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})633- prep = s.prepare_request(r)634- assert prep.hooks['response'] == [hook1]635-636- def test_prepared_request_hook(self, httpbin):637- def hook(resp, **kwargs):638- resp.hook_working = True639- return resp640-641- req = requests.Request('GET', httpbin(), hooks={'response': hook})642- prep = req.prepare()643-644- s = requests.Session()645- s.proxies = getproxies()646- resp = s.send(prep)647-648- assert hasattr(resp, 'hook_working')649-650- def test_prepared_from_session(self, httpbin):651- class DummyAuth(requests.auth.AuthBase):652- def __call__(self, r):653- r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'654- return r655-656- req = requests.Request('GET', httpbin('headers'))657- assert not req.auth658-659- s = requests.Session()660- s.auth = DummyAuth()661-662- prep = s.prepare_request(req)663- resp = s.send(prep)664-665- assert resp.json()['headers'][666- 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'667-668- def test_prepare_request_with_bytestring_url(self):669- req = requests.Request('GET', b'https://httpbin.org/')670- s = requests.Session()671- prep = s.prepare_request(req)672- assert prep.url == "https://httpbin.org/"673-674- def test_links(self):675- r = requests.Response()676- r.headers = {677- 'cache-control': 'public, max-age=60, s-maxage=60',678- 'connection': 'keep-alive',679- 'content-encoding': 'gzip',680- 'content-type': 'application/json; charset=utf-8',681- 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',682- 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',683- 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',684- 'link': ('<https://api.github.com/users/kennethreitz/repos?'685- 'page=2&per_page=10>; rel="next", <https://api.github.'686- 'com/users/kennethreitz/repos?page=7&per_page=10>; '687- ' rel="last"'),688- 'server': 'GitHub.com',689- 'status': '200 OK',690- 'vary': 'Accept',691- 'x-content-type-options': 'nosniff',692- 'x-github-media-type': 'github.beta',693- 'x-ratelimit-limit': '60',694- 'x-ratelimit-remaining': '57'695- }696- assert r.links['next']['rel'] == 'next'697-698- def test_cookie_parameters(self):699- key = 'some_cookie'700- value = 'some_value'701- secure = True702- domain = 'test.com'703- rest = {'HttpOnly': True}704-705- jar = requests.cookies.RequestsCookieJar()706- jar.set(key, value, secure=secure, domain=domain, rest=rest)707-708- assert len(jar) == 1709- assert 'some_cookie' in jar710-711- cookie = list(jar)[0]712- assert cookie.secure == secure713- assert cookie.domain == domain714- assert cookie._rest['HttpOnly'] == rest['HttpOnly']715-716- def test_cookie_as_dict_keeps_len(self):717- key = 'some_cookie'718- value = 'some_value'719-720- key1 = 'some_cookie1'721- value1 = 'some_value1'722-723- jar = requests.cookies.RequestsCookieJar()724- jar.set(key, value)725- jar.set(key1, value1)726-727- d1 = dict(jar)728- d2 = dict(jar.iteritems())729- d3 = dict(jar.items())730-731- assert len(jar) == 2732- assert len(d1) == 2733- assert len(d2) == 2734- assert len(d3) == 2735-736- def test_cookie_as_dict_keeps_items(self):737- key = 'some_cookie'738- value = 'some_value'739-740- key1 = 'some_cookie1'741- value1 = 'some_value1'742-743- jar = requests.cookies.RequestsCookieJar()744- jar.set(key, value)745- jar.set(key1, value1)746-747- d1 = dict(jar)748- d2 = dict(jar.iteritems())749- d3 = dict(jar.items())750-751- assert d1['some_cookie'] == 'some_value'752- assert d2['some_cookie'] == 'some_value'753- assert d3['some_cookie1'] == 'some_value1'754-755- def test_cookie_as_dict_keys(self):756- key = 'some_cookie'757- value = 'some_value'758-759- key1 = 'some_cookie1'760- value1 = 'some_value1'761-762- jar = requests.cookies.RequestsCookieJar()763- jar.set(key, value)764- jar.set(key1, value1)765-766- keys = jar.keys()767- assert keys == list(keys)768- # make sure one can use keys multiple times769- assert list(keys) == list(keys)770-771- def test_cookie_as_dict_values(self):772- key = 'some_cookie'773- value = 'some_value'774-775- key1 = 'some_cookie1'776- value1 = 'some_value1'777-778- jar = requests.cookies.RequestsCookieJar()779- jar.set(key, value)780- jar.set(key1, value1)781-782- values = jar.values()783- assert values == list(values)784- # make sure one can use values multiple times785- assert list(values) == list(values)786-787- def test_cookie_as_dict_items(self):788- key = 'some_cookie'789- value = 'some_value'790-791- key1 = 'some_cookie1'792- value1 = 'some_value1'793-794- jar = requests.cookies.RequestsCookieJar()795- jar.set(key, value)796- jar.set(key1, value1)797-798- items = jar.items()799- assert items == list(items)800- # make sure one can use items multiple times801- assert list(items) == list(items)802-803- def test_time_elapsed_blank(self, httpbin):804- r = requests.get(httpbin('get'))805- td = r.elapsed806- total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)807- * 10**6) / 10**6)808- assert total_seconds > 0.0809-810- def test_response_is_iterable(self):811- r = requests.Response()812- io = StringIO.StringIO('abc')813- read_ = io.read814-815- def read_mock(amt, decode_content=None):816- return read_(amt)817- setattr(io, 'read', read_mock)818- r.raw = io819- assert next(iter(r))820- io.close()821-822- def test_response_decode_unicode(self):823- """824- When called with decode_unicode, Response.iter_content should always825- return unicode.826- """827- r = requests.Response()828- r._content_consumed = True829- r._content = b'the content'830- r.encoding = 'ascii'831-832- chunks = r.iter_content(decode_unicode=True)833- assert all(isinstance(chunk, str) for chunk in chunks)834-835- # also for streaming836- r = requests.Response()837- r.raw = io.BytesIO(b'the content')838- r.encoding = 'ascii'839- chunks = r.iter_content(decode_unicode=True)840- assert all(isinstance(chunk, str) for chunk in chunks)841-842- def test_request_and_response_are_pickleable(self, httpbin):843- r = requests.get(httpbin('get'))844-845- # verify we can pickle the original request846- assert pickle.loads(pickle.dumps(r.request))847-848- # verify we can pickle the response and that we have access to849- # the original request.850- pr = pickle.loads(pickle.dumps(r))851- assert r.request.url == pr.request.url852- assert r.request.headers == pr.request.headers853-854- def test_get_auth_from_url(self):855- url = 'http://user:pass@complex.url.com/path?query=yes'856- assert ('user', 'pass') == requests.utils.get_auth_from_url(url)857-858- def test_get_auth_from_url_encoded_spaces(self):859- url = 'http://user:pass%20pass@complex.url.com/path?query=yes'860- assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)861-862- def test_get_auth_from_url_not_encoded_spaces(self):863- url = 'http://user:pass pass@complex.url.com/path?query=yes'864- assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)865-866- def test_get_auth_from_url_percent_chars(self):867- url = 'http://user%25user:pass@complex.url.com/path?query=yes'868- assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)869-870- def test_get_auth_from_url_encoded_hashes(self):871- url = 'http://user:pass%23pass@complex.url.com/path?query=yes'872- assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)873-874- def test_cannot_send_unprepared_requests(self, httpbin):875- r = requests.Request(url=httpbin())876- with pytest.raises(ValueError):877- requests.Session().send(r)878-879- def test_http_error(self):880- error = requests.exceptions.HTTPError()881- assert not error.response882- response = requests.Response()883- error = requests.exceptions.HTTPError(response=response)884- assert error.response == response885- error = requests.exceptions.HTTPError('message', response=response)886- assert str(error) == 'message'887- assert error.response == response888-889- def test_session_pickling(self, httpbin):890- r = requests.Request('GET', httpbin('get'))891- s = requests.Session()892-893- s = pickle.loads(pickle.dumps(s))894- s.proxies = getproxies()895-896- r = s.send(r.prepare())897- assert r.status_code == 200898-899- def test_fixes_1329(self, httpbin):900- """901- Ensure that header updates are done case-insensitively.902- """903- s = requests.Session()904- s.headers.update({'ACCEPT': 'BOGUS'})905- s.headers.update({'accept': 'application/json'})906- r = s.get(httpbin('get'))907- headers = r.request.headers908- assert headers['accept'] == 'application/json'909- assert headers['Accept'] == 'application/json'910- assert headers['ACCEPT'] == 'application/json'911-912- def test_uppercase_scheme_redirect(self, httpbin):913- parts = urlparse(httpbin('html'))914- url = "HTTP://" + parts.netloc + parts.path915- r = requests.get(httpbin('redirect-to'), params={'url': url})916- assert r.status_code == 200917- assert r.url.lower() == url.lower()918-919- def test_transport_adapter_ordering(self):920- s = requests.Session()921- order = ['https://', 'http://']922- assert order == list(s.adapters)923- s.mount('http://git', HTTPAdapter())924- s.mount('http://github', HTTPAdapter())925- s.mount('http://github.com', HTTPAdapter())926- s.mount('http://github.com/about/', HTTPAdapter())927- order = [928- 'http://github.com/about/',929- 'http://github.com',930- 'http://github',931- 'http://git',932- 'https://',933- 'http://',934- ]935- assert order == list(s.adapters)936- s.mount('http://gittip', HTTPAdapter())937- s.mount('http://gittip.com', HTTPAdapter())938- s.mount('http://gittip.com/about/', HTTPAdapter())939- order = [940- 'http://github.com/about/',941- 'http://gittip.com/about/',942- 'http://github.com',943- 'http://gittip.com',944- 'http://github',945- 'http://gittip',946- 'http://git',947- 'https://',948- 'http://',949- ]950- assert order == list(s.adapters)951- s2 = requests.Session()952- s2.adapters = {'http://': HTTPAdapter()}953- s2.mount('https://', HTTPAdapter())954- assert 'http://' in s2.adapters955- assert 'https://' in s2.adapters956-957- def test_header_remove_is_case_insensitive(self, httpbin):958- # From issue #1321959- s = requests.Session()960- s.headers['foo'] = 'bar'961- r = s.get(httpbin('get'), headers={'FOO': None})962- assert 'foo' not in r.request.headers963-964- def test_params_are_merged_case_sensitive(self, httpbin):965- s = requests.Session()966- s.params['foo'] = 'bar'967- r = s.get(httpbin('get'), params={'FOO': 'bar'})968- assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}969-970- def test_long_authinfo_in_url(self):971- url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(972- 'E8A3BE87-9E3F-4620-8858-95478E385B5B',973- 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',974- 'exactly-------------sixty-----------three------------characters',975- )976- r = requests.Request('GET', url).prepare()977- assert r.url == url978-979- def test_header_keys_are_native(self, httpbin):980- headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}981- r = requests.Request('GET', httpbin('get'), headers=headers)982- p = r.prepare()983-984- # This is testing that they are builtin strings. A bit weird, but there985- # we go.986- assert 'unicode' in p.headers.keys()987- assert 'byte' in p.headers.keys()988-989- def test_can_send_nonstring_objects_with_files(self, httpbin):990- data = {'a': 0.0}991- files = {'b': 'foo'}992- r = requests.Request('POST', httpbin('post'), data=data, files=files)993- p = r.prepare()994-995- assert 'multipart/form-data' in p.headers['Content-Type']996-997- def test_can_send_bytes_bytearray_objects_with_files(self, httpbin):998- # Test bytes:999- data = {'a': 'this is a string'}1000- files = {'b': b'foo'}1001- r = requests.Request('POST', httpbin('post'), data=data, files=files)1002- p = r.prepare()1003- assert 'multipart/form-data' in p.headers['Content-Type']1004- # Test bytearrays:1005- files = {'b': bytearray(b'foo')}1006- r = requests.Request('POST', httpbin('post'), data=data, files=files)1007- p = r.prepare()1008- assert 'multipart/form-data' in p.headers['Content-Type']1009-1010- def test_can_send_file_object_with_non_string_filename(self, httpbin):1011- f = io.BytesIO()1012- f.name = 21013- r = requests.Request('POST', httpbin('post'), files={'f': f})1014- p = r.prepare()1015-1016- assert 'multipart/form-data' in p.headers['Content-Type']1017-1018- def test_autoset_header_values_are_native(self, httpbin):1019- data = 'this is a string'1020- length = '16'1021- req = requests.Request('POST', httpbin('post'), data=data)1022- p = req.prepare()1023-1024- assert p.headers['Content-Length'] == length1025-1026- def test_nonhttp_schemes_dont_check_URLs(self):1027- test_urls = (1028- 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1029- 'file:///etc/passwd',1030- 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1031- )1032- for test_url in test_urls:1033- req = requests.Request('GET', test_url)1034- preq = req.prepare()1035- assert test_url == preq.url1036-1037- def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1038- r = requests.get(1039- httpbin('redirect-to'),1040- params={'url': 'http://www.google.co.uk'},1041- auth=('user', 'pass'),1042- )1043- assert r.history[0].request.headers['Authorization']1044- assert not r.request.headers.get('Authorization', '')1045-1046- def test_auth_is_retained_for_redirect_on_host(self, httpbin):1047- r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1048- h1 = r.history[0].request.headers['Authorization']1049- h2 = r.request.headers['Authorization']1050-1051- assert h1 == h21052-1053- def test_manual_redirect_with_partial_body_read(self, httpbin):1054- s = requests.Session()1055- r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1056- assert r1.is_redirect1057- rg = s.resolve_redirects(r1, r1.request, stream=True)1058-1059- # read only the first eight bytes of the response body,1060- # then follow the redirect1061- r1.iter_content(8)1062- r2 = next(rg)1063- assert r2.is_redirect1064-1065- # read all of the response via iter_content,1066- # then follow the redirect1067- for _ in r2.iter_content():1068- pass1069- r3 = next(rg)1070- assert not r3.is_redirect1071-1072- def _patch_adapter_gzipped_redirect(self, session, url):1073- adapter = session.get_adapter(url=url)1074- org_build_response = adapter.build_response1075- self._patched_response = False1076-1077- def build_response(*args, **kwargs):1078- resp = org_build_response(*args, **kwargs)1079- if not self._patched_response:1080- resp.raw.headers['content-encoding'] = 'gzip'1081- self._patched_response = True1082- return resp1083-1084- adapter.build_response = build_response1085-1086- def test_redirect_with_wrong_gzipped_header(self, httpbin):1087- s = requests.Session()1088- url = httpbin('redirect/1')1089- self._patch_adapter_gzipped_redirect(s, url)1090- s.get(url)1091-1092- def test_basic_auth_str_is_always_native(self):1093- s = _basic_auth_str("test", "test")1094- assert isinstance(s, builtin_str)1095- assert s == "Basic dGVzdDp0ZXN0"1096-1097- def test_requests_history_is_saved(self, httpbin):1098- r = requests.get(httpbin('redirect/5'))1099- total = r.history[-1].history1100- i = 01101- for item in r.history:1102- assert item.history == total[0:i]1103- i += 11104-1105- def test_json_param_post_content_type_works(self, httpbin):1106- r = requests.post(1107- httpbin('post'),1108- json={'life': 42}1109- )1110- assert r.status_code == 2001111- assert 'application/json' in r.request.headers['Content-Type']1112- assert {'life': 42} == r.json()['json']1113-1114- def test_json_param_post_should_not_override_data_param(self, httpbin):1115- r = requests.Request(method='POST', url=httpbin('post'),1116- data={'stuff': 'elixr'},1117- json={'music': 'flute'})1118- prep = r.prepare()1119- assert 'stuff=elixr' == prep.body1120-1121- def test_response_iter_lines(self, httpbin):1122- r = requests.get(httpbin('stream/4'), stream=True)1123- assert r.status_code == 2001124-1125- it = r.iter_lines()1126- next(it)1127- assert len(list(it)) == 31128-1129- def test_unconsumed_session_response_closes_connection(self, httpbin):1130- s = requests.session()1131-1132- with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1133- pass1134-1135- assert response._content_consumed is False1136- assert response.raw.closed1137-1138- @pytest.mark.xfail1139- def test_response_iter_lines_reentrant(self, httpbin):1140- """Response.iter_lines() is not reentrant safe"""1141- r = requests.get(httpbin('stream/4'), stream=True)1142- assert r.status_code == 2001143-1144- next(r.iter_lines())1145- assert len(list(r.iter_lines())) == 31146-1147-1148-class TestContentEncodingDetection:1149-1150- def test_none(self):1151- encodings = requests.utils.get_encodings_from_content('')1152- assert not len(encodings)1153-1154- @pytest.mark.parametrize(1155- 'content', (1156- # HTML5 meta charset attribute1157- '<meta charset="UTF-8">',1158- # HTML4 pragma directive1159- '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',1160- # XHTML 1.x served with text/html MIME type1161- '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',1162- # XHTML 1.x served as XML1163- '<?xml version="1.0" encoding="UTF-8"?>',1164- )1165- )1166- def test_pragmas(self, content):1167- encodings = requests.utils.get_encodings_from_content(content)1168- assert len(encodings) == 11169- assert encodings[0] == 'UTF-8'1170-1171- def test_precedence(self):1172- content = '''1173- <?xml version="1.0" encoding="XML"?>1174- <meta charset="HTML5">1175- <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1176- '''.strip()1177- encodings = requests.utils.get_encodings_from_content(content)1178- assert encodings == ['HTML5', 'HTML4', 'XML']1179-1180-1181-class TestCaseInsensitiveDict:1182-1183- @pytest.mark.parametrize('cid',1184- (1185- CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1186- CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1187- CaseInsensitiveDict(FOO='foo', BAr='bar'),1188- )1189- )1190- def test_init(self, cid):1191- assert len(cid) == 21192- assert 'foo' in cid1193- assert 'bar' in cid1194-1195- def test_docstring_example(self):1196- cid = CaseInsensitiveDict()1197- cid['Accept'] = 'application/json'1198- assert cid['aCCEPT'] == 'application/json'1199- assert list(cid) == ['Accept']1200-1201- def test_len(self):1202- cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1203- cid['A'] = 'a'1204- assert len(cid) == 21205-1206- def test_getitem(self):1207- cid = CaseInsensitiveDict({'Spam': 'blueval'})1208- assert cid['spam'] == 'blueval'1209- assert cid['SPAM'] == 'blueval'1210-1211- def test_fixes_649(self):1212- """__setitem__ should behave case-insensitively."""1213- cid = CaseInsensitiveDict()1214- cid['spam'] = 'oneval'1215- cid['Spam'] = 'twoval'1216- cid['sPAM'] = 'redval'1217- cid['SPAM'] = 'blueval'1218- assert cid['spam'] == 'blueval'1219- assert cid['SPAM'] == 'blueval'1220- assert list(cid.keys()) == ['SPAM']1221-1222- def test_delitem(self):1223- cid = CaseInsensitiveDict()1224- cid['Spam'] = 'someval'1225- del cid['sPam']1226- assert 'spam' not in cid1227- assert len(cid) == 01228-1229- def test_contains(self):1230- cid = CaseInsensitiveDict()1231- cid['Spam'] = 'someval'1232- assert 'Spam' in cid1233- assert 'spam' in cid1234- assert 'SPAM' in cid1235- assert 'sPam' in cid1236- assert 'notspam' not in cid1237-1238- def test_get(self):1239- cid = CaseInsensitiveDict()1240- cid['spam'] = 'oneval'1241- cid['SPAM'] = 'blueval'1242- assert cid.get('spam') == 'blueval'1243- assert cid.get('SPAM') == 'blueval'1244- assert cid.get('sPam') == 'blueval'1245- assert cid.get('notspam', 'default') == 'default'1246-1247- def test_update(self):1248- cid = CaseInsensitiveDict()1249- cid['spam'] = 'blueval'1250- cid.update({'sPam': 'notblueval'})1251- assert cid['spam'] == 'notblueval'1252- cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1253- cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1254- assert len(cid) == 21255- assert cid['foo'] == 'anotherfoo'1256- assert cid['bar'] == 'anotherbar'1257-1258- def test_update_retains_unchanged(self):1259- cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1260- cid.update({'foo': 'newfoo'})1261- assert cid['bar'] == 'bar'1262-1263- def test_iter(self):1264- cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1265- keys = frozenset(['Spam', 'Eggs'])1266- assert frozenset(iter(cid)) == keys1267-1268- def test_equality(self):1269- cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1270- othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1271- assert cid == othercid1272- del othercid['spam']1273- assert cid != othercid1274- assert cid == {'spam': 'blueval', 'eggs': 'redval'}1275- assert cid != object()1276-1277- def test_setdefault(self):1278- cid = CaseInsensitiveDict({'Spam': 'blueval'})1279- assert cid.setdefault('spam', 'notblueval') == 'blueval'1280- assert cid.setdefault('notspam', 'notblueval') == 'notblueval'1281-1282- def test_lower_items(self):1283- cid = CaseInsensitiveDict({1284- 'Accept': 'application/json',1285- 'user-Agent': 'requests',1286- })1287- keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1288- lowerkeyset = frozenset(['accept', 'user-agent'])1289- assert keyset == lowerkeyset1290-1291- def test_preserve_key_case(self):1292- cid = CaseInsensitiveDict({1293- 'Accept': 'application/json',1294- 'user-Agent': 'requests',1295- })1296- keyset = frozenset(['Accept', 'user-Agent'])1297- assert frozenset(i[0] for i in cid.items()) == keyset1298- assert frozenset(cid.keys()) == keyset1299- assert frozenset(cid) == keyset1300-1301- def test_preserve_last_key_case(self):1302- cid = CaseInsensitiveDict({1303- 'Accept': 'application/json',1304- 'user-Agent': 'requests',1305- })1306- cid.update({'ACCEPT': 'application/json'})1307- cid['USER-AGENT'] = 'requests'1308- keyset = frozenset(['ACCEPT', 'USER-AGENT'])1309- assert frozenset(i[0] for i in cid.items()) == keyset1310- assert frozenset(cid.keys()) == keyset1311- assert frozenset(cid) == keyset1312-1313- def test_copy(self):1314- cid = CaseInsensitiveDict({1315- 'Accept': 'application/json',1316- 'user-Agent': 'requests',1317- })1318- cid_copy = cid.copy()1319- assert cid == cid_copy1320- cid['changed'] = True1321- assert cid != cid_copy1322-1323-1324-class TestUtils:1325-1326- def test_super_len_io_streams(self):1327- """ Ensures that we properly deal with different kinds of IO streams. """1328- # uses StringIO or io.StringIO (see import above)1329- from io import BytesIO1330- from requests.utils import super_len1331-1332- assert super_len(StringIO.StringIO()) == 01333- assert super_len(1334- StringIO.StringIO('with so much drama in the LBC')) == 291335-1336- assert super_len(BytesIO()) == 01337- assert super_len(1338- BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 401339-1340- try:1341- import cStringIO1342- except ImportError:1343- pass1344- else:1345- assert super_len(1346- cStringIO.StringIO('but some how, some way...')) == 251347-1348- def test_super_len_correctly_calculates_len_of_partially_read_file(self):1349- """Ensure that we handle partially consumed file like objects."""1350- from requests.utils import super_len1351- s = StringIO.StringIO()1352- s.write('foobarbogus')1353- assert super_len(s) == 01354-1355- def test_get_environ_proxies_ip_ranges(self):1356- """Ensures that IP addresses are correctly matches with ranges1357- in no_proxy variable."""1358- from requests.utils import get_environ_proxies1359- os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1360- assert get_environ_proxies('http://192.168.0.1:5000/') == {}1361- assert get_environ_proxies('http://192.168.0.1/') == {}1362- assert get_environ_proxies('http://172.16.1.1/') == {}1363- assert get_environ_proxies('http://172.16.1.1:5000/') == {}1364- assert get_environ_proxies('http://192.168.1.1:5000/') != {}1365- assert get_environ_proxies('http://192.168.1.1/') != {}1366-1367- def test_get_environ_proxies(self):1368- """Ensures that IP addresses are correctly matches with ranges1369- in no_proxy variable."""1370- from requests.utils import get_environ_proxies1371- os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1372- assert get_environ_proxies(1373- 'http://localhost.localdomain:5000/v1.0/') == {}1374- assert get_environ_proxies('http://www.requests.com/') != {}1375-1376- def test_select_proxies(self):1377- """Make sure we can select per-host proxies correctly."""1378- from requests.utils import select_proxy1379- proxies = {'http': 'http://http.proxy',1380- 'http://some.host': 'http://some.host.proxy'}1381- assert select_proxy('hTTp://u:p@Some.Host/path', proxies) == 'http://some.host.proxy'1382- assert select_proxy('hTTp://u:p@Other.Host/path', proxies) == 'http://http.proxy'1383- assert select_proxy('hTTps://Other.Host', proxies) is None1384-1385- def test_guess_filename_when_int(self):1386- from requests.utils import guess_filename1387- assert None is guess_filename(1)1388-1389- def test_guess_filename_when_filename_is_an_int(self):1390- from requests.utils import guess_filename1391- fake = type('Fake', (object,), {'name': 1})()1392- assert None is guess_filename(fake)1393-1394- def test_guess_filename_with_file_like_obj(self):1395- from requests.utils import guess_filename1396- from requests import compat1397- fake = type('Fake', (object,), {'name': b'value'})()1398- guessed_name = guess_filename(fake)1399- assert b'value' == guessed_name1400- assert isinstance(guessed_name, compat.bytes)1401-1402- def test_guess_filename_with_unicode_name(self):1403- from requests.utils import guess_filename1404- from requests import compat1405- filename = b'value'.decode('utf-8')1406- fake = type('Fake', (object,), {'name': filename})()1407- guessed_name = guess_filename(fake)1408- assert filename == guessed_name1409- assert isinstance(guessed_name, compat.str)1410-1411- def test_is_ipv4_address(self):1412- from requests.utils import is_ipv4_address1413- assert is_ipv4_address('8.8.8.8')1414- assert not is_ipv4_address('8.8.8.8.8')1415- assert not is_ipv4_address('localhost.localdomain')1416-1417- def test_is_valid_cidr(self):1418- from requests.utils import is_valid_cidr1419- assert not is_valid_cidr('8.8.8.8')1420- assert is_valid_cidr('192.168.1.0/24')1421-1422- def test_dotted_netmask(self):1423- from requests.utils import dotted_netmask1424- assert dotted_netmask(8) == '255.0.0.0'1425- assert dotted_netmask(24) == '255.255.255.0'1426- assert dotted_netmask(25) == '255.255.255.128'1427-1428- def test_address_in_network(self):1429- from requests.utils import address_in_network1430- assert address_in_network('192.168.1.1', '192.168.1.0/24')1431- assert not address_in_network('172.16.0.1', '192.168.1.0/24')1432-1433- def test_get_auth_from_url(self):1434- """Ensures that username and password in well-encoded URI as per1435- RFC 3986 are correctly extracted."""1436- from requests.utils import get_auth_from_url1437- from requests.compat import quote1438- percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1439- url_address = "request.com/url.html#test"1440- url = "http://" + quote(1441- percent_encoding_test_chars, '') + ':' + quote(1442- percent_encoding_test_chars, '') + '@' + url_address1443- (username, password) = get_auth_from_url(url)1444- assert username == percent_encoding_test_chars1445- assert password == percent_encoding_test_chars1446-1447- def test_requote_uri_with_unquoted_percents(self):1448- """Ensure we handle unquoted percent signs in redirects.1449-1450- See: https://github.com/kennethreitz/requests/issues/23561451- """1452- from requests.utils import requote_uri1453- bad_uri = 'http://example.com/fiz?buz=%ppicture'1454- quoted = 'http://example.com/fiz?buz=%25ppicture'1455- assert quoted == requote_uri(bad_uri)1456-1457- def test_requote_uri_properly_requotes(self):1458- """Ensure requoting doesn't break expectations."""1459- from requests.utils import requote_uri1460- quoted = 'http://example.com/fiz?buz=%25ppicture'1461- assert quoted == requote_uri(quoted)1462-1463-1464-class TestMorselToCookieExpires:1465- """Tests for morsel_to_cookie when morsel contains expires."""1466-1467- def test_expires_valid_str(self):1468- """Test case where we convert expires from string time."""1469-1470- morsel = Morsel()1471- morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1472- cookie = morsel_to_cookie(morsel)1473- assert cookie.expires == 11474-1475- @pytest.mark.parametrize('value, exception',1476- (1477- (100, TypeError),1478- ('woops', ValueError),1479- )1480- )1481- def test_expires_invalid_int(self, value, exception):1482- """Test case where an invalid type is passed for expires."""1483- morsel = Morsel()1484- morsel['expires'] = value1485- with pytest.raises(exception):1486- morsel_to_cookie(morsel)1487-1488- def test_expires_none(self):1489- """Test case where expires is None."""1490-1491- morsel = Morsel()1492- morsel['expires'] = None1493- cookie = morsel_to_cookie(morsel)1494- assert cookie.expires is None1495-1496-1497-class TestMorselToCookieMaxAge:1498-1499- """Tests for morsel_to_cookie when morsel contains max-age."""1500-1501- def test_max_age_valid_int(self):1502- """Test case where a valid max age in seconds is passed."""1503-1504- morsel = Morsel()1505- morsel['max-age'] = 601506- cookie = morsel_to_cookie(morsel)1507- assert isinstance(cookie.expires, int)1508-1509- def test_max_age_invalid_str(self):1510- """Test case where a invalid max age is passed."""1511-1512- morsel = Morsel()1513- morsel['max-age'] = 'woops'1514- with pytest.raises(TypeError):1515- morsel_to_cookie(morsel)1516-1517-1518-class TestTimeout:1519- def test_stream_timeout(self, httpbin):1520- try:1521- requests.get(httpbin('delay/10'), timeout=2.0)1522- except requests.exceptions.Timeout as e:1523- assert 'Read timed out' in e.args[0].args[0]1524-1525- def test_invalid_timeout(self, httpbin):1526- with pytest.raises(ValueError) as e:1527- requests.get(httpbin('get'), timeout=(3, 4, 5))1528- assert '(connect, read)' in str(e)1529-1530- with pytest.raises(ValueError) as e:1531- requests.get(httpbin('get'), timeout="foo")1532- assert 'must be an int or float' in str(e)1533-1534- def test_none_timeout(self, httpbin):1535- """ Check that you can set None as a valid timeout value.1536-1537- To actually test this behavior, we'd want to check that setting the1538- timeout to None actually lets the request block past the system default1539- timeout. However, this would make the test suite unbearably slow.1540- Instead we verify that setting the timeout to None does not prevent the1541- request from succeeding.1542- """1543- r = requests.get(httpbin('get'), timeout=None)1544- assert r.status_code == 2001545-1546- def test_read_timeout(self, httpbin):1547- try:1548- requests.get(httpbin('delay/10'), timeout=(None, 0.1))1549- pytest.fail('The recv() request should time out.')1550- except ReadTimeout:1551- pass1552-1553- def test_connect_timeout(self):1554- try:1555- requests.get(TARPIT, timeout=(0.1, None))1556- pytest.fail('The connect() request should time out.')1557- except ConnectTimeout as e:1558- assert isinstance(e, ConnectionError)1559- assert isinstance(e, Timeout)1560-1561- def test_total_timeout_connect(self):1562- try:1563- requests.get(TARPIT, timeout=(0.1, 0.1))1564- pytest.fail('The connect() request should time out.')1565- except ConnectTimeout:1566- pass1567-1568- def test_encoded_methods(self, httpbin):1569- """See: https://github.com/kennethreitz/requests/issues/2316"""1570- r = requests.request(b'GET', httpbin('get'))1571- assert r.ok1572-1573-1574-SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))1575-1576-1577-class RedirectSession(SessionRedirectMixin):1578- def __init__(self, order_of_redirects):1579- self.redirects = order_of_redirects1580- self.calls = []1581- self.max_redirects = 301582- self.cookies = {}1583- self.trust_env = False1584-1585- def send(self, *args, **kwargs):1586- self.calls.append(SendCall(args, kwargs))1587- return self.build_response()1588-1589- def build_response(self):1590- request = self.calls[-1].args[0]1591- r = requests.Response()1592-1593- try:1594- r.status_code = int(self.redirects.pop(0))1595- except IndexError:1596- r.status_code = 2001597-1598- r.headers = CaseInsensitiveDict({'Location': '/'})1599- r.raw = self._build_raw()1600- r.request = request1601- return r1602-1603- def _build_raw(self):1604- string = StringIO.StringIO('')1605- setattr(string, 'release_conn', lambda *args: args)1606- return string1607-1608-1609-class TestRedirects:1610- default_keyword_args = {1611- 'stream': False,1612- 'verify': True,1613- 'cert': None,1614- 'timeout': None,1615- 'allow_redirects': False,1616- 'proxies': {},1617- }1618-1619- def test_requests_are_updated_each_time(self, httpbin):1620- session = RedirectSession([303, 307])1621- prep = requests.Request('POST', httpbin('post')).prepare()1622- r0 = session.send(prep)1623- assert r0.request.method == 'POST'1624- assert session.calls[-1] == SendCall((r0.request,), {})1625- redirect_generator = session.resolve_redirects(r0, prep)1626- for response in redirect_generator:1627- assert response.request.method == 'GET'1628- send_call = SendCall((response.request,),1629- TestRedirects.default_keyword_args)1630- assert session.calls[-1] == send_call1631-1632-1633-@pytest.fixture1634-def list_of_tuples():1635- return [1636- (('a', 'b'), ('c', 'd')),1637- (('c', 'd'), ('a', 'b')),1638- (('a', 'b'), ('c', 'd'), ('e', 'f')),1639- ]1640-1641-1642-def test_data_argument_accepts_tuples(list_of_tuples):1643- """Ensure that the data argument will accept tuples of strings1644- and properly encode them.1645- """1646- for data in list_of_tuples:1647- p = PreparedRequest()1648- p.prepare(1649- method='GET',1650- url='http://www.example.com',1651- data=data,1652- hooks=default_hooks()1653- )1654- assert p.body == urlencode(data)1655-1656-1657-def assert_copy(p, p_copy):1658- for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1659- assert getattr(p, attr) == getattr(p_copy, attr)1660-1661-1662-def test_prepared_request_empty_copy():1663- p = PreparedRequest()1664- assert_copy(p, p.copy())1665-1666-1667-def test_prepared_request_no_cookies_copy():1668- p = PreparedRequest()1669- p.prepare(1670- method='GET',1671- url='http://www.example.com',1672- data='foo=bar',1673- hooks=default_hooks()1674- )1675- assert_copy(p, p.copy())1676-1677-1678-def test_prepared_request_complete_copy():1679- p = PreparedRequest()1680- p.prepare(1681- method='GET',1682- url='http://www.example.com',1683- data='foo=bar',1684- hooks=default_hooks(),1685- cookies={'foo': 'bar'}1686- )1687- assert_copy(p, p.copy())1688-1689-1690-def test_prepare_unicode_url():1691- p = PreparedRequest()1692- p.prepare(1693- method='GET',1694- url=u('http://www.example.com/üniçø∂é'),1695- )1696- assert_copy(p, p.copy())1697-1698-1699-def test_urllib3_retries(httpbin):1700- from requests.packages.urllib3.util import Retry1701- s = requests.Session()1702- s.mount('http://', HTTPAdapter(max_retries=Retry(1703- total=2, status_forcelist=[500]1704- )))1705-1706- with pytest.raises(RetryError):1707- s.get(httpbin('status/500'))1708-1709-1710-def test_urllib3_pool_connection_closed(httpbin):1711- s = requests.Session()1712- s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))1713-1714- try:1715- s.get(httpbin('status/200'))1716- except ConnectionError as e:1717- assert u"Pool is closed." in str(e)1718-1719-1720-def test_vendor_aliases():1721- from requests.packages import urllib31722- from requests.packages import chardet1723-1724- with pytest.raises(ImportError):1725- from requests.packages import webbrowser