test_requests.py
This file
Path
test_requests.py
809 lines · 23.4 KiB · Python
Last changed by
binary data upload bug testKenneth Reitzbefore adoption0d8c08c
History of this fileTake it
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import io5import json6import time7import os8import sys9import unittest1011import requests12from requests.compat import str, bytes, StringIO13# import envoy14from requests import HTTPError15from requests import get, post, head, put16from requests.auth import HTTPBasicAuth, HTTPDigestAuth17181920if (sys.platform == 'win32') and ('HTTPBIN_URL' not in os.environ):21 os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'2223# TODO: Detect an open port.24PORT = os.environ.get('HTTPBIN_PORT', '7077')25HTTPBIN_URL = os.environ.get('HTTPBIN_URL', 'http://0.0.0.0:%s/' % (PORT))262728def httpbin(*suffix):29 """Returns url for HTTPBIN resource."""3031 return HTTPBIN_URL + '/'.join(suffix)323334SERVICES = (httpbin, )3536_httpbin = False3738class TestSetup(object):39 """Requests test cases."""4041 # It goes to eleven.42 _multiprocess_can_split_ = True4344 def setUp(self):4546 global _httpbin4748 if (not 'HTTPBIN_URL' in os.environ) and not _httpbin:49 # c = envoy.connect('httpbin %s' % (PORT))50 # time.sleep(1)51 _httpbin = True525354class RequestsTestSuite(TestSetup, unittest.TestCase):55 """Requests test cases."""5657 def test_entry_points(self):5859 requests.session60 requests.session().get61 requests.session().head62 requests.get63 requests.head64 requests.put65 requests.patch66 requests.post6768 def test_invalid_url(self):69 self.assertRaises(ValueError, get, 'hiwpefhipowhefopw')707172 def test_path_is_not_double_encoded(self):73 request = requests.Request("http://0.0.0.0/get/test case")7475 assert request.path_url == "/get/test%20case"7677 def test_HTTP_200_OK_GET(self):78 r = get(httpbin('/get'))79 self.assertEqual(r.status_code, 200)8081 def test_response_sent(self):82 r = get(httpbin('/get'))8384 self.assertTrue(r.request.sent)8586 def test_HTTP_302_ALLOW_REDIRECT_GET(self):87 r = get(httpbin('redirect', '1'))88 self.assertEqual(r.status_code, 200)8990 def test_HTTP_302_GET(self):91 r = get(httpbin('redirect', '1'), allow_redirects=False)92 self.assertEqual(r.status_code, 302)939495 def test_HTTP_200_OK_GET_WITH_PARAMS(self):96 heads = {'User-agent': 'Mozilla/5.0'}9798 r = get(httpbin('user-agent'), headers=heads)99100 assert heads['User-agent'] in r.text101 self.assertEqual(r.status_code, 200)102103104 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):105 heads = {'User-agent': 'Mozilla/5.0'}106107 r = get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)108 self.assertEqual(r.status_code, 200)109110 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)115116 # 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)120121 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))132133 # 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))141142 # 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))155156 # 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))163164 # 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))169170 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))174175 # 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))180181 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))186187188 def test_user_agent_transfers(self):189 """Issue XX"""190191 heads = {192 'User-agent':193 'Mozilla/5.0 (github.com/kennethreitz/requests)'194 }195196 r = get(httpbin('user-agent'), headers=heads);197 self.assertTrue(heads['User-agent'] in r.text)198199 heads = {200 'user-agent':201 'Mozilla/5.0 (github.com/kennethreitz/requests)'202 }203204 r = get(httpbin('user-agent'), headers=heads);205 self.assertTrue(heads['user-agent'] in r.text)206207208 def test_HTTP_200_OK_HEAD(self):209 r = head(httpbin('/get'))210 self.assertEqual(r.status_code, 200)211212213 def test_HTTP_200_OK_PUT(self):214 r = put(httpbin('put'))215 self.assertEqual(r.status_code, 200)216217218 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):219220 for service in SERVICES:221222 auth = ('user', 'pass')223 url = service('basic-auth', 'user', 'pass')224225 r = get(url, auth=auth)226 self.assertEqual(r.status_code, 200)227228 r = get(url)229 self.assertEqual(r.status_code, 401)230231232 s = requests.session(auth=auth)233 r = get(url, session=s)234 self.assertEqual(r.status_code, 200)235236237 def test_BASICAUTH_HTTP_200_OK_GET(self):238239 for service in SERVICES:240241 auth = HTTPBasicAuth('user', 'pass')242 url = service('basic-auth', 'user', 'pass')243244 r = get(url, auth=auth)245 self.assertEqual(r.status_code, 200)246247 auth = ('user', 'pass')248 r = get(url, auth=auth)249 self.assertEqual(r.status_code, 200)250251 r = get(url)252 self.assertEqual(r.status_code, 401)253254255 s = requests.session(auth=auth)256 r = get(url, session=s)257 self.assertEqual(r.status_code, 200)258259260 def test_DIGESTAUTH_HTTP_200_OK_GET(self):261262 for service in SERVICES:263264 auth = HTTPDigestAuth('user', 'pass')265 url = service('digest-auth', 'auth', 'user', 'pass')266267 r = get(url, auth=auth)268 self.assertEqual(r.status_code, 200)269270 r = get(url)271 self.assertEqual(r.status_code, 401)272273274 s = requests.session(auth=auth)275 r = get(url, session=s)276 self.assertEqual(r.status_code, 200)277278 def test_POSTBIN_GET_POST_FILES(self):279280 for service in SERVICES:281282 url = service('post')283 post1 = post(url).raise_for_status()284285 post1 = post(url, data={'some': 'data'})286 self.assertEqual(post1.status_code, 200)287288 post2 = post(url, files={'some': open('test_requests.py')})289 self.assertEqual(post2.status_code, 200)290291 post3 = post(url, data='[{"some": "json"}]')292 self.assertEqual(post3.status_code, 200)293294295 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):296297 for service in SERVICES:298299 url = service('post')300 post1 = post(url,301 files={'some': open('test_requests.py')},302 data={'some': 'data'})303304 self.assertEqual(post1.status_code, 200)305306307 def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):308309 for service in SERVICES:310311 url = service('post')312313 post2 = post(url,314 files={'some': open('test_requests.py')},315 headers = {'User-Agent': 'requests-tests'})316317 self.assertEqual(post2.status_code, 200)318319320 def test_nonzero_evaluation(self):321322 for service in SERVICES:323324 r = get(service('status', '500'))325 self.assertEqual(bool(r), False)326327 r = get(service('/get'))328 self.assertEqual(bool(r), True)329330331 def test_request_ok_set(self):332333 for service in SERVICES:334335 r = get(service('status', '404'))336 # print r.status_code337 # r.raise_for_status()338 self.assertEqual(r.ok, False)339340341 def test_status_raising(self):342 r = get(httpbin('status', '404'))343 self.assertRaises(HTTPError, r.raise_for_status)344345 r = get(httpbin('status', '200'))346 self.assertFalse(r.error)347 r.raise_for_status()348349350 def test_default_status_raising(self):351 config = {'danger_mode': True}352 args = [httpbin('status', '404')]353 kwargs = dict(config=config)354 self.assertRaises(HTTPError, get, *args, **kwargs)355356 r = get(httpbin('status', '200'))357 self.assertEqual(r.status_code, 200)358359360 def test_decompress_gzip(self):361362 r = get(httpbin('gzip'))363 r.content.decode('ascii')364365 def test_response_has_unicode_url(self):366367 for service in SERVICES:368369 url = service('get')370371 response = get(url)372373 assert isinstance(response.url, str)374375376 def test_unicode_get(self):377378 for service in SERVICES:379380 url = service('/get')381382 get(url, params={'foo': 'føø'})383 get(url, params={'føø': 'føø'})384 get(url, params={'føø': 'føø'})385 get(url, params={'foo': 'foo'})386 get(service('ø'), params={'foo': 'foo'})387388389 def test_httpauth_recursion(self):390391 http_auth = HTTPBasicAuth('user', 'BADpass')392393 for service in SERVICES:394 r = get(service('basic-auth', 'user', 'pass'), auth=http_auth)395 self.assertEqual(r.status_code, 401)396397398 def test_urlencoded_post_data(self):399400 for service in SERVICES:401402 r = post(service('post'), data=dict(test='fooaowpeuf'))403404 self.assertEqual(r.status_code, 200)405 self.assertEqual(r.headers['content-type'], 'application/json')406 self.assertEqual(r.url, service('post'))407408 rbody = json.loads(r.text)409410 self.assertEqual(rbody.get('form'), dict(test='fooaowpeuf'))411 self.assertEqual(rbody.get('data'), '')412413414 def test_nonurlencoded_post_data(self):415416 for service in SERVICES:417418 r = post(service('post'), data='fooaowpeuf')419420 self.assertEqual(r.status_code, 200)421 self.assertEqual(r.headers['content-type'], 'application/json')422 self.assertEqual(r.url, service('post'))423424 rbody = json.loads(r.text)425 # Body wasn't valid url encoded data, so the server returns None as426 # "form" and the raw body as "data".427428 assert rbody.get('form') in (None, {})429 self.assertEqual(rbody.get('data'), 'fooaowpeuf')430431432 def test_urlencoded_post_querystring(self):433434 for service in SERVICES:435436 r = post(service('post'), params=dict(test='fooaowpeuf'))437438 self.assertEqual(r.status_code, 200)439 self.assertEqual(r.headers['content-type'], 'application/json')440 self.assertEqual(r.url, service('post?test=fooaowpeuf'))441442 rbody = json.loads(r.text)443 self.assertEqual(rbody.get('form'), {}) # No form supplied444 self.assertEqual(rbody.get('data'), '')445446447 def test_urlencoded_post_query_and_data(self):448449 for service in SERVICES:450451 r = post(452 service('post'),453 params=dict(test='fooaowpeuf'),454 data=dict(test2="foobar"))455456 self.assertEqual(r.status_code, 200)457 self.assertEqual(r.headers['content-type'], 'application/json')458 self.assertEqual(r.url, service('post?test=fooaowpeuf'))459460 rbody = json.loads(r.text)461 self.assertEqual(rbody.get('form'), dict(test2='foobar'))462 self.assertEqual(rbody.get('data'), '')463464465 def test_nonurlencoded_postdata(self):466467 for service in SERVICES:468469 r = post(service('post'), data="foobar")470471 self.assertEqual(r.status_code, 200)472 self.assertEqual(r.headers['content-type'], 'application/json')473474 rbody = json.loads(r.text)475476 assert rbody.get('form') in (None, {})477 self.assertEqual(rbody.get('data'), 'foobar')478479480 # def test_idna(self):481 # r = get(u'http://➡.ws/httpbin')482 # assert 'httpbin' in r.url483484485 def test_urlencoded_get_query_multivalued_param(self):486487 for service in SERVICES:488489 r = get(service('get'), params=dict(test=['foo','baz']))490 self.assertEqual(r.status_code, 200)491 self.assertEqual(r.url, service('get?test=foo&test=baz'))492493494 def test_urlencoded_post_querystring_multivalued(self):495496 for service in SERVICES:497498 r = post(service('post'), params=dict(test=['foo','baz']))499 self.assertEqual(r.status_code, 200)500 self.assertEqual(r.headers['content-type'], 'application/json')501 self.assertEqual(r.url, service('post?test=foo&test=baz'))502503 rbody = json.loads(r.text)504 self.assertEqual(rbody.get('form'), {}) # No form supplied505 self.assertEqual(rbody.get('data'), '')506507508 def test_urlencoded_post_query_multivalued_and_data(self):509510 for service in SERVICES:511512 r = post(513 service('post'),514 params=dict(test=['foo','baz']),515 data=dict(test2="foobar",test3=['foo','baz']))516517 self.assertEqual(r.status_code, 200)518 self.assertEqual(r.headers['content-type'], 'application/json')519 self.assertEqual(r.url, service('post?test=foo&test=baz'))520521 # print(r.text)522 # print('-----------------------')523524 rbody = json.loads(r.text)525 self.assertEqual(rbody.get('form'), dict(test2='foobar',test3=['foo','baz']))526 self.assertEqual(rbody.get('data'), '')527528529 def test_GET_no_redirect(self):530531 for service in SERVICES:532533 r = get(service('redirect', '3'), allow_redirects=False)534 self.assertEqual(r.status_code, 302)535 self.assertEqual(len(r.history), 0)536537538 def test_HEAD_no_redirect(self):539540 for service in SERVICES:541542 r = head(service('redirect', '3'), allow_redirects=False)543 self.assertEqual(r.status_code, 302)544 self.assertEqual(len(r.history), 0)545546547 def test_redirect_history(self):548549 for service in SERVICES:550551 r = get(service('redirect', '3'))552 self.assertEqual(r.status_code, 200)553 self.assertEqual(len(r.history), 3)554555556 def test_relative_redirect_history(self):557558 for service in SERVICES:559560 r = get(service('relative-redirect', '3'))561 self.assertEqual(r.status_code, 200)562 self.assertEqual(len(r.history), 3)563564565 def test_session_HTTP_200_OK_GET(self):566567 s = requests.session()568 r = get(httpbin('/get'), session=s)569 self.assertEqual(r.status_code, 200)570571572 def test_session_persistent_headers(self):573574 heads = {'User-agent': 'Mozilla/5.0'}575576 s = requests.session()577 s.headers = heads578579 # Make 2 requests from Session object, should send header both times580 r1 = get(httpbin('user-agent'), session=s)581 assert heads['User-agent'] in r1.text582583 r2 = get(httpbin('user-agent'), session=s)584 assert heads['User-agent'] in r2.text585586 new_heads = {'User-agent': 'blah'}587 r3 = get(httpbin('user-agent'), headers=new_heads, session=s)588 assert new_heads['User-agent'] in r3.text589590 self.assertEqual(r2.status_code, 200)591592 def test_single_hook(self):593594 def add_foo_header(args):595 if not args.get('headers'):596 args['headers'] = {}597598 args['headers'].update({599 'X-Foo': 'foo'600 })601602 return args603604 for service in SERVICES:605 url = service('headers')606607 response = get(608 url = url,609 hooks = {610 'args': add_foo_header611 }612 )613614 assert 'foo' in response.text615616 def test_multiple_hooks(self):617618 def add_foo_header(args):619 if not args.get('headers'):620 args['headers'] = {}621622 args['headers'].update({623 'X-Foo': 'foo'624 })625626 return args627628 def add_bar_header(args):629 if not args.get('headers'):630 args['headers'] = {}631632 args['headers'].update({633 'X-Bar': 'bar'634 })635636 return args637638 for service in SERVICES:639 url = service('headers')640641 response = get(642 url = url,643 hooks = {644 'args': [add_foo_header, add_bar_header]645 }646 )647648 assert 'foo' in response.text649 assert 'bar' in response.text650651 def test_session_persistent_cookies(self):652653 s = requests.session()654655 # Internally dispatched cookies are sent.656 _c = {'kenneth': 'reitz', 'bessie': 'monke'}657 r = get(httpbin('cookies'), cookies=_c, session=s)658 r = get(httpbin('cookies'), session=s)659660 # Those cookies persist transparently.661 c = json.loads(r.text).get('cookies')662 assert c == _c663664 # Double check.665 r = get(httpbin('cookies'), cookies={}, session=s)666 c = json.loads(r.text).get('cookies')667 assert c == _c668669 # Remove a cookie by setting it's value to None.670 r = get(httpbin('cookies'), cookies={'bessie': None}, session=s)671 c = json.loads(r.text).get('cookies')672 del _c['bessie']673 assert c == _c674675 # Test session-level cookies.676 s = requests.session(cookies=_c)677 r = get(httpbin('cookies'), session=s)678 c = json.loads(r.text).get('cookies')679 assert c == _c680681 # Have the server set a cookie.682 r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)683 c = json.loads(r.text).get('cookies')684685 assert 'k' in c686687 # And server-set cookie persistience.688 r = get(httpbin('cookies'), session=s)689 c = json.loads(r.text).get('cookies')690691 assert 'k' in c692693694695 def test_session_persistent_params(self):696697 params = {'a': 'a_test'}698699 s = requests.session()700 s.params = params701702 # Make 2 requests from Session object, should send header both times703 r1 = get(httpbin('get'), session=s)704 assert params['a'] in r1.text705706707 params2 = {'b': 'b_test'}708709 r2 = get(httpbin('get'), params=params2, session=s)710 assert params['a'] in r2.text711 assert params2['b'] in r2.text712713714 params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}715716 r3 = get(httpbin('get'), params=params3, session=s)717718 assert not params['a'] in r3.text719 assert params3['b'] in r3.text720 assert params3['c'] in r3.text721722 def test_invalid_content(self):723 # WARNING: if you're using a terrible DNS provider (comcast),724 # this will fail.725 try:726 hah = 'http://somedomainthatclearlydoesntexistg.com'727 r = get(hah, allow_redirects=False)728 except requests.ConnectionError:729 pass # \o/730 else:731 assert False732733734 config = {'safe_mode': True}735 r = get(hah, allow_redirects=False, config=config)736 assert r.content == None737738 def test_cached_response(self):739740 r1 = get(httpbin('get'), prefetch=False)741 assert not r1._content742 assert r1.content743 assert r1.text744745 r2 = get(httpbin('get'), prefetch=True)746 assert r2._content747 assert r2.content748 assert r2.text749750 def test_iter_lines(self):751752 lines = (0, 2, 10, 100)753754 for i in lines:755 r = get(httpbin('stream', str(i)), prefetch=False)756 lines = list(r.iter_lines())757 len_lines = len(lines)758759 self.assertEqual(i, len_lines)760761 # Test 'dangling' fragment in responses that do not terminate in762 # a newline.763 quote = (764 '''Why will he not upon our fair request\n'''765 '''Untent his person and share the air with us?'''766 )767768 # Make a request and monkey-patch its contents769 r = get(httpbin('get'))770 r.raw = StringIO(quote)771772 # Make sure iter_lines doesn't chop the trailing bit773 lines = '\n'.join(r.iter_lines())774 self.assertEqual(lines, quote)775776 def test_safe_mode(self):777778 safe = requests.session(config=dict(safe_mode=True))779780 # Safe mode creates empty responses for failed requests.781 # Iterating on these responses should produce empty sequences782 r = get('http://_/', session=safe)783 self.assertEqual(list(r.iter_lines()), [])784 assert isinstance(r.error, requests.exceptions.ConnectionError)785786 r = get('http://_/', session=safe)787 self.assertEqual(list(r.iter_content()), [])788 assert isinstance(r.error, requests.exceptions.ConnectionError)789790 # When not in safe mode, should raise Timeout exception791 self.assertRaises(792 requests.exceptions.Timeout,793 get,794 httpbin('stream', '1000'), timeout=0.0001)795796 # In safe mode, should return a blank response797 r = get(httpbin('stream', '1000'), timeout=0.0001,798 config=dict(safe_mode=True))799 assert r.content is None800 assert isinstance(r.error, requests.exceptions.Timeout)801802 def test_upload_binary_data(self):803804 r = requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')805806807808if __name__ == '__main__':809 unittest.main()