move tests over
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parent 2759060 · Browse files · 7 files·+936 added−924 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+936 added−924 removed
- tests:+935 added−0 removed
- other:+1 added−924 removed
Provenance
- Commit
0b9a2a1- Tree
af593ba- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
2759060
7 files changed+936 added−924 removed
added:tests/test_requests_async.py+62 added
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+4+# Path hack.5+import sys, os6+sys.path.insert(0, os.path.abspath('..'))7+8+import sys9+import unittest10+11+from requests import async12+import envoy13+14+sys.path.append('.')15+from test_requests import httpbin, RequestsTestSuite, SERVICES16+17+18+class RequestsTestSuiteUsingAsyncApi(RequestsTestSuite):19+ """Requests async test cases."""20+21+ def patched(f):22+ """Automatically send request after creation."""23+24+ def wrapped(*args, **kwargs):25+26+ request = f(*args, **kwargs)27+ return async.map([request])[0]28+29+ return wrapped30+31+ # Patched requests.api functions.32+ global request33+ request = patched(async.request)34+35+ global delete, get, head, options, patch, post, put36+ delete = patched(async.delete)37+ get = patched(async.get)38+ head = patched(async.head)39+ options = patched(async.options)40+ patch = patched(async.patch)41+ post = patched(async.post)42+ put = patched(async.put)43+44+45+ def test_entry_points(self):46+47+ async.request48+49+ async.delete50+ async.get51+ async.head52+ async.options53+ async.patch54+ async.post55+ async.put56+57+ async.map58+ async.send59+60+61+if __name__ == '__main__':62+ unittest.main()added:tests/test_requests_ext.py+54 added
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+4+# Path hack.5+import sys, os6+sys.path.insert(0, os.path.abspath('..'))7+8+import unittest9+10+import requests11+12+try:13+ import omnijson as json14+except ImportError:15+ import json16+17+18+class RequestsTestSuite(unittest.TestCase):19+ """Requests test cases."""20+21+ # It goes to eleven.22+ _multiprocess_can_split_ = True23+24+ def test_addition(self):25+ assert (1 + 1) == 226+27+28+ def test_ssl_hostname_ok(self):29+ requests.get('https://github.com', verify=True)30+31+32+ def test_ssl_hostname_not_ok(self):33+ requests.get('https://kennethreitz.com', verify=False)34+35+ self.assertRaises(requests.exceptions.SSLError, requests.get, 'https://kennethreitz.com')36+37+38+ def test_ssl_hostname_session_not_ok(self):39+40+ s = requests.session()41+42+ self.assertRaises(requests.exceptions.SSLError, s.get, 'https://kennethreitz.com')43+44+ s.get('https://kennethreitz.com', verify=False)45+46+47+ def test_binary_post(self):48+ utf8_string = (u'Smörgås').encode('utf-8')49+ requests.post('http://www.google.com/', data=utf8_string)50+51+52+if __name__ == '__main__':53+ unittest.main()54+added:tests/test_requests.py+819 added
1+#!/usr/bin/env python2+# -*- coding: utf-8 -*-3+4+# from __future__ import unicode_literals5+6+# Path hack.7+import sys, os8+sys.path.insert(0, os.path.abspath('..'))9+10+import io11+import json12+import time13+import os14+import sys15+import unittest16+17+import requests18+from requests.compat import str, bytes, StringIO19+# import envoy20+from requests import HTTPError21+from requests import get, post, head, put22+from requests.auth import HTTPBasicAuth, HTTPDigestAuth23+24+25+26+if (sys.platform == 'win32') and ('HTTPBIN_URL' not in os.environ):27+ os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'28+29+# TODO: Detect an open port.30+PORT = os.environ.get('HTTPBIN_PORT', '7077')31+HTTPBIN_URL = os.environ.get('HTTPBIN_URL', 'http://0.0.0.0:%s/' % (PORT))32+33+34+def httpbin(*suffix):35+ """Returns url for HTTPBIN resource."""36+37+ return HTTPBIN_URL + '/'.join(suffix)38+39+40+SERVICES = (httpbin, )41+42+_httpbin = False43+44+class TestSetup(object):45+ """Requests test cases."""46+47+ # It goes to eleven.48+ _multiprocess_can_split_ = True49+50+ def setUp(self):51+52+ global _httpbin53+54+ if (not 'HTTPBIN_URL' in os.environ) and not _httpbin:55+ # c = envoy.connect('httpbin %s' % (PORT))56+ # time.sleep(1)57+ _httpbin = True58+59+60+class RequestsTestSuite(TestSetup, unittest.TestCase):61+ """Requests test cases."""62+63+ def test_entry_points(self):64+65+ requests.session66+ requests.session().get67+ requests.session().head68+ requests.get69+ requests.head70+ requests.put71+ requests.patch72+ requests.post73+74+ def test_invalid_url(self):75+ self.assertRaises(ValueError, get, 'hiwpefhipowhefopw')76+77+78+ def test_path_is_not_double_encoded(self):79+ request = requests.Request("http://0.0.0.0/get/test case")80+81+ assert request.path_url == "/get/test%20case"82+83+ def test_HTTP_200_OK_GET(self):84+ r = get(httpbin('/get'))85+ self.assertEqual(r.status_code, 200)86+87+ def test_response_sent(self):88+ r = get(httpbin('/get'))89+90+ self.assertTrue(r.request.sent)91+92+ def test_HTTP_302_ALLOW_REDIRECT_GET(self):93+ r = get(httpbin('redirect', '1'))94+ self.assertEqual(r.status_code, 200)95+96+ def test_HTTP_302_GET(self):97+ r = get(httpbin('redirect', '1'), allow_redirects=False)98+ self.assertEqual(r.status_code, 302)99+100+101+ def test_HTTP_200_OK_GET_WITH_PARAMS(self):102+ heads = {'User-agent': 'Mozilla/5.0'}103+104+ r = get(httpbin('user-agent'), headers=heads)105+106+ assert heads['User-agent'] in r.text107+ self.assertEqual(r.status_code, 200)108+109+110+ def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):111+ heads = {'User-agent': 'Mozilla/5.0'}112+113+ r = get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)114+ self.assertEqual(r.status_code, 200)115+116+ # def test_unicode_headers(self):117+ # # Simply calling requests with a unicode instance should simply work118+ # # when the characters are all representable using latin-1:119+ # heads = { u'User-Agent': u'Requests Test Suite' }120+ # requests.get(url=httpbin('get'), headers=heads)121+122+ # # Characters outside latin-1 should raise an exception:123+ # heads = { u'User-Agent': u'\u30cd\u30c3\u30c8\u30ef\u30fc\u30af' }124+ # self.assertRaises(UnicodeEncodeError, requests.get,125+ # url=httpbin('get'), headers=heads)126+127+ # def test_session_with_escaped_url(self):128+ # # Test a URL that contains percent-escaped characters129+ # # This URL should not be modified (double-escaped)130+ # # Tests:131+ # # - Quoted illegal characters ("%20" (' '), "%3C" ('<'), "%3E" ('>'))132+ # # - Quoted reserved characters ("%25" ('%'), "%23" ('#'), "%2F" ('/'))133+ # # - Quoted non-ASCII characters ("%C3%98", "%C3%A5")134+ # path_fully_escaped = '%3Ca%25b%23c%2Fd%3E/%C3%98%20%C3%A5'135+ # url = httpbin('get/' + path_fully_escaped)136+ # response = get(url)137+ # self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))138+139+ # # Test that illegal characters in a path get properly percent-escaped140+ # # Tests:141+ # # - Bare illegal characters (space, '<')142+ # # - Bare non-ASCII characters ('\u00d8')143+ # path = u'<a%25b%23c%2Fd%3E/\u00d8 %C3%A5'144+ # url = httpbin('get/' + path)145+ # response = get(url)146+ # self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))147+148+ # # Test that reserved characters in a path do not get percent-escaped149+ # # Tests:150+ # # - All reserved characters (RFC 3986), except '?', '#', '[' and ']',151+ # # which are not allowed in the path, and ';' which delimits152+ # # parameters.153+ # # All such characters must be allowed bare in path, and must not be154+ # # encoded.155+ # # - Special unreserved characters (RFC 3986), which should not be156+ # # encoded (even though it wouldn't hurt).157+ # path_reserved = '!$&\'()*+,/:=@-._~'158+ # url = httpbin('get/' + path_reserved)159+ # response = get(url)160+ # self.assertEqual(response.url, httpbin('get/' + path_reserved))161+162+ # # Test that percent-encoded unreserved characters in a path get163+ # # normalised to their un-encoded forms.164+ # path_unreserved = 'ABCDwxyz1234-._~'165+ # path_unreserved_escaped = '%41%42%43%44%77%78%79%7A%31%32%33%34%2D%2E%5F%7E'166+ # url = httpbin('get/' + path_unreserved_escaped)167+ # response = get(url)168+ # self.assertEqual(response.url, httpbin('get/' + path_unreserved))169+170+ # # Re-run all of the same tests on the query part of the URI171+ # query_fully_escaped = '%3Ca%25b%23c%2Fd%3E=%C3%98%20%C3%A5'172+ # url = httpbin('get/?' + query_fully_escaped)173+ # response = get(url)174+ # self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))175+176+ # query = u'<a%25b%23c%2Fd%3E=\u00d8 %C3%A5'177+ # url = httpbin('get/?' + query)178+ # response = get(url)179+ # self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))180+181+ # # The legal characters in query happens to be the same as in path182+ # query_reserved = '!$&\'()*+,/:=@-._~'183+ # url = httpbin('get/?' + query_reserved)184+ # response = get(url)185+ # self.assertEqual(response.url, httpbin('get/?' + query_reserved))186+187+ # query_unreserved = 'ABCDwxyz=1234-._~'188+ # query_unreserved_escaped = '%41%42%43%44%77%78%79%7A=%31%32%33%34%2D%2E%5F%7E'189+ # url = httpbin('get/?' + query_unreserved_escaped)190+ # response = get(url)191+ # self.assertEqual(response.url, httpbin('get/?' + query_unreserved))192+193+194+ def test_user_agent_transfers(self):195+ """Issue XX"""196+197+ heads = {198+ 'User-agent':199+ 'Mozilla/5.0 (github.com/kennethreitz/requests)'200+ }201+202+ r = get(httpbin('user-agent'), headers=heads);203+ self.assertTrue(heads['User-agent'] in r.text)204+205+ heads = {206+ 'user-agent':207+ 'Mozilla/5.0 (github.com/kennethreitz/requests)'208+ }209+210+ r = get(httpbin('user-agent'), headers=heads);211+ self.assertTrue(heads['user-agent'] in r.text)212+213+214+ def test_HTTP_200_OK_HEAD(self):215+ r = head(httpbin('/get'))216+ self.assertEqual(r.status_code, 200)217+218+219+ def test_HTTP_200_OK_PUT(self):220+ r = put(httpbin('put'))221+ self.assertEqual(r.status_code, 200)222+223+224+ def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):225+226+ for service in SERVICES:227+228+ auth = ('user', 'pass')229+ url = service('basic-auth', 'user', 'pass')230+231+ r = get(url, auth=auth)232+ self.assertEqual(r.status_code, 200)233+234+ r = get(url)235+ self.assertEqual(r.status_code, 401)236+237+238+ s = requests.session(auth=auth)239+ r = get(url, session=s)240+ self.assertEqual(r.status_code, 200)241+242+243+ def test_BASICAUTH_HTTP_200_OK_GET(self):244+245+ for service in SERVICES:246+247+ auth = HTTPBasicAuth('user', 'pass')248+ url = service('basic-auth', 'user', 'pass')249+250+ r = get(url, auth=auth)251+ self.assertEqual(r.status_code, 200)252+253+ auth = ('user', 'pass')254+ r = get(url, auth=auth)255+ self.assertEqual(r.status_code, 200)256+257+ r = get(url)258+ self.assertEqual(r.status_code, 401)259+260+261+ s = requests.session(auth=auth)262+ r = get(url, session=s)263+ self.assertEqual(r.status_code, 200)264+265+266+ def test_DIGESTAUTH_HTTP_200_OK_GET(self):267+268+ for service in SERVICES:269+270+ auth = HTTPDigestAuth('user', 'pass')271+ url = service('digest-auth', 'auth', 'user', 'pass')272+273+ r = get(url, auth=auth)274+ self.assertEqual(r.status_code, 200)275+276+ r = get(url)277+ self.assertEqual(r.status_code, 401)278+279+280+ s = requests.session(auth=auth)281+ r = get(url, session=s)282+ self.assertEqual(r.status_code, 200)283+284+ def test_POSTBIN_GET_POST_FILES(self):285+286+ for service in SERVICES:287+288+ url = service('post')289+ post1 = post(url).raise_for_status()290+291+ post1 = post(url, data={'some': 'data'})292+ self.assertEqual(post1.status_code, 200)293+294+ with open('test_requests.py') as f:295+ post2 = post(url, files={'some': f})296+ self.assertEqual(post2.status_code, 200)297+298+ post3 = post(url, data='[{"some": "json"}]')299+ self.assertEqual(post3.status_code, 200)300+301+302+ def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):303+304+ for service in SERVICES:305+306+ with open('test_requests.py') as f:307+ url = service('post')308+ post1 = post(url,309+ files={'some': f},310+ data={'some': 'data'})311+312+ self.assertEqual(post1.status_code, 200)313+314+315+ def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):316+317+ for service in SERVICES:318+319+ url = service('post')320+321+ with open('test_requests.py') as f:322+323+ post2 = post(url,324+ files={'some': f},325+ headers = {'User-Agent': 'requests-tests'})326+327+ self.assertEqual(post2.status_code, 200)328+329+330+ def test_nonzero_evaluation(self):331+332+ for service in SERVICES:333+334+ r = get(service('status', '500'))335+ self.assertEqual(bool(r), False)336+337+ r = get(service('/get'))338+ self.assertEqual(bool(r), True)339+340+341+ def test_request_ok_set(self):342+343+ for service in SERVICES:344+345+ r = get(service('status', '404'))346+ # print r.status_code347+ # r.raise_for_status()348+ self.assertEqual(r.ok, False)349+350+351+ def test_status_raising(self):352+ r = get(httpbin('status', '404'))353+ self.assertRaises(HTTPError, r.raise_for_status)354+355+ r = get(httpbin('status', '200'))356+ self.assertFalse(r.error)357+ r.raise_for_status()358+359+360+ def test_default_status_raising(self):361+ config = {'danger_mode': True}362+ args = [httpbin('status', '404')]363+ kwargs = dict(config=config)364+ self.assertRaises(HTTPError, get, *args, **kwargs)365+366+ r = get(httpbin('status', '200'))367+ self.assertEqual(r.status_code, 200)368+369+370+ def test_decompress_gzip(self):371+372+ r = get(httpbin('gzip'))373+ r.content.decode('ascii')374+375+ def test_response_has_unicode_url(self):376+377+ for service in SERVICES:378+379+ url = service('get')380+381+ response = get(url)382+383+ assert isinstance(response.url, str)384+385+386+ def test_unicode_get(self):387+388+ for service in SERVICES:389+390+ url = service('/get')391+392+ get(url, params={'foo': 'føø'})393+ get(url, params={'føø': 'føø'})394+ get(url, params={'føø': 'føø'})395+ get(url, params={'foo': 'foo'})396+ get(service('ø'), params={'foo': 'foo'})397+398+399+ def test_httpauth_recursion(self):400+401+ http_auth = HTTPBasicAuth('user', 'BADpass')402+403+ for service in SERVICES:404+ r = get(service('basic-auth', 'user', 'pass'), auth=http_auth)405+ self.assertEqual(r.status_code, 401)406+407+408+ def test_urlencoded_post_data(self):409+410+ for service in SERVICES:411+412+ r = post(service('post'), data=dict(test='fooaowpeuf'))413+414+ self.assertEqual(r.status_code, 200)415+ self.assertEqual(r.headers['content-type'], 'application/json')416+ self.assertEqual(r.url, service('post'))417+418+ rbody = json.loads(r.text)419+420+ self.assertEqual(rbody.get('form'), dict(test='fooaowpeuf'))421+ self.assertEqual(rbody.get('data'), '')422+423+424+ def test_nonurlencoded_post_data(self):425+426+ for service in SERVICES:427+428+ r = post(service('post'), data='fooaowpeuf')429+430+ self.assertEqual(r.status_code, 200)431+ self.assertEqual(r.headers['content-type'], 'application/json')432+ self.assertEqual(r.url, service('post'))433+434+ rbody = json.loads(r.text)435+ # Body wasn't valid url encoded data, so the server returns None as436+ # "form" and the raw body as "data".437+438+ assert rbody.get('form') in (None, {})439+ self.assertEqual(rbody.get('data'), 'fooaowpeuf')440+441+442+ def test_urlencoded_post_querystring(self):443+444+ for service in SERVICES:445+446+ r = post(service('post'), params=dict(test='fooaowpeuf'))447+448+ self.assertEqual(r.status_code, 200)449+ self.assertEqual(r.headers['content-type'], 'application/json')450+ self.assertEqual(r.url, service('post?test=fooaowpeuf'))451+452+ rbody = json.loads(r.text)453+ self.assertEqual(rbody.get('form'), {}) # No form supplied454+ self.assertEqual(rbody.get('data'), '')455+456+457+ def test_urlencoded_post_query_and_data(self):458+459+ for service in SERVICES:460+461+ r = post(462+ service('post'),463+ params=dict(test='fooaowpeuf'),464+ data=dict(test2="foobar"))465+466+ self.assertEqual(r.status_code, 200)467+ self.assertEqual(r.headers['content-type'], 'application/json')468+ self.assertEqual(r.url, service('post?test=fooaowpeuf'))469+470+ rbody = json.loads(r.text)471+ self.assertEqual(rbody.get('form'), dict(test2='foobar'))472+ self.assertEqual(rbody.get('data'), '')473+474+475+ def test_nonurlencoded_postdata(self):476+477+ for service in SERVICES:478+479+ r = post(service('post'), data="foobar")480+481+ self.assertEqual(r.status_code, 200)482+ self.assertEqual(r.headers['content-type'], 'application/json')483+484+ rbody = json.loads(r.text)485+486+ assert rbody.get('form') in (None, {})487+ self.assertEqual(rbody.get('data'), 'foobar')488+489+490+ # def test_idna(self):491+ # r = get(u'http://➡.ws/httpbin')492+ # assert 'httpbin' in r.url493+494+495+ def test_urlencoded_get_query_multivalued_param(self):496+497+ for service in SERVICES:498+499+ r = get(service('get'), params=dict(test=['foo','baz']))500+ self.assertEqual(r.status_code, 200)501+ self.assertEqual(r.url, service('get?test=foo&test=baz'))502+503+504+ def test_urlencoded_post_querystring_multivalued(self):505+506+ for service in SERVICES:507+508+ r = post(service('post'), params=dict(test=['foo','baz']))509+ self.assertEqual(r.status_code, 200)510+ self.assertEqual(r.headers['content-type'], 'application/json')511+ self.assertEqual(r.url, service('post?test=foo&test=baz'))512+513+ rbody = json.loads(r.text)514+ self.assertEqual(rbody.get('form'), {}) # No form supplied515+ self.assertEqual(rbody.get('data'), '')516+517+518+ def test_urlencoded_post_query_multivalued_and_data(self):519+520+ for service in SERVICES:521+522+ r = post(523+ service('post'),524+ params=dict(test=['foo','baz']),525+ data=dict(test2="foobar",test3=['foo','baz']))526+527+ self.assertEqual(r.status_code, 200)528+ self.assertEqual(r.headers['content-type'], 'application/json')529+ self.assertEqual(r.url, service('post?test=foo&test=baz'))530+531+ # print(r.text)532+ # print('-----------------------')533+534+ rbody = json.loads(r.text)535+ self.assertEqual(rbody.get('form'), dict(test2='foobar',test3=['foo','baz']))536+ self.assertEqual(rbody.get('data'), '')537+538+539+ def test_GET_no_redirect(self):540+541+ for service in SERVICES:542+543+ r = get(service('redirect', '3'), allow_redirects=False)544+ self.assertEqual(r.status_code, 302)545+ self.assertEqual(len(r.history), 0)546+547+548+ def test_HEAD_no_redirect(self):549+550+ for service in SERVICES:551+552+ r = head(service('redirect', '3'), allow_redirects=False)553+ self.assertEqual(r.status_code, 302)554+ self.assertEqual(len(r.history), 0)555+556+557+ def test_redirect_history(self):558+559+ for service in SERVICES:560+561+ r = get(service('redirect', '3'))562+ self.assertEqual(r.status_code, 200)563+ self.assertEqual(len(r.history), 3)564+565+566+ def test_relative_redirect_history(self):567+568+ for service in SERVICES:569+570+ r = get(service('relative-redirect', '3'))571+ self.assertEqual(r.status_code, 200)572+ self.assertEqual(len(r.history), 3)573+574+575+ def test_session_HTTP_200_OK_GET(self):576+577+ s = requests.session()578+ r = get(httpbin('/get'), session=s)579+ self.assertEqual(r.status_code, 200)580+581+582+ def test_session_persistent_headers(self):583+584+ heads = {'User-agent': 'Mozilla/5.0'}585+586+ s = requests.session()587+ s.headers = heads588+589+ # Make 2 requests from Session object, should send header both times590+ r1 = get(httpbin('user-agent'), session=s)591+ assert heads['User-agent'] in r1.text592+593+ r2 = get(httpbin('user-agent'), session=s)594+ assert heads['User-agent'] in r2.text595+596+ new_heads = {'User-agent': 'blah'}597+ r3 = get(httpbin('user-agent'), headers=new_heads, session=s)598+ assert new_heads['User-agent'] in r3.text599+600+ self.assertEqual(r2.status_code, 200)601+602+ def test_single_hook(self):603+604+ def add_foo_header(args):605+ if not args.get('headers'):606+ args['headers'] = {}607+608+ args['headers'].update({609+ 'X-Foo': 'foo'610+ })611+612+ return args613+614+ for service in SERVICES:615+ url = service('headers')616+617+ response = get(618+ url = url,619+ hooks = {620+ 'args': add_foo_header621+ }622+ )623+624+ assert 'foo' in response.text625+626+ def test_multiple_hooks(self):627+628+ def add_foo_header(args):629+ if not args.get('headers'):630+ args['headers'] = {}631+632+ args['headers'].update({633+ 'X-Foo': 'foo'634+ })635+636+ return args637+638+ def add_bar_header(args):639+ if not args.get('headers'):640+ args['headers'] = {}641+642+ args['headers'].update({643+ 'X-Bar': 'bar'644+ })645+646+ return args647+648+ for service in SERVICES:649+ url = service('headers')650+651+ response = get(652+ url = url,653+ hooks = {654+ 'args': [add_foo_header, add_bar_header]655+ }656+ )657+658+ assert 'foo' in response.text659+ assert 'bar' in response.text660+661+ def test_session_persistent_cookies(self):662+663+ s = requests.session()664+665+ # Internally dispatched cookies are sent.666+ _c = {'kenneth': 'reitz', 'bessie': 'monke'}667+ r = get(httpbin('cookies'), cookies=_c, session=s)668+ r = get(httpbin('cookies'), session=s)669+670+ # Those cookies persist transparently.671+ c = json.loads(r.text).get('cookies')672+ assert c == _c673+674+ # Double check.675+ r = get(httpbin('cookies'), cookies={}, session=s)676+ c = json.loads(r.text).get('cookies')677+ assert c == _c678+679+ # Remove a cookie by setting it's value to None.680+ r = get(httpbin('cookies'), cookies={'bessie': None}, session=s)681+ c = json.loads(r.text).get('cookies')682+ del _c['bessie']683+ assert c == _c684+685+ # Test session-level cookies.686+ s = requests.session(cookies=_c)687+ r = get(httpbin('cookies'), session=s)688+ c = json.loads(r.text).get('cookies')689+ assert c == _c690+691+ # Have the server set a cookie.692+ r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)693+ c = json.loads(r.text).get('cookies')694+695+ assert 'k' in c696+697+ # And server-set cookie persistience.698+ r = get(httpbin('cookies'), session=s)699+ c = json.loads(r.text).get('cookies')700+701+ assert 'k' in c702+703+704+705+ def test_session_persistent_params(self):706+707+ params = {'a': 'a_test'}708+709+ s = requests.session()710+ s.params = params711+712+ # Make 2 requests from Session object, should send header both times713+ r1 = get(httpbin('get'), session=s)714+ assert params['a'] in r1.text715+716+717+ params2 = {'b': 'b_test'}718+719+ r2 = get(httpbin('get'), params=params2, session=s)720+ assert params['a'] in r2.text721+ assert params2['b'] in r2.text722+723+724+ params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}725+726+ r3 = get(httpbin('get'), params=params3, session=s)727+728+ assert not params['a'] in r3.text729+ assert params3['b'] in r3.text730+ assert params3['c'] in r3.text731+732+ def test_invalid_content(self):733+ # WARNING: if you're using a terrible DNS provider (comcast),734+ # this will fail.735+ try:736+ hah = 'http://somedomainthatclearlydoesntexistg.com'737+ r = get(hah, allow_redirects=False)738+ except requests.ConnectionError:739+ pass # \o/740+ else:741+ assert False742+743+744+ config = {'safe_mode': True}745+ r = get(hah, allow_redirects=False, config=config)746+ assert r.content == None747+748+ def test_cached_response(self):749+750+ r1 = get(httpbin('get'), prefetch=False)751+ assert not r1._content752+ assert r1.content753+ assert r1.text754+755+ r2 = get(httpbin('get'), prefetch=True)756+ assert r2._content757+ assert r2.content758+ assert r2.text759+760+ def test_iter_lines(self):761+762+ lines = (0, 2, 10, 100)763+764+ for i in lines:765+ r = get(httpbin('stream', str(i)), prefetch=False)766+ lines = list(r.iter_lines())767+ len_lines = len(lines)768+769+ self.assertEqual(i, len_lines)770+771+ # Test 'dangling' fragment in responses that do not terminate in772+ # a newline.773+ quote = (774+ '''Why will he not upon our fair request\n'''775+ '''Untent his person and share the air with us?'''776+ )777+778+ # Make a request and monkey-patch its contents779+ r = get(httpbin('get'))780+ r.raw = StringIO(quote)781+782+ # Make sure iter_lines doesn't chop the trailing bit783+ lines = '\n'.join(r.iter_lines())784+ self.assertEqual(lines, quote)785+786+ def test_safe_mode(self):787+788+ safe = requests.session(config=dict(safe_mode=True))789+790+ # Safe mode creates empty responses for failed requests.791+ # Iterating on these responses should produce empty sequences792+ r = get('http://_/', session=safe)793+ self.assertEqual(list(r.iter_lines()), [])794+ assert isinstance(r.error, requests.exceptions.ConnectionError)795+796+ r = get('http://_/', session=safe)797+ self.assertEqual(list(r.iter_content()), [])798+ assert isinstance(r.error, requests.exceptions.ConnectionError)799+800+ # When not in safe mode, should raise Timeout exception801+ self.assertRaises(802+ requests.exceptions.Timeout,803+ get,804+ httpbin('stream', '1000'), timeout=0.0001)805+806+ # In safe mode, should return a blank response807+ r = get(httpbin('stream', '1000'), timeout=0.0001,808+ config=dict(safe_mode=True))809+ assert r.content is None810+ assert isinstance(r.error, requests.exceptions.Timeout)811+812+ def test_upload_binary_data(self):813+814+ r = requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')815+816+817+818+if __name__ == '__main__':819+ unittest.main()modified:Makefile+1 added-1 removed
3 unmodified lines4 python setup.py develop5 pip install -r requirements.txt6 7 test:8- nosetests --with-color ./test_*8+ nosetests --with-color ./tests/*9 10 lazy:11 nosetests --with-color test_requests.py12 23 unmodified linesdeleted:test_requests_async.py-58 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-4-import sys5-import unittest6-7-from requests import async8-import envoy9-10-sys.path.append('.')11-from test_requests import httpbin, RequestsTestSuite, SERVICES12-13-14-class RequestsTestSuiteUsingAsyncApi(RequestsTestSuite):15- """Requests async test cases."""16-17- def patched(f):18- """Automatically send request after creation."""19- 20- def wrapped(*args, **kwargs):21- 22- request = f(*args, **kwargs)23- return async.map([request])[0]24- 25- return wrapped26-27- # Patched requests.api functions.28- global request29- request = patched(async.request)30- 31- global delete, get, head, options, patch, post, put32- delete = patched(async.delete)33- get = patched(async.get)34- head = patched(async.head)35- options = patched(async.options)36- patch = patched(async.patch)37- post = patched(async.post)38- put = patched(async.put)39-40-41- def test_entry_points(self):42-43- async.request44- 45- async.delete 46- async.get47- async.head48- async.options49- async.patch50- async.post51- async.put52- 53- async.map54- async.send55- 56-57-if __name__ == '__main__':58- unittest.main()deleted:test_requests_ext.py-52 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-4-from __future__ import with_statement5-6-import unittest7-8-import requests9-10-try:11- import omnijson as json12-except ImportError:13- import json14-15-16-class RequestsTestSuite(unittest.TestCase):17- """Requests test cases."""18-19- # It goes to eleven.20- _multiprocess_can_split_ = True21-22- def test_addition(self):23- assert (1 + 1) == 224-25-26- def test_ssl_hostname_ok(self):27- requests.get('https://github.com', verify=True)28-29-30- def test_ssl_hostname_not_ok(self):31- requests.get('https://kennethreitz.com', verify=False)32-33- self.assertRaises(requests.exceptions.SSLError, requests.get, 'https://kennethreitz.com')34-35-36- def test_ssl_hostname_session_not_ok(self):37-38- s = requests.session()39-40- self.assertRaises(requests.exceptions.SSLError, s.get, 'https://kennethreitz.com')41-42- s.get('https://kennethreitz.com', verify=False)43-44-45- def test_binary_post(self):46- utf8_string = (u'Smörgås').encode('utf-8')47- requests.post('http://www.google.com/', data=utf8_string)48-49-50-if __name__ == '__main__':51- unittest.main()52-deleted:test_requests.py-813 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-4-import io5-import json6-import time7-import os8-import sys9-import unittest10-11-import requests12-from requests.compat import str, bytes, StringIO13-# import envoy14-from requests import HTTPError15-from requests import get, post, head, put16-from requests.auth import HTTPBasicAuth, HTTPDigestAuth17-18-19-20-if (sys.platform == 'win32') and ('HTTPBIN_URL' not in os.environ):21- os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'22-23-# TODO: Detect an open port.24-PORT = os.environ.get('HTTPBIN_PORT', '7077')25-HTTPBIN_URL = os.environ.get('HTTPBIN_URL', 'http://0.0.0.0:%s/' % (PORT))26-27-28-def httpbin(*suffix):29- """Returns url for HTTPBIN resource."""30-31- return HTTPBIN_URL + '/'.join(suffix)32-33-34-SERVICES = (httpbin, )35-36-_httpbin = False37-38-class TestSetup(object):39- """Requests test cases."""40-41- # It goes to eleven.42- _multiprocess_can_split_ = True43-44- def setUp(self):45-46- global _httpbin47-48- if (not 'HTTPBIN_URL' in os.environ) and not _httpbin:49- # c = envoy.connect('httpbin %s' % (PORT))50- # time.sleep(1)51- _httpbin = True52-53-54-class RequestsTestSuite(TestSetup, unittest.TestCase):55- """Requests test cases."""56-57- def test_entry_points(self):58-59- requests.session60- requests.session().get61- requests.session().head62- requests.get63- requests.head64- requests.put65- requests.patch66- requests.post67-68- def test_invalid_url(self):69- self.assertRaises(ValueError, get, 'hiwpefhipowhefopw')70-71-72- def test_path_is_not_double_encoded(self):73- request = requests.Request("http://0.0.0.0/get/test case")74-75- assert request.path_url == "/get/test%20case"76-77- def test_HTTP_200_OK_GET(self):78- r = get(httpbin('/get'))79- self.assertEqual(r.status_code, 200)80-81- def test_response_sent(self):82- r = get(httpbin('/get'))83-84- self.assertTrue(r.request.sent)85-86- def test_HTTP_302_ALLOW_REDIRECT_GET(self):87- r = get(httpbin('redirect', '1'))88- self.assertEqual(r.status_code, 200)89-90- def test_HTTP_302_GET(self):91- r = get(httpbin('redirect', '1'), allow_redirects=False)92- self.assertEqual(r.status_code, 302)93-94-95- def test_HTTP_200_OK_GET_WITH_PARAMS(self):96- heads = {'User-agent': 'Mozilla/5.0'}97-98- r = get(httpbin('user-agent'), headers=heads)99-100- assert heads['User-agent'] in r.text101- self.assertEqual(r.status_code, 200)102-103-104- def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):105- heads = {'User-agent': 'Mozilla/5.0'}106-107- r = get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)108- self.assertEqual(r.status_code, 200)109-110- # def test_unicode_headers(self):111- # # Simply calling requests with a unicode instance should simply work112- # # when the characters are all representable using latin-1:113- # heads = { u'User-Agent': u'Requests Test Suite' }114- # requests.get(url=httpbin('get'), headers=heads)115-116- # # Characters outside latin-1 should raise an exception:117- # heads = { u'User-Agent': u'\u30cd\u30c3\u30c8\u30ef\u30fc\u30af' }118- # self.assertRaises(UnicodeEncodeError, requests.get,119- # url=httpbin('get'), headers=heads)120-121- # def test_session_with_escaped_url(self):122- # # Test a URL that contains percent-escaped characters123- # # This URL should not be modified (double-escaped)124- # # Tests:125- # # - Quoted illegal characters ("%20" (' '), "%3C" ('<'), "%3E" ('>'))126- # # - Quoted reserved characters ("%25" ('%'), "%23" ('#'), "%2F" ('/'))127- # # - Quoted non-ASCII characters ("%C3%98", "%C3%A5")128- # path_fully_escaped = '%3Ca%25b%23c%2Fd%3E/%C3%98%20%C3%A5'129- # url = httpbin('get/' + path_fully_escaped)130- # response = get(url)131- # self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))132-133- # # Test that illegal characters in a path get properly percent-escaped134- # # Tests:135- # # - Bare illegal characters (space, '<')136- # # - Bare non-ASCII characters ('\u00d8')137- # path = u'<a%25b%23c%2Fd%3E/\u00d8 %C3%A5'138- # url = httpbin('get/' + path)139- # response = get(url)140- # self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))141-142- # # Test that reserved characters in a path do not get percent-escaped143- # # Tests:144- # # - All reserved characters (RFC 3986), except '?', '#', '[' and ']',145- # # which are not allowed in the path, and ';' which delimits146- # # parameters.147- # # All such characters must be allowed bare in path, and must not be148- # # encoded.149- # # - Special unreserved characters (RFC 3986), which should not be150- # # encoded (even though it wouldn't hurt).151- # path_reserved = '!$&\'()*+,/:=@-._~'152- # url = httpbin('get/' + path_reserved)153- # response = get(url)154- # self.assertEqual(response.url, httpbin('get/' + path_reserved))155-156- # # Test that percent-encoded unreserved characters in a path get157- # # normalised to their un-encoded forms.158- # path_unreserved = 'ABCDwxyz1234-._~'159- # path_unreserved_escaped = '%41%42%43%44%77%78%79%7A%31%32%33%34%2D%2E%5F%7E'160- # url = httpbin('get/' + path_unreserved_escaped)161- # response = get(url)162- # self.assertEqual(response.url, httpbin('get/' + path_unreserved))163-164- # # Re-run all of the same tests on the query part of the URI165- # query_fully_escaped = '%3Ca%25b%23c%2Fd%3E=%C3%98%20%C3%A5'166- # url = httpbin('get/?' + query_fully_escaped)167- # response = get(url)168- # self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))169-170- # query = u'<a%25b%23c%2Fd%3E=\u00d8 %C3%A5'171- # url = httpbin('get/?' + query)172- # response = get(url)173- # self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))174-175- # # The legal characters in query happens to be the same as in path176- # query_reserved = '!$&\'()*+,/:=@-._~'177- # url = httpbin('get/?' + query_reserved)178- # response = get(url)179- # self.assertEqual(response.url, httpbin('get/?' + query_reserved))180-181- # query_unreserved = 'ABCDwxyz=1234-._~'182- # query_unreserved_escaped = '%41%42%43%44%77%78%79%7A=%31%32%33%34%2D%2E%5F%7E'183- # url = httpbin('get/?' + query_unreserved_escaped)184- # response = get(url)185- # self.assertEqual(response.url, httpbin('get/?' + query_unreserved))186-187-188- def test_user_agent_transfers(self):189- """Issue XX"""190-191- heads = {192- 'User-agent':193- 'Mozilla/5.0 (github.com/kennethreitz/requests)'194- }195-196- r = get(httpbin('user-agent'), headers=heads);197- self.assertTrue(heads['User-agent'] in r.text)198-199- heads = {200- 'user-agent':201- 'Mozilla/5.0 (github.com/kennethreitz/requests)'202- }203-204- r = get(httpbin('user-agent'), headers=heads);205- self.assertTrue(heads['user-agent'] in r.text)206-207-208- def test_HTTP_200_OK_HEAD(self):209- r = head(httpbin('/get'))210- self.assertEqual(r.status_code, 200)211-212-213- def test_HTTP_200_OK_PUT(self):214- r = put(httpbin('put'))215- self.assertEqual(r.status_code, 200)216-217-218- def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):219-220- for service in SERVICES:221-222- auth = ('user', 'pass')223- url = service('basic-auth', 'user', 'pass')224-225- r = get(url, auth=auth)226- self.assertEqual(r.status_code, 200)227-228- r = get(url)229- self.assertEqual(r.status_code, 401)230-231-232- s = requests.session(auth=auth)233- r = get(url, session=s)234- self.assertEqual(r.status_code, 200)235-236-237- def test_BASICAUTH_HTTP_200_OK_GET(self):238-239- for service in SERVICES:240-241- auth = HTTPBasicAuth('user', 'pass')242- url = service('basic-auth', 'user', 'pass')243-244- r = get(url, auth=auth)245- self.assertEqual(r.status_code, 200)246-247- auth = ('user', 'pass')248- r = get(url, auth=auth)249- self.assertEqual(r.status_code, 200)250-251- r = get(url)252- self.assertEqual(r.status_code, 401)253-254-255- s = requests.session(auth=auth)256- r = get(url, session=s)257- self.assertEqual(r.status_code, 200)258-259-260- def test_DIGESTAUTH_HTTP_200_OK_GET(self):261-262- for service in SERVICES:263-264- auth = HTTPDigestAuth('user', 'pass')265- url = service('digest-auth', 'auth', 'user', 'pass')266-267- r = get(url, auth=auth)268- self.assertEqual(r.status_code, 200)269-270- r = get(url)271- self.assertEqual(r.status_code, 401)272-273-274- s = requests.session(auth=auth)275- r = get(url, session=s)276- self.assertEqual(r.status_code, 200)277-278- def test_POSTBIN_GET_POST_FILES(self):279-280- for service in SERVICES:281-282- url = service('post')283- post1 = post(url).raise_for_status()284-285- post1 = post(url, data={'some': 'data'})286- self.assertEqual(post1.status_code, 200)287-288- with open('test_requests.py') as f:289- post2 = post(url, files={'some': f})290- self.assertEqual(post2.status_code, 200)291-292- post3 = post(url, data='[{"some": "json"}]')293- self.assertEqual(post3.status_code, 200)294-295-296- def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):297-298- for service in SERVICES:299-300- with open('test_requests.py') as f:301- url = service('post')302- post1 = post(url,303- files={'some': f},304- data={'some': 'data'})305-306- self.assertEqual(post1.status_code, 200)307-308-309- def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):310-311- for service in SERVICES:312-313- url = service('post')314-315- with open('test_requests.py') as f:316-317- post2 = post(url,318- files={'some': f},319- headers = {'User-Agent': 'requests-tests'})320-321- self.assertEqual(post2.status_code, 200)322-323-324- def test_nonzero_evaluation(self):325-326- for service in SERVICES:327-328- r = get(service('status', '500'))329- self.assertEqual(bool(r), False)330-331- r = get(service('/get'))332- self.assertEqual(bool(r), True)333-334-335- def test_request_ok_set(self):336-337- for service in SERVICES:338-339- r = get(service('status', '404'))340- # print r.status_code341- # r.raise_for_status()342- self.assertEqual(r.ok, False)343-344-345- def test_status_raising(self):346- r = get(httpbin('status', '404'))347- self.assertRaises(HTTPError, r.raise_for_status)348-349- r = get(httpbin('status', '200'))350- self.assertFalse(r.error)351- r.raise_for_status()352-353-354- def test_default_status_raising(self):355- config = {'danger_mode': True}356- args = [httpbin('status', '404')]357- kwargs = dict(config=config)358- self.assertRaises(HTTPError, get, *args, **kwargs)359-360- r = get(httpbin('status', '200'))361- self.assertEqual(r.status_code, 200)362-363-364- def test_decompress_gzip(self):365-366- r = get(httpbin('gzip'))367- r.content.decode('ascii')368-369- def test_response_has_unicode_url(self):370-371- for service in SERVICES:372-373- url = service('get')374-375- response = get(url)376-377- assert isinstance(response.url, str)378-379-380- def test_unicode_get(self):381-382- for service in SERVICES:383-384- url = service('/get')385-386- get(url, params={'foo': 'føø'})387- get(url, params={'føø': 'føø'})388- get(url, params={'føø': 'føø'})389- get(url, params={'foo': 'foo'})390- get(service('ø'), params={'foo': 'foo'})391-392-393- def test_httpauth_recursion(self):394-395- http_auth = HTTPBasicAuth('user', 'BADpass')396-397- for service in SERVICES:398- r = get(service('basic-auth', 'user', 'pass'), auth=http_auth)399- self.assertEqual(r.status_code, 401)400-401-402- def test_urlencoded_post_data(self):403-404- for service in SERVICES:405-406- r = post(service('post'), data=dict(test='fooaowpeuf'))407-408- self.assertEqual(r.status_code, 200)409- self.assertEqual(r.headers['content-type'], 'application/json')410- self.assertEqual(r.url, service('post'))411-412- rbody = json.loads(r.text)413-414- self.assertEqual(rbody.get('form'), dict(test='fooaowpeuf'))415- self.assertEqual(rbody.get('data'), '')416-417-418- def test_nonurlencoded_post_data(self):419-420- for service in SERVICES:421-422- r = post(service('post'), data='fooaowpeuf')423-424- self.assertEqual(r.status_code, 200)425- self.assertEqual(r.headers['content-type'], 'application/json')426- self.assertEqual(r.url, service('post'))427-428- rbody = json.loads(r.text)429- # Body wasn't valid url encoded data, so the server returns None as430- # "form" and the raw body as "data".431-432- assert rbody.get('form') in (None, {})433- self.assertEqual(rbody.get('data'), 'fooaowpeuf')434-435-436- def test_urlencoded_post_querystring(self):437-438- for service in SERVICES:439-440- r = post(service('post'), params=dict(test='fooaowpeuf'))441-442- self.assertEqual(r.status_code, 200)443- self.assertEqual(r.headers['content-type'], 'application/json')444- self.assertEqual(r.url, service('post?test=fooaowpeuf'))445-446- rbody = json.loads(r.text)447- self.assertEqual(rbody.get('form'), {}) # No form supplied448- self.assertEqual(rbody.get('data'), '')449-450-451- def test_urlencoded_post_query_and_data(self):452-453- for service in SERVICES:454-455- r = post(456- service('post'),457- params=dict(test='fooaowpeuf'),458- data=dict(test2="foobar"))459-460- self.assertEqual(r.status_code, 200)461- self.assertEqual(r.headers['content-type'], 'application/json')462- self.assertEqual(r.url, service('post?test=fooaowpeuf'))463-464- rbody = json.loads(r.text)465- self.assertEqual(rbody.get('form'), dict(test2='foobar'))466- self.assertEqual(rbody.get('data'), '')467-468-469- def test_nonurlencoded_postdata(self):470-471- for service in SERVICES:472-473- r = post(service('post'), data="foobar")474-475- self.assertEqual(r.status_code, 200)476- self.assertEqual(r.headers['content-type'], 'application/json')477-478- rbody = json.loads(r.text)479-480- assert rbody.get('form') in (None, {})481- self.assertEqual(rbody.get('data'), 'foobar')482-483-484- # def test_idna(self):485- # r = get(u'http://➡.ws/httpbin')486- # assert 'httpbin' in r.url487-488-489- def test_urlencoded_get_query_multivalued_param(self):490-491- for service in SERVICES:492-493- r = get(service('get'), params=dict(test=['foo','baz']))494- self.assertEqual(r.status_code, 200)495- self.assertEqual(r.url, service('get?test=foo&test=baz'))496-497-498- def test_urlencoded_post_querystring_multivalued(self):499-500- for service in SERVICES:501-502- r = post(service('post'), params=dict(test=['foo','baz']))503- self.assertEqual(r.status_code, 200)504- self.assertEqual(r.headers['content-type'], 'application/json')505- self.assertEqual(r.url, service('post?test=foo&test=baz'))506-507- rbody = json.loads(r.text)508- self.assertEqual(rbody.get('form'), {}) # No form supplied509- self.assertEqual(rbody.get('data'), '')510-511-512- def test_urlencoded_post_query_multivalued_and_data(self):513-514- for service in SERVICES:515-516- r = post(517- service('post'),518- params=dict(test=['foo','baz']),519- data=dict(test2="foobar",test3=['foo','baz']))520-521- self.assertEqual(r.status_code, 200)522- self.assertEqual(r.headers['content-type'], 'application/json')523- self.assertEqual(r.url, service('post?test=foo&test=baz'))524-525- # print(r.text)526- # print('-----------------------')527-528- rbody = json.loads(r.text)529- self.assertEqual(rbody.get('form'), dict(test2='foobar',test3=['foo','baz']))530- self.assertEqual(rbody.get('data'), '')531-532-533- def test_GET_no_redirect(self):534-535- for service in SERVICES:536-537- r = get(service('redirect', '3'), allow_redirects=False)538- self.assertEqual(r.status_code, 302)539- self.assertEqual(len(r.history), 0)540-541-542- def test_HEAD_no_redirect(self):543-544- for service in SERVICES:545-546- r = head(service('redirect', '3'), allow_redirects=False)547- self.assertEqual(r.status_code, 302)548- self.assertEqual(len(r.history), 0)549-550-551- def test_redirect_history(self):552-553- for service in SERVICES:554-555- r = get(service('redirect', '3'))556- self.assertEqual(r.status_code, 200)557- self.assertEqual(len(r.history), 3)558-559-560- def test_relative_redirect_history(self):561-562- for service in SERVICES:563-564- r = get(service('relative-redirect', '3'))565- self.assertEqual(r.status_code, 200)566- self.assertEqual(len(r.history), 3)567-568-569- def test_session_HTTP_200_OK_GET(self):570-571- s = requests.session()572- r = get(httpbin('/get'), session=s)573- self.assertEqual(r.status_code, 200)574-575-576- def test_session_persistent_headers(self):577-578- heads = {'User-agent': 'Mozilla/5.0'}579-580- s = requests.session()581- s.headers = heads582-583- # Make 2 requests from Session object, should send header both times584- r1 = get(httpbin('user-agent'), session=s)585- assert heads['User-agent'] in r1.text586-587- r2 = get(httpbin('user-agent'), session=s)588- assert heads['User-agent'] in r2.text589-590- new_heads = {'User-agent': 'blah'}591- r3 = get(httpbin('user-agent'), headers=new_heads, session=s)592- assert new_heads['User-agent'] in r3.text593-594- self.assertEqual(r2.status_code, 200)595-596- def test_single_hook(self):597-598- def add_foo_header(args):599- if not args.get('headers'):600- args['headers'] = {}601-602- args['headers'].update({603- 'X-Foo': 'foo'604- })605-606- return args607-608- for service in SERVICES:609- url = service('headers')610-611- response = get(612- url = url,613- hooks = {614- 'args': add_foo_header615- }616- )617-618- assert 'foo' in response.text619-620- def test_multiple_hooks(self):621-622- def add_foo_header(args):623- if not args.get('headers'):624- args['headers'] = {}625-626- args['headers'].update({627- 'X-Foo': 'foo'628- })629-630- return args631-632- def add_bar_header(args):633- if not args.get('headers'):634- args['headers'] = {}635-636- args['headers'].update({637- 'X-Bar': 'bar'638- })639-640- return args641-642- for service in SERVICES:643- url = service('headers')644-645- response = get(646- url = url,647- hooks = {648- 'args': [add_foo_header, add_bar_header]649- }650- )651-652- assert 'foo' in response.text653- assert 'bar' in response.text654-655- def test_session_persistent_cookies(self):656-657- s = requests.session()658-659- # Internally dispatched cookies are sent.660- _c = {'kenneth': 'reitz', 'bessie': 'monke'}661- r = get(httpbin('cookies'), cookies=_c, session=s)662- r = get(httpbin('cookies'), session=s)663-664- # Those cookies persist transparently.665- c = json.loads(r.text).get('cookies')666- assert c == _c667-668- # Double check.669- r = get(httpbin('cookies'), cookies={}, session=s)670- c = json.loads(r.text).get('cookies')671- assert c == _c672-673- # Remove a cookie by setting it's value to None.674- r = get(httpbin('cookies'), cookies={'bessie': None}, session=s)675- c = json.loads(r.text).get('cookies')676- del _c['bessie']677- assert c == _c678-679- # Test session-level cookies.680- s = requests.session(cookies=_c)681- r = get(httpbin('cookies'), session=s)682- c = json.loads(r.text).get('cookies')683- assert c == _c684-685- # Have the server set a cookie.686- r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)687- c = json.loads(r.text).get('cookies')688-689- assert 'k' in c690-691- # And server-set cookie persistience.692- r = get(httpbin('cookies'), session=s)693- c = json.loads(r.text).get('cookies')694-695- assert 'k' in c696-697-698-699- def test_session_persistent_params(self):700-701- params = {'a': 'a_test'}702-703- s = requests.session()704- s.params = params705-706- # Make 2 requests from Session object, should send header both times707- r1 = get(httpbin('get'), session=s)708- assert params['a'] in r1.text709-710-711- params2 = {'b': 'b_test'}712-713- r2 = get(httpbin('get'), params=params2, session=s)714- assert params['a'] in r2.text715- assert params2['b'] in r2.text716-717-718- params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}719-720- r3 = get(httpbin('get'), params=params3, session=s)721-722- assert not params['a'] in r3.text723- assert params3['b'] in r3.text724- assert params3['c'] in r3.text725-726- def test_invalid_content(self):727- # WARNING: if you're using a terrible DNS provider (comcast),728- # this will fail.729- try:730- hah = 'http://somedomainthatclearlydoesntexistg.com'731- r = get(hah, allow_redirects=False)732- except requests.ConnectionError:733- pass # \o/734- else:735- assert False736-737-738- config = {'safe_mode': True}739- r = get(hah, allow_redirects=False, config=config)740- assert r.content == None741-742- def test_cached_response(self):743-744- r1 = get(httpbin('get'), prefetch=False)745- assert not r1._content746- assert r1.content747- assert r1.text748-749- r2 = get(httpbin('get'), prefetch=True)750- assert r2._content751- assert r2.content752- assert r2.text753-754- def test_iter_lines(self):755-756- lines = (0, 2, 10, 100)757-758- for i in lines:759- r = get(httpbin('stream', str(i)), prefetch=False)760- lines = list(r.iter_lines())761- len_lines = len(lines)762-763- self.assertEqual(i, len_lines)764-765- # Test 'dangling' fragment in responses that do not terminate in766- # a newline.767- quote = (768- '''Why will he not upon our fair request\n'''769- '''Untent his person and share the air with us?'''770- )771-772- # Make a request and monkey-patch its contents773- r = get(httpbin('get'))774- r.raw = StringIO(quote)775-776- # Make sure iter_lines doesn't chop the trailing bit777- lines = '\n'.join(r.iter_lines())778- self.assertEqual(lines, quote)779-780- def test_safe_mode(self):781-782- safe = requests.session(config=dict(safe_mode=True))783-784- # Safe mode creates empty responses for failed requests.785- # Iterating on these responses should produce empty sequences786- r = get('http://_/', session=safe)787- self.assertEqual(list(r.iter_lines()), [])788- assert isinstance(r.error, requests.exceptions.ConnectionError)789-790- r = get('http://_/', session=safe)791- self.assertEqual(list(r.iter_content()), [])792- assert isinstance(r.error, requests.exceptions.ConnectionError)793-794- # When not in safe mode, should raise Timeout exception795- self.assertRaises(796- requests.exceptions.Timeout,797- get,798- httpbin('stream', '1000'), timeout=0.0001)799-800- # In safe mode, should return a blank response801- r = get(httpbin('stream', '1000'), timeout=0.0001,802- config=dict(safe_mode=True))803- assert r.content is None804- assert isinstance(r.error, requests.exceptions.Timeout)805-806- def test_upload_binary_data(self):807-808- r = requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')809-810-811-812-if __name__ == '__main__':813- unittest.main()