Skip to content
Myr

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

7 files+936 added−924 removed

added:tests/test_requests_async.py+62 added
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34# Path hack.5import sys, os6sys.path.insert(0, os.path.abspath('..'))78import sys9import unittest1011from requests import async12import envoy1314sys.path.append('.')15from test_requests import httpbin, RequestsTestSuite, SERVICES161718class RequestsTestSuiteUsingAsyncApi(RequestsTestSuite):19 """Requests async test cases."""2021 def patched(f):22 """Automatically send request after creation."""2324 def wrapped(*args, **kwargs):2526 request = f(*args, **kwargs)27 return async.map([request])[0]2829 return wrapped3031 # Patched requests.api functions.32 global request33 request = patched(async.request)3435 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)434445 def test_entry_points(self):4647 async.request4849 async.delete50 async.get51 async.head52 async.options53 async.patch54 async.post55 async.put5657 async.map58 async.send596061if __name__ == '__main__':62 unittest.main()
added:tests/test_requests_ext.py+54 added
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34# Path hack.5import sys, os6sys.path.insert(0, os.path.abspath('..'))78import unittest910import requests1112try:13 import omnijson as json14except ImportError:15 import json161718class RequestsTestSuite(unittest.TestCase):19 """Requests test cases."""2021 # It goes to eleven.22 _multiprocess_can_split_ = True2324 def test_addition(self):25 assert (1 + 1) == 2262728 def test_ssl_hostname_ok(self):29 requests.get('https://github.com', verify=True)303132 def test_ssl_hostname_not_ok(self):33 requests.get('https://kennethreitz.com', verify=False)3435 self.assertRaises(requests.exceptions.SSLError, requests.get, 'https://kennethreitz.com')363738 def test_ssl_hostname_session_not_ok(self):3940 s = requests.session()4142 self.assertRaises(requests.exceptions.SSLError, s.get, 'https://kennethreitz.com')4344 s.get('https://kennethreitz.com', verify=False)454647 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)505152if __name__ == '__main__':53 unittest.main()54
added:tests/test_requests.py+819 added
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34# from __future__ import unicode_literals56# Path hack.7import sys, os8sys.path.insert(0, os.path.abspath('..'))910import io11import json12import time13import os14import sys15import unittest1617import requests18from requests.compat import str, bytes, StringIO19# import envoy20from requests import HTTPError21from requests import get, post, head, put22from requests.auth import HTTPBasicAuth, HTTPDigestAuth23242526if (sys.platform == 'win32') and ('HTTPBIN_URL' not in os.environ):27 os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'2829# TODO: Detect an open port.30PORT = os.environ.get('HTTPBIN_PORT', '7077')31HTTPBIN_URL = os.environ.get('HTTPBIN_URL', 'http://0.0.0.0:%s/' % (PORT))323334def httpbin(*suffix):35 """Returns url for HTTPBIN resource."""3637 return HTTPBIN_URL + '/'.join(suffix)383940SERVICES = (httpbin, )4142_httpbin = False4344class TestSetup(object):45 """Requests test cases."""4647 # It goes to eleven.48 _multiprocess_can_split_ = True4950 def setUp(self):5152 global _httpbin5354 if (not 'HTTPBIN_URL' in os.environ) and not _httpbin:55 # c = envoy.connect('httpbin %s' % (PORT))56 # time.sleep(1)57 _httpbin = True585960class RequestsTestSuite(TestSetup, unittest.TestCase):61 """Requests test cases."""6263 def test_entry_points(self):6465 requests.session66 requests.session().get67 requests.session().head68 requests.get69 requests.head70 requests.put71 requests.patch72 requests.post7374 def test_invalid_url(self):75 self.assertRaises(ValueError, get, 'hiwpefhipowhefopw')767778 def test_path_is_not_double_encoded(self):79 request = requests.Request("http://0.0.0.0/get/test case")8081 assert request.path_url == "/get/test%20case"8283 def test_HTTP_200_OK_GET(self):84 r = get(httpbin('/get'))85 self.assertEqual(r.status_code, 200)8687 def test_response_sent(self):88 r = get(httpbin('/get'))8990 self.assertTrue(r.request.sent)9192 def test_HTTP_302_ALLOW_REDIRECT_GET(self):93 r = get(httpbin('redirect', '1'))94 self.assertEqual(r.status_code, 200)9596 def test_HTTP_302_GET(self):97 r = get(httpbin('redirect', '1'), allow_redirects=False)98 self.assertEqual(r.status_code, 302)99100101 def test_HTTP_200_OK_GET_WITH_PARAMS(self):102 heads = {'User-agent': 'Mozilla/5.0'}103104 r = get(httpbin('user-agent'), headers=heads)105106 assert heads['User-agent'] in r.text107 self.assertEqual(r.status_code, 200)108109110 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):111 heads = {'User-agent': 'Mozilla/5.0'}112113 r = get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)114 self.assertEqual(r.status_code, 200)115116 # 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)121122 # # 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)126127 # 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))138139 # # 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))147148 # # 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))161162 # # 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))169170 # # 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))175176 # 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))180181 # # 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))186187 # 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))192193194 def test_user_agent_transfers(self):195 """Issue XX"""196197 heads = {198 'User-agent':199 'Mozilla/5.0 (github.com/kennethreitz/requests)'200 }201202 r = get(httpbin('user-agent'), headers=heads);203 self.assertTrue(heads['User-agent'] in r.text)204205 heads = {206 'user-agent':207 'Mozilla/5.0 (github.com/kennethreitz/requests)'208 }209210 r = get(httpbin('user-agent'), headers=heads);211 self.assertTrue(heads['user-agent'] in r.text)212213214 def test_HTTP_200_OK_HEAD(self):215 r = head(httpbin('/get'))216 self.assertEqual(r.status_code, 200)217218219 def test_HTTP_200_OK_PUT(self):220 r = put(httpbin('put'))221 self.assertEqual(r.status_code, 200)222223224 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):225226 for service in SERVICES:227228 auth = ('user', 'pass')229 url = service('basic-auth', 'user', 'pass')230231 r = get(url, auth=auth)232 self.assertEqual(r.status_code, 200)233234 r = get(url)235 self.assertEqual(r.status_code, 401)236237238 s = requests.session(auth=auth)239 r = get(url, session=s)240 self.assertEqual(r.status_code, 200)241242243 def test_BASICAUTH_HTTP_200_OK_GET(self):244245 for service in SERVICES:246247 auth = HTTPBasicAuth('user', 'pass')248 url = service('basic-auth', 'user', 'pass')249250 r = get(url, auth=auth)251 self.assertEqual(r.status_code, 200)252253 auth = ('user', 'pass')254 r = get(url, auth=auth)255 self.assertEqual(r.status_code, 200)256257 r = get(url)258 self.assertEqual(r.status_code, 401)259260261 s = requests.session(auth=auth)262 r = get(url, session=s)263 self.assertEqual(r.status_code, 200)264265266 def test_DIGESTAUTH_HTTP_200_OK_GET(self):267268 for service in SERVICES:269270 auth = HTTPDigestAuth('user', 'pass')271 url = service('digest-auth', 'auth', 'user', 'pass')272273 r = get(url, auth=auth)274 self.assertEqual(r.status_code, 200)275276 r = get(url)277 self.assertEqual(r.status_code, 401)278279280 s = requests.session(auth=auth)281 r = get(url, session=s)282 self.assertEqual(r.status_code, 200)283284 def test_POSTBIN_GET_POST_FILES(self):285286 for service in SERVICES:287288 url = service('post')289 post1 = post(url).raise_for_status()290291 post1 = post(url, data={'some': 'data'})292 self.assertEqual(post1.status_code, 200)293294 with open('test_requests.py') as f:295 post2 = post(url, files={'some': f})296 self.assertEqual(post2.status_code, 200)297298 post3 = post(url, data='[{"some": "json"}]')299 self.assertEqual(post3.status_code, 200)300301302 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):303304 for service in SERVICES:305306 with open('test_requests.py') as f:307 url = service('post')308 post1 = post(url,309 files={'some': f},310 data={'some': 'data'})311312 self.assertEqual(post1.status_code, 200)313314315 def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):316317 for service in SERVICES:318319 url = service('post')320321 with open('test_requests.py') as f:322323 post2 = post(url,324 files={'some': f},325 headers = {'User-Agent': 'requests-tests'})326327 self.assertEqual(post2.status_code, 200)328329330 def test_nonzero_evaluation(self):331332 for service in SERVICES:333334 r = get(service('status', '500'))335 self.assertEqual(bool(r), False)336337 r = get(service('/get'))338 self.assertEqual(bool(r), True)339340341 def test_request_ok_set(self):342343 for service in SERVICES:344345 r = get(service('status', '404'))346 # print r.status_code347 # r.raise_for_status()348 self.assertEqual(r.ok, False)349350351 def test_status_raising(self):352 r = get(httpbin('status', '404'))353 self.assertRaises(HTTPError, r.raise_for_status)354355 r = get(httpbin('status', '200'))356 self.assertFalse(r.error)357 r.raise_for_status()358359360 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)365366 r = get(httpbin('status', '200'))367 self.assertEqual(r.status_code, 200)368369370 def test_decompress_gzip(self):371372 r = get(httpbin('gzip'))373 r.content.decode('ascii')374375 def test_response_has_unicode_url(self):376377 for service in SERVICES:378379 url = service('get')380381 response = get(url)382383 assert isinstance(response.url, str)384385386 def test_unicode_get(self):387388 for service in SERVICES:389390 url = service('/get')391392 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'})397398399 def test_httpauth_recursion(self):400401 http_auth = HTTPBasicAuth('user', 'BADpass')402403 for service in SERVICES:404 r = get(service('basic-auth', 'user', 'pass'), auth=http_auth)405 self.assertEqual(r.status_code, 401)406407408 def test_urlencoded_post_data(self):409410 for service in SERVICES:411412 r = post(service('post'), data=dict(test='fooaowpeuf'))413414 self.assertEqual(r.status_code, 200)415 self.assertEqual(r.headers['content-type'], 'application/json')416 self.assertEqual(r.url, service('post'))417418 rbody = json.loads(r.text)419420 self.assertEqual(rbody.get('form'), dict(test='fooaowpeuf'))421 self.assertEqual(rbody.get('data'), '')422423424 def test_nonurlencoded_post_data(self):425426 for service in SERVICES:427428 r = post(service('post'), data='fooaowpeuf')429430 self.assertEqual(r.status_code, 200)431 self.assertEqual(r.headers['content-type'], 'application/json')432 self.assertEqual(r.url, service('post'))433434 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".437438 assert rbody.get('form') in (None, {})439 self.assertEqual(rbody.get('data'), 'fooaowpeuf')440441442 def test_urlencoded_post_querystring(self):443444 for service in SERVICES:445446 r = post(service('post'), params=dict(test='fooaowpeuf'))447448 self.assertEqual(r.status_code, 200)449 self.assertEqual(r.headers['content-type'], 'application/json')450 self.assertEqual(r.url, service('post?test=fooaowpeuf'))451452 rbody = json.loads(r.text)453 self.assertEqual(rbody.get('form'), {}) # No form supplied454 self.assertEqual(rbody.get('data'), '')455456457 def test_urlencoded_post_query_and_data(self):458459 for service in SERVICES:460461 r = post(462 service('post'),463 params=dict(test='fooaowpeuf'),464 data=dict(test2="foobar"))465466 self.assertEqual(r.status_code, 200)467 self.assertEqual(r.headers['content-type'], 'application/json')468 self.assertEqual(r.url, service('post?test=fooaowpeuf'))469470 rbody = json.loads(r.text)471 self.assertEqual(rbody.get('form'), dict(test2='foobar'))472 self.assertEqual(rbody.get('data'), '')473474475 def test_nonurlencoded_postdata(self):476477 for service in SERVICES:478479 r = post(service('post'), data="foobar")480481 self.assertEqual(r.status_code, 200)482 self.assertEqual(r.headers['content-type'], 'application/json')483484 rbody = json.loads(r.text)485486 assert rbody.get('form') in (None, {})487 self.assertEqual(rbody.get('data'), 'foobar')488489490 # def test_idna(self):491 # r = get(u'http://➡.ws/httpbin')492 # assert 'httpbin' in r.url493494495 def test_urlencoded_get_query_multivalued_param(self):496497 for service in SERVICES:498499 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'))502503504 def test_urlencoded_post_querystring_multivalued(self):505506 for service in SERVICES:507508 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'))512513 rbody = json.loads(r.text)514 self.assertEqual(rbody.get('form'), {}) # No form supplied515 self.assertEqual(rbody.get('data'), '')516517518 def test_urlencoded_post_query_multivalued_and_data(self):519520 for service in SERVICES:521522 r = post(523 service('post'),524 params=dict(test=['foo','baz']),525 data=dict(test2="foobar",test3=['foo','baz']))526527 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'))530531 # print(r.text)532 # print('-----------------------')533534 rbody = json.loads(r.text)535 self.assertEqual(rbody.get('form'), dict(test2='foobar',test3=['foo','baz']))536 self.assertEqual(rbody.get('data'), '')537538539 def test_GET_no_redirect(self):540541 for service in SERVICES:542543 r = get(service('redirect', '3'), allow_redirects=False)544 self.assertEqual(r.status_code, 302)545 self.assertEqual(len(r.history), 0)546547548 def test_HEAD_no_redirect(self):549550 for service in SERVICES:551552 r = head(service('redirect', '3'), allow_redirects=False)553 self.assertEqual(r.status_code, 302)554 self.assertEqual(len(r.history), 0)555556557 def test_redirect_history(self):558559 for service in SERVICES:560561 r = get(service('redirect', '3'))562 self.assertEqual(r.status_code, 200)563 self.assertEqual(len(r.history), 3)564565566 def test_relative_redirect_history(self):567568 for service in SERVICES:569570 r = get(service('relative-redirect', '3'))571 self.assertEqual(r.status_code, 200)572 self.assertEqual(len(r.history), 3)573574575 def test_session_HTTP_200_OK_GET(self):576577 s = requests.session()578 r = get(httpbin('/get'), session=s)579 self.assertEqual(r.status_code, 200)580581582 def test_session_persistent_headers(self):583584 heads = {'User-agent': 'Mozilla/5.0'}585586 s = requests.session()587 s.headers = heads588589 # 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.text592593 r2 = get(httpbin('user-agent'), session=s)594 assert heads['User-agent'] in r2.text595596 new_heads = {'User-agent': 'blah'}597 r3 = get(httpbin('user-agent'), headers=new_heads, session=s)598 assert new_heads['User-agent'] in r3.text599600 self.assertEqual(r2.status_code, 200)601602 def test_single_hook(self):603604 def add_foo_header(args):605 if not args.get('headers'):606 args['headers'] = {}607608 args['headers'].update({609 'X-Foo': 'foo'610 })611612 return args613614 for service in SERVICES:615 url = service('headers')616617 response = get(618 url = url,619 hooks = {620 'args': add_foo_header621 }622 )623624 assert 'foo' in response.text625626 def test_multiple_hooks(self):627628 def add_foo_header(args):629 if not args.get('headers'):630 args['headers'] = {}631632 args['headers'].update({633 'X-Foo': 'foo'634 })635636 return args637638 def add_bar_header(args):639 if not args.get('headers'):640 args['headers'] = {}641642 args['headers'].update({643 'X-Bar': 'bar'644 })645646 return args647648 for service in SERVICES:649 url = service('headers')650651 response = get(652 url = url,653 hooks = {654 'args': [add_foo_header, add_bar_header]655 }656 )657658 assert 'foo' in response.text659 assert 'bar' in response.text660661 def test_session_persistent_cookies(self):662663 s = requests.session()664665 # 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)669670 # Those cookies persist transparently.671 c = json.loads(r.text).get('cookies')672 assert c == _c673674 # Double check.675 r = get(httpbin('cookies'), cookies={}, session=s)676 c = json.loads(r.text).get('cookies')677 assert c == _c678679 # 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 == _c684685 # 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 == _c690691 # 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')694695 assert 'k' in c696697 # And server-set cookie persistience.698 r = get(httpbin('cookies'), session=s)699 c = json.loads(r.text).get('cookies')700701 assert 'k' in c702703704705 def test_session_persistent_params(self):706707 params = {'a': 'a_test'}708709 s = requests.session()710 s.params = params711712 # Make 2 requests from Session object, should send header both times713 r1 = get(httpbin('get'), session=s)714 assert params['a'] in r1.text715716717 params2 = {'b': 'b_test'}718719 r2 = get(httpbin('get'), params=params2, session=s)720 assert params['a'] in r2.text721 assert params2['b'] in r2.text722723724 params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}725726 r3 = get(httpbin('get'), params=params3, session=s)727728 assert not params['a'] in r3.text729 assert params3['b'] in r3.text730 assert params3['c'] in r3.text731732 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 False742743744 config = {'safe_mode': True}745 r = get(hah, allow_redirects=False, config=config)746 assert r.content == None747748 def test_cached_response(self):749750 r1 = get(httpbin('get'), prefetch=False)751 assert not r1._content752 assert r1.content753 assert r1.text754755 r2 = get(httpbin('get'), prefetch=True)756 assert r2._content757 assert r2.content758 assert r2.text759760 def test_iter_lines(self):761762 lines = (0, 2, 10, 100)763764 for i in lines:765 r = get(httpbin('stream', str(i)), prefetch=False)766 lines = list(r.iter_lines())767 len_lines = len(lines)768769 self.assertEqual(i, len_lines)770771 # 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 )777778 # Make a request and monkey-patch its contents779 r = get(httpbin('get'))780 r.raw = StringIO(quote)781782 # Make sure iter_lines doesn't chop the trailing bit783 lines = '\n'.join(r.iter_lines())784 self.assertEqual(lines, quote)785786 def test_safe_mode(self):787788 safe = requests.session(config=dict(safe_mode=True))789790 # 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)795796 r = get('http://_/', session=safe)797 self.assertEqual(list(r.iter_content()), [])798 assert isinstance(r.error, requests.exceptions.ConnectionError)799800 # When not in safe mode, should raise Timeout exception801 self.assertRaises(802 requests.exceptions.Timeout,803 get,804 httpbin('stream', '1000'), timeout=0.0001)805806 # 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)811812 def test_upload_binary_data(self):813814 r = requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')815816817818if __name__ == '__main__':819 unittest.main()
modified:Makefile+1 added-1 removed
3 unmodified lines
4 python setup.py develop5 pip install -r requirements.txt67test:8 nosetests --with-color ./test_*8 nosetests --with-color ./tests/*910lazy:11 nosetests --with-color test_requests.py12
23 unmodified lines
deleted:test_requests_async.py-58 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import sys5import unittest67from requests import async8import envoy910sys.path.append('.')11from test_requests import httpbin, RequestsTestSuite, SERVICES121314class RequestsTestSuiteUsingAsyncApi(RequestsTestSuite):15 """Requests async test cases."""1617 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 wrapped2627 # 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)394041 def test_entry_points(self):4243 async.request44 45 async.delete 46 async.get47 async.head48 async.options49 async.patch50 async.post51 async.put52 53 async.map54 async.send55 5657if __name__ == '__main__':58 unittest.main()
deleted:test_requests_ext.py-52 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34from __future__ import with_statement56import unittest78import requests910try:11 import omnijson as json12except ImportError:13 import json141516class RequestsTestSuite(unittest.TestCase):17 """Requests test cases."""1819 # It goes to eleven.20 _multiprocess_can_split_ = True2122 def test_addition(self):23 assert (1 + 1) == 2242526 def test_ssl_hostname_ok(self):27 requests.get('https://github.com', verify=True)282930 def test_ssl_hostname_not_ok(self):31 requests.get('https://kennethreitz.com', verify=False)3233 self.assertRaises(requests.exceptions.SSLError, requests.get, 'https://kennethreitz.com')343536 def test_ssl_hostname_session_not_ok(self):3738 s = requests.session()3940 self.assertRaises(requests.exceptions.SSLError, s.get, 'https://kennethreitz.com')4142 s.get('https://kennethreitz.com', verify=False)434445 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)484950if __name__ == '__main__':51 unittest.main()52
deleted:test_requests.py-813 removed
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 with open('test_requests.py') as f:289 post2 = post(url, files={'some': f})290 self.assertEqual(post2.status_code, 200)291292 post3 = post(url, data='[{"some": "json"}]')293 self.assertEqual(post3.status_code, 200)294295296 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):297298 for service in SERVICES:299300 with open('test_requests.py') as f:301 url = service('post')302 post1 = post(url,303 files={'some': f},304 data={'some': 'data'})305306 self.assertEqual(post1.status_code, 200)307308309 def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):310311 for service in SERVICES:312313 url = service('post')314315 with open('test_requests.py') as f:316317 post2 = post(url,318 files={'some': f},319 headers = {'User-Agent': 'requests-tests'})320321 self.assertEqual(post2.status_code, 200)322323324 def test_nonzero_evaluation(self):325326 for service in SERVICES:327328 r = get(service('status', '500'))329 self.assertEqual(bool(r), False)330331 r = get(service('/get'))332 self.assertEqual(bool(r), True)333334335 def test_request_ok_set(self):336337 for service in SERVICES:338339 r = get(service('status', '404'))340 # print r.status_code341 # r.raise_for_status()342 self.assertEqual(r.ok, False)343344345 def test_status_raising(self):346 r = get(httpbin('status', '404'))347 self.assertRaises(HTTPError, r.raise_for_status)348349 r = get(httpbin('status', '200'))350 self.assertFalse(r.error)351 r.raise_for_status()352353354 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)359360 r = get(httpbin('status', '200'))361 self.assertEqual(r.status_code, 200)362363364 def test_decompress_gzip(self):365366 r = get(httpbin('gzip'))367 r.content.decode('ascii')368369 def test_response_has_unicode_url(self):370371 for service in SERVICES:372373 url = service('get')374375 response = get(url)376377 assert isinstance(response.url, str)378379380 def test_unicode_get(self):381382 for service in SERVICES:383384 url = service('/get')385386 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'})391392393 def test_httpauth_recursion(self):394395 http_auth = HTTPBasicAuth('user', 'BADpass')396397 for service in SERVICES:398 r = get(service('basic-auth', 'user', 'pass'), auth=http_auth)399 self.assertEqual(r.status_code, 401)400401402 def test_urlencoded_post_data(self):403404 for service in SERVICES:405406 r = post(service('post'), data=dict(test='fooaowpeuf'))407408 self.assertEqual(r.status_code, 200)409 self.assertEqual(r.headers['content-type'], 'application/json')410 self.assertEqual(r.url, service('post'))411412 rbody = json.loads(r.text)413414 self.assertEqual(rbody.get('form'), dict(test='fooaowpeuf'))415 self.assertEqual(rbody.get('data'), '')416417418 def test_nonurlencoded_post_data(self):419420 for service in SERVICES:421422 r = post(service('post'), data='fooaowpeuf')423424 self.assertEqual(r.status_code, 200)425 self.assertEqual(r.headers['content-type'], 'application/json')426 self.assertEqual(r.url, service('post'))427428 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".431432 assert rbody.get('form') in (None, {})433 self.assertEqual(rbody.get('data'), 'fooaowpeuf')434435436 def test_urlencoded_post_querystring(self):437438 for service in SERVICES:439440 r = post(service('post'), params=dict(test='fooaowpeuf'))441442 self.assertEqual(r.status_code, 200)443 self.assertEqual(r.headers['content-type'], 'application/json')444 self.assertEqual(r.url, service('post?test=fooaowpeuf'))445446 rbody = json.loads(r.text)447 self.assertEqual(rbody.get('form'), {}) # No form supplied448 self.assertEqual(rbody.get('data'), '')449450451 def test_urlencoded_post_query_and_data(self):452453 for service in SERVICES:454455 r = post(456 service('post'),457 params=dict(test='fooaowpeuf'),458 data=dict(test2="foobar"))459460 self.assertEqual(r.status_code, 200)461 self.assertEqual(r.headers['content-type'], 'application/json')462 self.assertEqual(r.url, service('post?test=fooaowpeuf'))463464 rbody = json.loads(r.text)465 self.assertEqual(rbody.get('form'), dict(test2='foobar'))466 self.assertEqual(rbody.get('data'), '')467468469 def test_nonurlencoded_postdata(self):470471 for service in SERVICES:472473 r = post(service('post'), data="foobar")474475 self.assertEqual(r.status_code, 200)476 self.assertEqual(r.headers['content-type'], 'application/json')477478 rbody = json.loads(r.text)479480 assert rbody.get('form') in (None, {})481 self.assertEqual(rbody.get('data'), 'foobar')482483484 # def test_idna(self):485 # r = get(u'http://➡.ws/httpbin')486 # assert 'httpbin' in r.url487488489 def test_urlencoded_get_query_multivalued_param(self):490491 for service in SERVICES:492493 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'))496497498 def test_urlencoded_post_querystring_multivalued(self):499500 for service in SERVICES:501502 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'))506507 rbody = json.loads(r.text)508 self.assertEqual(rbody.get('form'), {}) # No form supplied509 self.assertEqual(rbody.get('data'), '')510511512 def test_urlencoded_post_query_multivalued_and_data(self):513514 for service in SERVICES:515516 r = post(517 service('post'),518 params=dict(test=['foo','baz']),519 data=dict(test2="foobar",test3=['foo','baz']))520521 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'))524525 # print(r.text)526 # print('-----------------------')527528 rbody = json.loads(r.text)529 self.assertEqual(rbody.get('form'), dict(test2='foobar',test3=['foo','baz']))530 self.assertEqual(rbody.get('data'), '')531532533 def test_GET_no_redirect(self):534535 for service in SERVICES:536537 r = get(service('redirect', '3'), allow_redirects=False)538 self.assertEqual(r.status_code, 302)539 self.assertEqual(len(r.history), 0)540541542 def test_HEAD_no_redirect(self):543544 for service in SERVICES:545546 r = head(service('redirect', '3'), allow_redirects=False)547 self.assertEqual(r.status_code, 302)548 self.assertEqual(len(r.history), 0)549550551 def test_redirect_history(self):552553 for service in SERVICES:554555 r = get(service('redirect', '3'))556 self.assertEqual(r.status_code, 200)557 self.assertEqual(len(r.history), 3)558559560 def test_relative_redirect_history(self):561562 for service in SERVICES:563564 r = get(service('relative-redirect', '3'))565 self.assertEqual(r.status_code, 200)566 self.assertEqual(len(r.history), 3)567568569 def test_session_HTTP_200_OK_GET(self):570571 s = requests.session()572 r = get(httpbin('/get'), session=s)573 self.assertEqual(r.status_code, 200)574575576 def test_session_persistent_headers(self):577578 heads = {'User-agent': 'Mozilla/5.0'}579580 s = requests.session()581 s.headers = heads582583 # 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.text586587 r2 = get(httpbin('user-agent'), session=s)588 assert heads['User-agent'] in r2.text589590 new_heads = {'User-agent': 'blah'}591 r3 = get(httpbin('user-agent'), headers=new_heads, session=s)592 assert new_heads['User-agent'] in r3.text593594 self.assertEqual(r2.status_code, 200)595596 def test_single_hook(self):597598 def add_foo_header(args):599 if not args.get('headers'):600 args['headers'] = {}601602 args['headers'].update({603 'X-Foo': 'foo'604 })605606 return args607608 for service in SERVICES:609 url = service('headers')610611 response = get(612 url = url,613 hooks = {614 'args': add_foo_header615 }616 )617618 assert 'foo' in response.text619620 def test_multiple_hooks(self):621622 def add_foo_header(args):623 if not args.get('headers'):624 args['headers'] = {}625626 args['headers'].update({627 'X-Foo': 'foo'628 })629630 return args631632 def add_bar_header(args):633 if not args.get('headers'):634 args['headers'] = {}635636 args['headers'].update({637 'X-Bar': 'bar'638 })639640 return args641642 for service in SERVICES:643 url = service('headers')644645 response = get(646 url = url,647 hooks = {648 'args': [add_foo_header, add_bar_header]649 }650 )651652 assert 'foo' in response.text653 assert 'bar' in response.text654655 def test_session_persistent_cookies(self):656657 s = requests.session()658659 # 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)663664 # Those cookies persist transparently.665 c = json.loads(r.text).get('cookies')666 assert c == _c667668 # Double check.669 r = get(httpbin('cookies'), cookies={}, session=s)670 c = json.loads(r.text).get('cookies')671 assert c == _c672673 # 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 == _c678679 # 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 == _c684685 # 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')688689 assert 'k' in c690691 # And server-set cookie persistience.692 r = get(httpbin('cookies'), session=s)693 c = json.loads(r.text).get('cookies')694695 assert 'k' in c696697698699 def test_session_persistent_params(self):700701 params = {'a': 'a_test'}702703 s = requests.session()704 s.params = params705706 # Make 2 requests from Session object, should send header both times707 r1 = get(httpbin('get'), session=s)708 assert params['a'] in r1.text709710711 params2 = {'b': 'b_test'}712713 r2 = get(httpbin('get'), params=params2, session=s)714 assert params['a'] in r2.text715 assert params2['b'] in r2.text716717718 params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}719720 r3 = get(httpbin('get'), params=params3, session=s)721722 assert not params['a'] in r3.text723 assert params3['b'] in r3.text724 assert params3['c'] in r3.text725726 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 False736737738 config = {'safe_mode': True}739 r = get(hah, allow_redirects=False, config=config)740 assert r.content == None741742 def test_cached_response(self):743744 r1 = get(httpbin('get'), prefetch=False)745 assert not r1._content746 assert r1.content747 assert r1.text748749 r2 = get(httpbin('get'), prefetch=True)750 assert r2._content751 assert r2.content752 assert r2.text753754 def test_iter_lines(self):755756 lines = (0, 2, 10, 100)757758 for i in lines:759 r = get(httpbin('stream', str(i)), prefetch=False)760 lines = list(r.iter_lines())761 len_lines = len(lines)762763 self.assertEqual(i, len_lines)764765 # 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 )771772 # Make a request and monkey-patch its contents773 r = get(httpbin('get'))774 r.raw = StringIO(quote)775776 # Make sure iter_lines doesn't chop the trailing bit777 lines = '\n'.join(r.iter_lines())778 self.assertEqual(lines, quote)779780 def test_safe_mode(self):781782 safe = requests.session(config=dict(safe_mode=True))783784 # 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)789790 r = get('http://_/', session=safe)791 self.assertEqual(list(r.iter_content()), [])792 assert isinstance(r.error, requests.exceptions.ConnectionError)793794 # When not in safe mode, should raise Timeout exception795 self.assertRaises(796 requests.exceptions.Timeout,797 get,798 httpbin('stream', '1000'), timeout=0.0001)799800 # 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)805806 def test_upload_binary_data(self):807808 r = requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')809810811812if __name__ == '__main__':813 unittest.main()