Skip to content
Myr

remove all old tests

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 a982b0d · Browse files · 14 files+8 added−1907 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

14 files+8 added−1907 removed

  • tests:+0 added−1844 removed
  • other:+8 added−63 removed

14 files+8 added−1907 removed

deleted:tests/informal/test_leaked_connections.py-31 removed
1"""2This is an informal test originally written by Bluehorn;3it verifies that Requests does not leak connections when4the body of the request is not read.5"""67import gc8import os9import requests10import subprocess11import sys121314def main():15 gc.disable()1617 for x in range(20):18 requests.head("http://www.google.com/")1920 print("Open sockets after 20 head requests:")21 pid = os.getpid()22 subprocess.call("lsof -p%d -a -iTCP" % (pid,), shell=True)2324 gcresult = gc.collect()25 print("Garbage collection result: %s" % (gcresult,))2627 print("Open sockets after garbage collection:")28 subprocess.call("lsof -p%d -a -iTCP" % (pid,), shell=True)2930if __name__ == '__main__':31 sys.exit(main())
deleted:tests/dummy_server.py-46 removed
1import asyncore2import threading3import socket45class HttpServer(threading.Thread):6 def __init__(self, port):7 threading.Thread.__init__(self)8 self.dispatcher = HttpServerDispatcher(port)910 def run(self):11 asyncore.loop()1213 @property14 def connection_count(self):15 return self.dispatcher.connection_count1617 def close(self):18 asyncore.close_all()1920class HttpServerDispatcher(asyncore.dispatcher):21 def __init__(self, port):22 asyncore.dispatcher.__init__(self)23 self.connected = False24 self.create_socket(socket.AF_INET, socket.SOCK_STREAM)25 self.bind(('127.0.0.1', port))26 self.listen(1)27 self.connection_count = 02829 def handle_accept(self):30 self.connection_count += 131 self.handler = RequestHandler(self.accept()[0])3233 def handle_close(self):34 self.close()353637class RequestHandler(asyncore.dispatcher_with_send):38 def __init__(self, sock):39 asyncore.dispatcher_with_send.__init__(self, sock)40 self.response = ("HTTP/1.1 200 OK\r\n"41 "Connection: keep-alive\r\n"42 "Content-Length: 0\r\n\r\n")4344 def handle_read(self):45 self.recv(1024)46 self.send(self.response)
deleted:tests/test_cookies.py-244 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import sys5import json6import os7import tempfile8import unittest910# Path hack.11sys.path.insert(0, os.path.abspath('..'))12import requests13from requests.compat import cookielib1415# More hacks16sys.path.append('.')17from test_requests import httpbin, TestBaseMixin181920class CookieTests(TestBaseMixin, unittest.TestCase):2122 def test_cookies_from_response(self):23 """Basic test that we correctly parse received cookies in the Response object."""24 r = requests.get(httpbin('cookies', 'set', 'myname', 'myvalue'))2526 # test deprecated dictionary interface27 self.assertEqual(r.cookies['myname'], 'myvalue')28 self.assertEqual(r.cookies.get('myname'), 'myvalue')29 # test CookieJar interface30 jar = r.cookies31 self.assertEqual(len(jar), 1)32 cookie_from_jar = list(jar)[0]33 self.assertCookieHas(cookie_from_jar, name='myname', value='myvalue')3435 q = requests.get(httpbin('cookies'), cookies=jar)36 self.assertEqual(json.loads(q.text)['cookies'], {'myname': 'myvalue'})3738 def test_crossdomain_cookies(self):39 """Cookies should not be sent to domains they didn't originate from."""40 r = requests.get("http://github.com")41 c = r.cookies42 # github should send us cookies43 self.assertTrue(len(c) >= 1)4445 # github cookies should not be sent to httpbin.org:46 r2 = requests.get(httpbin('cookies'), cookies=c)47 self.assertEqual(json.loads(r2.text)['cookies'], {})4849 # let's do this again using the session object50 s = requests.session()51 s.get("http://github.com")52 self.assertTrue(len(s.cookies) >= 1)53 r = s.get(httpbin('cookies'))54 self.assertEqual(json.loads(r.text)['cookies'], {})55 # we can set a cookie and get exactly that same-domain cookie back:56 r = s.get(httpbin('cookies', 'set', 'myname', 'myvalue'))57 self.assertEqual(json.loads(r.text)['cookies'], {'myname': 'myvalue'})5859 def test_overwrite(self):60 """Cookies should get overwritten when appropriate."""61 r = requests.get(httpbin('cookies', 'set', 'shimon', 'yochai'))62 cookies = r.cookies63 requests.get(httpbin('cookies', 'set', 'elazar', 'shimon'), cookies=cookies)64 r = requests.get(httpbin('cookies'), cookies=cookies)65 self.assertEqual(json.loads(r.text)['cookies'],66 {'shimon': 'yochai', 'elazar': 'shimon'})67 # overwrite the value of 'shimon'68 r = requests.get(httpbin('cookies', 'set', 'shimon', 'gamaliel'), cookies=cookies)69 self.assertEqual(len(cookies), 2)70 r = requests.get(httpbin('cookies'), cookies=cookies)71 self.assertEqual(json.loads(r.text)['cookies'],72 {'shimon': 'gamaliel', 'elazar': 'shimon'})7374 def test_redirects(self):75 """Test that cookies set by a 302 page are correctly processed."""76 r = requests.get(httpbin('cookies', 'set', 'redirects', 'work'))77 self.assertEqual(r.history[0].status_code, 302)78 expected_cookies = {'redirects': 'work'}79 self.assertEqual(json.loads(r.text)['cookies'], expected_cookies)8081 r2 = requests.get(httpbin('cookies', 'set', 'very', 'well'), cookies=r.cookies)82 expected_cookies = {'redirects': 'work', 'very': 'well'}83 self.assertEqual(json.loads(r2.text)['cookies'], expected_cookies)84 self.assertTrue(r.cookies is r2.cookies)8586 def test_none_cookie(self):87 """Regression test: don't send a Cookie header with a string value of 'None'!"""88 page = json.loads(requests.get(httpbin('headers')).text)89 self.assertTrue('Cookie' not in page['headers'])9091 def test_secure_cookies(self):92 """Test that secure cookies can only be sent via https."""93 header = "Set-Cookie: ThisIsA=SecureCookie; Path=/; Secure; HttpOnly"94 url = 'https://httpbin.org/response-headers?%s' % (requests.utils.quote(header),)95 cookies = requests.get(url, verify=False).cookies96 self.assertEqual(len(cookies), 1)97 self.assertEqual(list(cookies)[0].secure, True)9899 secure_resp = requests.get('https://httpbin.org/cookies', cookies=cookies, verify=False)100 secure_cookies_sent = json.loads(secure_resp.text)['cookies']101 self.assertEqual(secure_cookies_sent, {'ThisIsA': 'SecureCookie'})102103 insecure_resp = requests.get('http://httpbin.org/cookies', cookies=cookies)104 insecure_cookies_sent = json.loads(insecure_resp.text)['cookies']105 self.assertEqual(insecure_cookies_sent, {})106107 def test_jar_utility_functions(self):108 """Test utility functions such as list_domains, list_paths, multiple_domains."""109 r = requests.get("http://github.com")110 c = r.cookies111 # github should send us cookies112 self.assertTrue(len(c) >= 1)113 self.assertEqual(len(c), len(r.cookies.keys()))114 self.assertEqual(len(c), len(r.cookies.values()))115 self.assertEqual(len(c), len(r.cookies.items()))116117 # domain and path utility functions118 domain = r.cookies.list_domains()[0]119 path = r.cookies.list_paths()[0]120 self.assertEqual(dict(r.cookies), r.cookies.get_dict(domain=domain, path=path))121 self.assertEqual(len(r.cookies.list_domains()), 1)122 self.assertEqual(len(r.cookies.list_paths()), 1)123 self.assertFalse(r.cookies.multiple_domains())124125 def test_convert_jar_to_dict(self):126 """Test that keys, values, and items are defined and that we can convert127 cookie jars to plain old Python dicts."""128 r = requests.get(httpbin('cookies', 'set', 'myname', 'myvalue'))129130 # test keys, values, and items131 self.assertEqual(r.cookies.keys(), ['myname'])132 self.assertEqual(r.cookies.values(), ['myvalue'])133 self.assertEqual(r.cookies.items(), [('myname', 'myvalue')])134135 # test if we can convert jar to dict136 dictOfCookies = dict(r.cookies)137 self.assertEqual(dictOfCookies, {'myname': 'myvalue'})138 self.assertEqual(dictOfCookies, r.cookies.get_dict())139140141class LWPCookieJarTest(TestBaseMixin, unittest.TestCase):142 """Check store/load of cookies to FileCookieJar's, specifically LWPCookieJar's."""143144 COOKIEJAR_CLASS = cookielib.LWPCookieJar145146 def setUp(self):147 # blank the file148 self.cookiejar_file = tempfile.NamedTemporaryFile()149 self.cookiejar_filename = self.cookiejar_file.name150 cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)151 cookiejar.save()152153 def tearDown(self):154 try:155 self.cookiejar_file.close()156 except OSError:157 pass158159 def test_cookiejar_persistence(self):160 """Test that we can save cookies to a FileCookieJar."""161 cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)162 cookiejar.load()163 # initially should be blank164 self.assertEqual(len(cookiejar), 0)165166 response = requests.get(httpbin('cookies', 'set', 'key', 'value'), cookies=cookiejar)167 self.assertEqual(len(cookiejar), 1)168 cookie = list(cookiejar)[0]169 self.assertEqual(json.loads(response.text)['cookies'], {'key': 'value'})170 self.assertCookieHas(cookie, name='key', value='value')171172 # save and reload the cookies from the file:173 cookiejar.save(ignore_discard=True)174 cookiejar_2 = self.COOKIEJAR_CLASS(self.cookiejar_filename)175 cookiejar_2.load(ignore_discard=True)176 self.assertEqual(len(cookiejar_2), 1)177 cookie_2 = list(cookiejar_2)[0]178 # this cookie should have been saved with the correct domain restriction:179 self.assertCookieHas(cookie_2, name='key', value='value',180 domain='httpbin.org', path='/')181182 # httpbin sets session cookies, so if we don't ignore the discard attribute,183 # there should be no cookie:184 cookiejar_3 = self.COOKIEJAR_CLASS(self.cookiejar_filename)185 cookiejar_3.load()186 self.assertEqual(len(cookiejar_3), 0)187188 def test_crossdomain(self):189 """Test persistence of the domains associated with the cookies."""190 cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)191 cookiejar.load()192 self.assertEqual(len(cookiejar), 0)193194 # github sets a cookie195 requests.get("http://github.com", cookies=cookiejar)196 num_github_cookies = len(cookiejar)197 self.assertTrue(num_github_cookies >= 1)198 # httpbin sets another199 requests.get(httpbin('cookies', 'set', 'key', 'value'), cookies=cookiejar)200 num_total_cookies = len(cookiejar)201 self.assertTrue(num_total_cookies >= 2)202 self.assertTrue(num_total_cookies > num_github_cookies)203204 # save and load205 cookiejar.save(ignore_discard=True)206 cookiejar_2 = self.COOKIEJAR_CLASS(self.cookiejar_filename)207 cookiejar_2.load(ignore_discard=True)208 self.assertEqual(len(cookiejar_2), num_total_cookies)209 r = requests.get(httpbin('cookies'), cookies=cookiejar_2)210 self.assertEqual(json.loads(r.text)['cookies'], {'key': 'value'})211212 def test_persistent_cookies(self):213 """Test that we correctly interpret persistent cookies."""214 # httpbin's normal cookie methods don't send persistent cookies,215 # so cook up the appropriate header and force it to send216 header = "Set-Cookie: Persistent=CookiesAreScary; expires=Sun, 04-May-2032 04:56:50 GMT; path=/"217 url = httpbin('response-headers?%s' % (requests.utils.quote(header),))218 cookiejar = self.COOKIEJAR_CLASS(self.cookiejar_filename)219220 requests.get(url, cookies=cookiejar)221 self.assertEqual(len(cookiejar), 1)222 self.assertCookieHas(list(cookiejar)[0], name='Persistent', value='CookiesAreScary')223224 requests.get(httpbin('cookies', 'set', 'ThisCookieIs', 'SessionOnly'), cookies=cookiejar)225 self.assertEqual(len(cookiejar), 2)226 self.assertEqual(len([c for c in cookiejar if c.name == 'Persistent']), 1)227 self.assertEqual(len([c for c in cookiejar if c.name == 'ThisCookieIs']), 1)228229 # save and load230 cookiejar.save()231 cookiejar_2 = self.COOKIEJAR_CLASS(self.cookiejar_filename)232 cookiejar_2.load()233 # we should only load the persistent cookie234 self.assertEqual(len(cookiejar_2), 1)235 self.assertCookieHas(list(cookiejar_2)[0], name='Persistent', value='CookiesAreScary')236237238class MozCookieJarTest(LWPCookieJarTest):239 """Same test, but substitute MozillaCookieJar."""240241 COOKIEJAR_CLASS = cookielib.MozillaCookieJar242243if __name__ == '__main__':244 unittest.main()
deleted:tests/test_keep_alive.py-65 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import os5import sys6import unittest78# Path hack.9sys.path.insert(0, os.path.abspath('..'))10import requests11import dummy_server1213class KeepAliveTests(unittest.TestCase):14 server_and_proxy_port = 123415 request_count = 216 url = 'http://localhost:{0}'.format(server_and_proxy_port)17 proxies={'http': url}1819 def setUp(self):20 self.session = requests.session()21 self.proxy_server = dummy_server.HttpServer(self.server_and_proxy_port)22 self.proxy_server.start()2324 def tearDown(self):25 self.proxy_server.close()2627 def test_keep_alive_with_direct_connection(self):28 self.make_requests()29 self.check_each_request_are_in_same_connection()3031 def test_no_keep_alive_with_direct_connection(self):32 self.disable_keep_alive_in_session()33 self.make_requests()34 self.check_each_request_are_in_different_connection()3536 def test_keep_alive_with_proxy_connection(self):37 self.make_proxy_requests()38 self.check_each_request_are_in_same_connection()3940 def test_no_keep_alive_with_proxy_connection(self):41 self.disable_keep_alive_in_session()42 self.make_proxy_requests()43 self.check_each_request_are_in_different_connection()4445 def make_proxy_requests(self):46 self.make_requests(self.proxies)4748 def make_requests(self, proxies=None):49 for _ in range(self.request_count):50 self.session.get(self.url, proxies=proxies).text5152 def check_each_request_are_in_same_connection(self):53 """Keep-alive requests open a single connection to the server."""54 self.assertEqual(self.proxy_server.connection_count, 1)5556 def check_each_request_are_in_different_connection(self):57 """Keep-alive requests open a single connection to the server."""58 self.assertEqual(self.proxy_server.connection_count, self.request_count)5960 def disable_keep_alive_in_session(self):61 self.session.config['keep_alive'] = False626364if __name__ == '__main__':65 unittest.main()
deleted:tests/test_proxies.py-29 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import os5import sys6import unittest78# Path hack.9sys.path.insert(0, os.path.abspath('..'))10import requests111213class HTTPSProxyTest(unittest.TestCase):14 """Smoke test for https functionality."""1516 smoke_url = "https://github.com"1718 def test_empty_https_proxy(self):19 proxy = {"https": ""}20 result = requests.get(self.smoke_url, verify=False, proxies=proxy)21 self.assertEqual(result.status_code, 200)2223 def test_empty_http_proxy(self):24 proxy = {"http": ""}25 result = requests.get(self.smoke_url, proxies=proxy)26 self.assertEqual(result.status_code, 200)2728if __name__ == '__main__':29 unittest.main()
deleted:tests/test_requests_ext.py-124 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34# Path hack.5import os6import sys7sys.path.insert(0, os.path.abspath('..'))89import unittest1011import requests12from requests.compat import is_py2, is_py31314try:15 import omnijson as json16except ImportError:17 import json181920class RequestsTestSuite(unittest.TestCase):21 """Requests test cases."""2223 # It goes to eleven.24 _multiprocess_can_split_ = True2526 def test_addition(self):27 self.assertEqual(2, 1 + 1)2829 def test_ssl_hostname_ok(self):30 requests.get('https://github.com', verify=True)3132 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')3637 def test_ssl_hostname_session_not_ok(self):3839 s = requests.session()4041 self.assertRaises(requests.exceptions.SSLError, s.get, 'https://kennethreitz.com')4243 s.get('https://kennethreitz.com', verify=False)4445 def test_binary_post(self):46 '''We need to be careful how we build the utf-8 string since47 unicode literals are a syntax error in python348 '''4950 if is_py2:51 # Blasphemy!52 utf8_string = eval("u'Smörgås'.encode('utf-8')")53 elif is_py3:54 utf8_string = 'Smörgås'.encode('utf-8')55 else:56 raise EnvironmentError('Flesh out this test for your environment.')57 requests.post('http://www.google.com/', data=utf8_string)5859 def test_unicode_error(self):60 url = 'http://blip.fm/~1abvfu'61 requests.get(url)6263 def test_chunked_head_redirect(self):64 url = "http://t.co/NFrx0zLG"65 r = requests.head(url, allow_redirects=True)66 self.assertEqual(r.status_code, 200)6768 def test_unicode_redirect(self):69 '''This url redirects to a location that has a nonstandard70 character in it, that breaks requests in python2.77172 After some research, the cause was identified as an unintended73 sideeffect of overriding of str with unicode.7475 In the case that the redirected url is actually a malformed76 "bytes" object, i.e. a string with character c where77 ord(c) > 127,78 then unicode(url) breaks.79 '''80 r = requests.get('http://www.marketwire.com/mw/release.' +81 'do?id=1628202&sourceType=3')82 self.assertTrue(r.ok)8384 def test_unicode_url_outright(self):85 '''This url visits in my browser'''86 r = requests.get('http://www.marketwire.com/press-release/' +87 'jp-morgan-behauptet-sich-der-spitze-euro' +88 'p%C3%A4ischer-anleihe-analysten-laut-umf' +89 'rageergebnissen-1628202.htm')90 self.assertTrue(r.ok)9192 def test_redirect_encoding(self):93 '''This url redirects to94 http://www.dealipedia.com/deal_view_investment.php?r=20012'''9596 r = requests.get('http://feedproxy.google.com/~r/Dealipedia' +97 'News/~3/BQtUJRJeZlo/deal_view_investment.' +98 'php')99 self.assertTrue(r.ok)100101 def test_cookies_on_redirects(self):102 """Test interaction between cookie handling and redirection."""103 # get a cookie for tinyurl.com ONLY104 s = requests.session()105 s.get(url='http://tinyurl.com/preview.php?disable=1')106 # we should have set a cookie for tinyurl: preview=0107 self.assertTrue('preview' in s.cookies)108 self.assertEqual(s.cookies['preview'], '0')109 self.assertEqual(list(s.cookies)[0].name, 'preview')110 self.assertEqual(list(s.cookies)[0].domain, 'tinyurl.com')111112 # get cookies on another domain113 r2 = s.get(url='http://httpbin.org/cookies')114 # the cookie is not there115 self.assertTrue('preview' not in json.loads(r2.text)['cookies'])116117 # this redirects to another domain, httpbin.org118 # cookies of the first domain should NOT be sent to the next one119 r3 = s.get(url='http://tinyurl.com/7zp3jnr')120 self.assertEqual(r3.url, 'http://httpbin.org/cookies')121 self.assertTrue('preview' not in json.loads(r3.text)['cookies'])122123if __name__ == '__main__':124 unittest.main()
deleted:tests/test_requests_https.py-32 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import os5import sys6import unittest78# Path hack.9sys.path.insert(0, os.path.abspath('..'))10import requests111213class HTTPSTest(unittest.TestCase):14 """Smoke test for https functionality."""1516 smoke_url = "https://github.com"1718 def perform_smoke_test(self, verify=False):19 result = requests.get(self.smoke_url, verify=verify)20 self.assertEqual(result.status_code, 200)2122 def test_smoke(self):23 """Smoke test without verification."""24 self.perform_smoke_test(verify=False)2526 def test_smoke_verified(self):27 """Smoke test with SSL verification."""28 self.perform_smoke_test(verify=True)293031if __name__ == '__main__':32 unittest.main()
deleted:tests/test_requests.py-1151 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34# from __future__ import unicode_literals56# Path hack.7import sys8import os9sys.path.insert(0, os.path.abspath('..'))10import json11import unittest12import pickle13import tempfile14import collections1516import requests17from requests.compat import str, StringIO18# import envoy19from requests import HTTPError20from requests import get, post, head, put21from requests.auth import HTTPBasicAuth, HTTPDigestAuth22from requests.exceptions import InvalidURL2324if 'HTTPBIN_URL' not in os.environ:25 os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'2627HTTPBIN_URL = os.environ.get('HTTPBIN_URL')282930def httpbin(*suffix):31 """Returns url for HTTPBIN resource."""32 return HTTPBIN_URL + '/'.join(suffix)333435SERVICES = (httpbin, )3637_httpbin = False383940class TestSetup(object):41 """Requests test cases."""4243 # It goes to eleven.44 _multiprocess_can_split_ = True4546 def setUp(self):4748 global _httpbin4950 if (not 'HTTPBIN_URL' in os.environ) and not _httpbin:51 # c = envoy.connect('httpbin %s' % (PORT))52 # time.sleep(1)53 _httpbin = True545556class TestBaseMixin(object):5758 def assertCookieHas(self, cookie, **kwargs):59 """Assert that a cookie has various specified properties."""60 for attr, expected_value in kwargs.items():61 cookie_attr = getattr(cookie, attr)62 message = 'Failed comparison for %s: %s != %s' % (attr, cookie_attr, expected_value)63 self.assertEqual(cookie_attr, expected_value, message)646566class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):67 """Requests test cases."""6869 def test_entry_points(self):7071 requests.session72 requests.session().get73 requests.session().head74 requests.get75 requests.head76 requests.put77 requests.patch78 requests.post7980 def test_invalid_url(self):81 self.assertRaises(ValueError, get, 'hiwpefhipowhefopw')8283 def test_path_is_not_double_encoded(self):84 request = requests.Request("http://0.0.0.0/get/test case")8586 self.assertEqual(request.path_url, "/get/test%20case")8788 def test_params_are_added_before_fragment(self):89 request = requests.Request(90 "http://example.com/path#fragment", params={"a": "b"})91 self.assertEqual(request.full_url,92 "http://example.com/path?a=b#fragment")93 request = requests.Request(94 "http://example.com/path?key=value#fragment", params={"a": "b"})95 self.assertEqual(request.full_url,96 "http://example.com/path?key=value&a=b#fragment")9798 def test_params_accepts_kv_list(self):99 request = requests.Request('http://example.com/path',100 params=[('a', 'b')])101 self.assertEqual(request.full_url, 'http://example.com/path?a=b')102103 def test_HTTP_200_OK_GET(self):104 r = get(httpbin('get'))105 self.assertEqual(r.status_code, 200)106107 def test_response_sent(self):108 r = get(httpbin('get'))109110 self.assertTrue(r.request.sent)111112 def test_HTTP_302_ALLOW_REDIRECT_GET(self):113 r = get(httpbin('redirect', '1'))114 self.assertEqual(r.status_code, 200)115116 def test_HTTP_302_GET(self):117 r = get(httpbin('redirect', '1'), allow_redirects=False)118 self.assertEqual(r.status_code, 302)119120 def test_HTTP_200_OK_GET_WITH_PARAMS(self):121 heads = {'User-agent': 'Mozilla/5.0'}122123 r = get(httpbin('user-agent'), headers=heads)124125 self.assertTrue(heads['User-agent'] in r.text)126 self.assertEqual(r.status_code, 200)127128 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):129 heads = {'User-agent': 'Mozilla/5.0'}130131 r = get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)132 self.assertEqual(r.status_code, 200)133134 # def test_unicode_headers(self):135 # # Simply calling requests with a unicode instance should simply work136 # # when the characters are all representable using latin-1:137 # heads = { u'User-Agent': u'Requests Test Suite' }138 # requests.get(url=httpbin('get'), headers=heads)139140 # # Characters outside latin-1 should raise an exception:141 # heads = { u'User-Agent': u'\u30cd\u30c3\u30c8\u30ef\u30fc\u30af' }142 # self.assertRaises(UnicodeEncodeError, requests.get,143 # url=httpbin('get'), headers=heads)144145 # def test_session_with_escaped_url(self):146 # # Test a URL that contains percent-escaped characters147 # # This URL should not be modified (double-escaped)148 # # Tests:149 # # - Quoted illegal characters ("%20" (' '), "%3C" ('<'), "%3E" ('>'))150 # # - Quoted reserved characters ("%25" ('%'), "%23" ('#'), "%2F" ('/'))151 # # - Quoted non-ASCII characters ("%C3%98", "%C3%A5")152 # path_fully_escaped = '%3Ca%25b%23c%2Fd%3E/%C3%98%20%C3%A5'153 # url = httpbin('get/' + path_fully_escaped)154 # response = get(url)155 # self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))156157 # # Test that illegal characters in a path get properly percent-escaped158 # # Tests:159 # # - Bare illegal characters (space, '<')160 # # - Bare non-ASCII characters ('\u00d8')161 # path = u'<a%25b%23c%2Fd%3E/\u00d8 %C3%A5'162 # url = httpbin('get/' + path)163 # response = get(url)164 # self.assertEqual(response.url, httpbin('get/' + path_fully_escaped))165166 # # Test that reserved characters in a path do not get percent-escaped167 # # Tests:168 # # - All reserved characters (RFC 3986), except '?', '#', '[' and ']',169 # # which are not allowed in the path, and ';' which delimits170 # # parameters.171 # # All such characters must be allowed bare in path, and must not be172 # # encoded.173 # # - Special unreserved characters (RFC 3986), which should not be174 # # encoded (even though it wouldn't hurt).175 # path_reserved = '!$&\'()*+,/:=@-._~'176 # url = httpbin('get/' + path_reserved)177 # response = get(url)178 # self.assertEqual(response.url, httpbin('get/' + path_reserved))179180 # # Test that percent-encoded unreserved characters in a path get181 # # normalised to their un-encoded forms.182 # path_unreserved = 'ABCDwxyz1234-._~'183 # path_unreserved_escaped = '%41%42%43%44%77%78%79%7A%31%32%33%34%2D%2E%5F%7E'184 # url = httpbin('get/' + path_unreserved_escaped)185 # response = get(url)186 # self.assertEqual(response.url, httpbin('get/' + path_unreserved))187188 # # Re-run all of the same tests on the query part of the URI189 # query_fully_escaped = '%3Ca%25b%23c%2Fd%3E=%C3%98%20%C3%A5'190 # url = httpbin('get/?' + query_fully_escaped)191 # response = get(url)192 # self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))193194 # query = u'<a%25b%23c%2Fd%3E=\u00d8 %C3%A5'195 # url = httpbin('get/?' + query)196 # response = get(url)197 # self.assertEqual(response.url, httpbin('get/?' + query_fully_escaped))198199 # # The legal characters in query happens to be the same as in path200 # query_reserved = '!$&\'()*+,/:=@-._~'201 # url = httpbin('get/?' + query_reserved)202 # response = get(url)203 # self.assertEqual(response.url, httpbin('get/?' + query_reserved))204205 # query_unreserved = 'ABCDwxyz=1234-._~'206 # query_unreserved_escaped = '%41%42%43%44%77%78%79%7A=%31%32%33%34%2D%2E%5F%7E'207 # url = httpbin('get/?' + query_unreserved_escaped)208 # response = get(url)209 # self.assertEqual(response.url, httpbin('get/?' + query_unreserved))210211 def test_user_agent_transfers(self):212 """Issue XX"""213214 heads = {215 'User-agent':216 'Mozilla/5.0 (github.com/kennethreitz/requests)'217 }218219 r = get(httpbin('user-agent'), headers=heads)220 self.assertTrue(heads['User-agent'] in r.text)221222 heads = {223 'user-agent':224 'Mozilla/5.0 (github.com/kennethreitz/requests)'225 }226227 r = get(httpbin('user-agent'), headers=heads)228 self.assertTrue(heads['user-agent'] in r.text)229230 def test_HTTP_200_OK_HEAD(self):231 r = head(httpbin('get'))232 self.assertEqual(r.status_code, 200)233234 def test_HTTP_200_OK_PUT(self):235 r = put(httpbin('put'))236 self.assertEqual(r.status_code, 200)237238 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):239240 for service in SERVICES:241242 auth = ('user', 'pass')243 url = service('basic-auth', 'user', 'pass')244245 r = get(url, auth=auth)246 self.assertEqual(r.status_code, 200)247248 r = get(url)249 self.assertEqual(r.status_code, 401)250251 s = requests.session(auth=auth)252 r = get(url, session=s)253 self.assertEqual(r.status_code, 200)254255 def test_BASICAUTH_HTTP_200_OK_GET(self):256257 for service in SERVICES:258259 auth = HTTPBasicAuth('user', 'pass')260 url = service('basic-auth', 'user', 'pass')261262 r = get(url, auth=auth)263 self.assertEqual(r.status_code, 200)264265 auth = ('user', 'pass')266 r = get(url, auth=auth)267 self.assertEqual(r.status_code, 200)268269 r = get(url)270 self.assertEqual(r.status_code, 401)271272 s = requests.session(auth=auth)273 r = get(url, session=s)274 self.assertEqual(r.status_code, 200)275276 def test_DIGESTAUTH_HTTP_200_OK_GET(self):277278 for service in SERVICES:279280 auth = HTTPDigestAuth('user', 'pass')281 url = service('digest-auth', 'auth', 'user', 'pass')282283 r = get(url, auth=auth)284 self.assertEqual(r.status_code, 200)285 self.assertEqual(len(r.history), 1)286287 r = get(url, auth=auth)288 self.assertEqual(r.status_code, 200)289 self.assertEqual(len(r.history), 0)290291 r = get(url)292 self.assertEqual(r.status_code, 401)293294 s = requests.session(auth=auth)295 r = get(url, session=s)296 self.assertEqual(r.status_code, 200)297298 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):299300 for service in SERVICES:301302 auth = HTTPDigestAuth('user', 'wrongpass')303 url = service('digest-auth', 'auth', 'user', 'pass')304305 r = get(url, auth=auth)306 self.assertEqual(r.status_code, 401)307308 s = requests.session(auth=auth)309 r = get(url, session=s)310 self.assertEqual(r.status_code, 401)311312 def test_POSTBIN_GET_POST_FILES(self):313314 for service in SERVICES:315316 url = service('post')317 post1 = post(url).raise_for_status()318319 post1 = post(url, data={'some': 'data'})320 self.assertEqual(post1.status_code, 200)321322 with open(__file__) as f:323 post2 = post(url, files={'some': f})324 post3 = post(url, files=[('some', f)])325 self.assertEqual(post2.status_code, 200)326 self.assertEqual(post3.status_code, 200)327328 post4 = post(url, data='[{"some": "json"}]')329 self.assertEqual(post4.status_code, 200)330331 try:332 post(url, files=['bad file data'])333 except ValueError:334 pass335336 def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):337338 for service in SERVICES:339340 with open(__file__) as f:341 url = service('post')342 post1 = post(url, data={'some': 'data'}, files={'some': f})343 post2 = post(url, data={'some': 'data'}, files=[('some', f)])344 post3 = post(url, data=[('some', 'data')], files=[('some', f)])345346 self.assertEqual(post1.status_code, 200)347 self.assertEqual(post2.status_code, 200)348 self.assertEqual(post3.status_code, 200)349350 def test_POSTBIN_GET_POST_FILES_WITH_CJK_PARAMS(self):351352 for service in SERVICES:353354 with open(__file__) as f:355 url = service('post')356 post1 = post(url, data={'some': '中文'}, files={'some': f})357 post2 = post(url, data={'some': '日本語'}, files=[('some', f)])358 post3 = post(url, data=[('some', '한국의')], files=[('some', f)])359360 self.assertEqual(post1.status_code, 200)361 self.assertEqual(post2.status_code, 200)362 self.assertEqual(post3.status_code, 200)363364 def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):365366 for service in SERVICES:367368 url = service('post')369370 with open(__file__) as f:371372 post2 = post(url,373 files={'some': f},374 headers={'User-Agent': 'requests-tests'})375376 self.assertEqual(post2.status_code, 200)377378 def test_POSTBIN_GET_POST_FILES_STRINGS(self):379380 for service in SERVICES:381382 url = service('post')383384 post1 = post(url, files={'fname.txt': 'fdata'})385 self.assertEqual(post1.status_code, 200)386387 post2 = post(url, files={'fname.txt': 'fdata',388 'fname2.txt': 'more fdata'})389 self.assertEqual(post2.status_code, 200)390391 post3 = post(url, files={'fname.txt': 'fdata',392 'fname2.txt': open(__file__, 'rb')})393 self.assertEqual(post3.status_code, 200)394395 post4 = post(url, files={'fname.txt': 'fdata'})396 self.assertEqual(post4.status_code, 200)397398 post5 = post(url, files={'file': ('file.txt', 'more fdata')})399 self.assertEqual(post5.status_code, 200)400401 # Dirty hack to tide us over until 3.3.402 # TODO: Remove this hack when Python 3.3 is released.403 if (sys.version_info[0] == 2):404 fdata = '\xc3\xa9'.decode('utf-8')405 else:406 fdata = '\xe9'407408 post6 = post(url, files={'fname.txt': fdata})409 self.assertEqual(post6.status_code, 200)410411 post7 = post(url, files={'fname.txt': 'fdata to verify'})412 rbody = json.loads(post7.text)413 self.assertTrue(rbody.get('files', None))414 self.assertTrue(rbody['files'].get('fname.txt', None))415 self.assertEqual(rbody['files']['fname.txt'], 'fdata to verify')416417 post8 = post(url, files=[('fname.txt', 'fdata')])418 self.assertEqual(post8.status_code, 200)419 resp_body = post8.json420 self.assertTrue(resp_body.get('files', None))421 self.assertTrue(resp_body['files'].get('fname.txt', None))422 self.assertEqual(resp_body['files']['fname.txt'], 'fdata')423424 post9 = post(url, files=[('fname.txt', fdata)])425 self.assertEqual(post9.status_code, 200)426427 post10 = post(url, files=[('file',428 ('file.txt', 'more file data'))])429 self.assertEqual(post10.status_code, 200)430431 post11 = post(url, files=[('fname.txt', 'fdata'),432 ('fname2.txt', 'more fdata')])433 post12 = post(url, files=[('fname.txt', 'fdata'),434 ('fname2.txt', open(__file__, 'rb'))])435 self.assertEqual(post11.status_code, 200)436 self.assertEqual(post12.status_code, 200)437438 def test_nonzero_evaluation(self):439440 for service in SERVICES:441442 r = get(service('status', '500'))443 self.assertEqual(bool(r), False)444445 r = get(service('/get'))446 self.assertEqual(bool(r), True)447448 def test_request_ok_set(self):449450 for service in SERVICES:451452 r = get(service('status', '404'))453 # print r.status_code454 # r.raise_for_status()455 self.assertEqual(r.ok, False)456457 def test_status_raising(self):458 r = get(httpbin('status', '404'))459 self.assertRaises(HTTPError, r.raise_for_status)460461 r = get(httpbin('status', '200'))462 self.assertFalse(r.error)463 r.raise_for_status()464465 def test_decompress_gzip(self):466467 r = get(httpbin('gzip'))468 r.content.decode('ascii')469470 def test_response_has_unicode_url(self):471472 for service in SERVICES:473474 url = service('get')475476 response = get(url)477478 self.assertTrue(isinstance(response.url, str))479480 def test_unicode_get(self):481482 for service in SERVICES:483484 url = service('/get')485486 get(url, params={'foo': 'føø'})487 get(url, params={'føø': 'føø'})488 get(url, params={'føø': 'føø'})489 get(url, params={'foo': 'foo'})490 get(service('ø'), params={'foo': 'foo'})491492 def test_httpauth_recursion(self):493494 http_auth = HTTPBasicAuth('user', 'BADpass')495496 for service in SERVICES:497 r = get(service('basic-auth', 'user', 'pass'), auth=http_auth)498 self.assertEqual(r.status_code, 401)499500 def test_urlencoded_post_data(self):501502 for service in SERVICES:503504 r = post(service('post'), data=dict(test='fooaowpeuf'))505506 self.assertEqual(r.status_code, 200)507 self.assertEqual(r.headers['content-type'], 'application/json')508 self.assertEqual(r.url, service('post'))509510 rbody = json.loads(r.text)511512 self.assertEqual(rbody.get('form'), dict(test='fooaowpeuf'))513 self.assertEqual(rbody.get('data'), '')514515 def test_nonurlencoded_post_data(self):516517 for service in SERVICES:518519 r = post(service('post'), data='fooaowpeuf')520521 self.assertEqual(r.status_code, 200)522 self.assertEqual(r.headers['content-type'], 'application/json')523 self.assertEqual(r.url, service('post'))524525 rbody = json.loads(r.text)526 # Body wasn't valid url encoded data, so the server returns None as527 # "form" and the raw body as "data".528529 self.assertTrue(rbody.get('form') in (None, {}))530 self.assertEqual(rbody.get('data'), 'fooaowpeuf')531532 def test_file_post_data(self):533534 filecontent = b"fooaowpeufbarasjhf"535 testfile = tempfile.NamedTemporaryFile(delete=False)536 testfile.write(filecontent)537 testfile.flush()538 testfile.close()539540 for service in SERVICES:541542 data = open(testfile.name, "rb")543 r = post(service('post'), data=data,544 headers={"content-type": "application/octet-stream"})545546 data.close()547 self.assertEqual(r.status_code, 200)548 self.assertEqual(r.headers['content-type'], 'application/json')549 self.assertEqual(r.url, service('post'))550551 rbody = json.loads(r.text)552 self.assertTrue(rbody.get('form') in (None, {}))553 self.assertEqual(rbody.get('data'), filecontent.decode('ascii'))554 os.remove(testfile.name)555556 def test_urlencoded_post_querystring(self):557558 for service in SERVICES:559560 r = post(service('post'), params=dict(test='fooaowpeuf'))561562 self.assertEqual(r.status_code, 200)563 self.assertEqual(r.headers['content-type'], 'application/json')564 self.assertEqual(r.url, service('post?test=fooaowpeuf'))565566 rbody = json.loads(r.text)567 self.assertEqual(rbody.get('form'), {}) # No form supplied568 self.assertEqual(rbody.get('data'), '')569570 def test_urlencoded_post_query_and_data(self):571572 for service in SERVICES:573574 r = post(575 service('post'),576 params=dict(test='fooaowpeuf'),577 data=dict(test2="foobar"))578579 self.assertEqual(r.status_code, 200)580 self.assertEqual(r.headers['content-type'], 'application/json')581 self.assertEqual(r.url, service('post?test=fooaowpeuf'))582583 rbody = json.loads(r.text)584 self.assertEqual(rbody.get('form'), dict(test2='foobar'))585 self.assertEqual(rbody.get('data'), '')586587 def test_nonurlencoded_postdata(self):588589 for service in SERVICES:590591 r = post(service('post'), data="foobar")592593 self.assertEqual(r.status_code, 200)594 self.assertEqual(r.headers['content-type'], 'application/json')595596 rbody = json.loads(r.text)597598 self.assertTrue(rbody.get('form') in (None, {}))599 self.assertEqual(rbody.get('data'), 'foobar')600601 def test_urlencoded_get_query_multivalued_param(self):602603 for service in SERVICES:604605 r = get(service('get'), params=dict(test=['foo', 'baz']))606 self.assertEqual(r.status_code, 200)607 self.assertEqual(r.url, service('get?test=foo&test=baz'))608609 def test_urlencoded_post_querystring_multivalued(self):610611 for service in SERVICES:612613 r = post(service('post'), params=dict(test=['foo', 'baz']))614 self.assertEqual(r.status_code, 200)615 self.assertEqual(r.headers['content-type'], 'application/json')616 self.assertEqual(r.url, service('post?test=foo&test=baz'))617618 rbody = json.loads(r.text)619 self.assertEqual(rbody.get('form'), {}) # No form supplied620 self.assertEqual(rbody.get('data'), '')621622 def test_urlencoded_post_query_multivalued_and_data(self):623624 for service in SERVICES:625626 r = post(627 service('post'),628 params=dict(test=['foo', 'baz']),629 data=dict(test2="foobar", test3=['foo', 'baz']))630631 self.assertEqual(r.status_code, 200)632 self.assertEqual(r.headers['content-type'], 'application/json')633 self.assertEqual(r.url, service('post?test=foo&test=baz'))634635 # print(r.text)636 # print('-----------------------')637638 rbody = json.loads(r.text)639 self.assertEqual(rbody.get('form'), dict(test2='foobar', test3=['foo', 'baz']))640 self.assertEqual(rbody.get('data'), '')641642 def test_multivalued_data_encoding(self):643 """644 Make sure data encoding works on a value that is an iterable but not645 a list646 """647 for service in SERVICES:648 # Can't have unicode literals in Python3, so avoid them.649 # TODO: fixup when moving to Python 3.3650 if (sys.version_info[0] == 2):651 nonascii = '\xc3\xa9'.decode('utf-8')652 else:653 nonascii = '\xe9'654655 r = post(656 service('post'),657 data=dict(test=('foo', nonascii)))658659 self.assertEqual(r.status_code, 200)660 self.assertEqual(r.headers['content-type'], 'application/json')661662 rbody = json.loads(r.text)663 self.assertEqual(rbody.get('form'),664 dict(test=['foo', nonascii]))665666 def test_GET_no_redirect(self):667668 for service in SERVICES:669670 r = get(service('redirect', '3'), allow_redirects=False)671 self.assertEqual(r.status_code, 302)672 self.assertEqual(len(r.history), 0)673674 def test_HEAD_no_redirect(self):675676 for service in SERVICES:677678 r = head(service('redirect', '3'), allow_redirects=False)679 self.assertEqual(r.status_code, 302)680 self.assertEqual(len(r.history), 0)681682 def test_redirect_history(self):683684 for service in SERVICES:685686 r = get(service('redirect', '3'))687 self.assertEqual(r.status_code, 200)688 self.assertEqual(len(r.history), 3)689690 def test_relative_redirect_history(self):691692 for service in SERVICES:693694 r = get(service('relative-redirect', '3'))695 self.assertEqual(r.status_code, 200)696 self.assertEqual(len(r.history), 3)697698 def test_session_HTTP_200_OK_GET(self):699700 s = requests.session()701 r = get(httpbin('get'), session=s)702 self.assertEqual(r.status_code, 200)703704 def test_session_persistent_headers(self):705706 heads = {'User-agent': 'Mozilla/5.0'}707708 s = requests.session()709 s.headers = heads710711 # Make 2 requests from Session object, should send header both times712 r1 = get(httpbin('user-agent'), session=s)713 self.assertTrue(heads['User-agent'] in r1.text)714715 r2 = get(httpbin('user-agent'), session=s)716 self.assertTrue(heads['User-agent'] in r2.text)717718 new_heads = {'User-agent': 'blah'}719 r3 = get(httpbin('user-agent'), headers=new_heads, session=s)720 self.assertTrue(new_heads['User-agent'] in r3.text)721722 self.assertEqual(r2.status_code, 200)723724 def test_single_hook(self):725726 def add_foo_header(args):727 if not args.get('headers'):728 args['headers'] = {}729730 args['headers'].update({731 'X-Foo': 'foo'732 })733734 return args735736 for service in SERVICES:737 url = service('headers')738 response = get(url=url, hooks={'args': add_foo_header})739740 self.assertTrue('foo' in response.text)741742 def test_multiple_hooks(self):743744 def add_foo_header(args):745 if not args.get('headers'):746 args['headers'] = {}747748 args['headers'].update({749 'X-Foo': 'foo'750 })751752 return args753754 def add_bar_header(args):755 if not args.get('headers'):756 args['headers'] = {}757758 args['headers'].update({759 'X-Bar': 'bar'760 })761762 return args763764 for service in SERVICES:765 url = service('headers')766767 response = get(url=url,768 hooks={769 'args': [add_foo_header, add_bar_header]770 }771 )772773 for text in ('foo', 'bar'):774 self.assertTrue(text in response.text)775776 def test_allow_list_of_hooks_to_register_hook(self):777 """Issue 785: https://github.com/kennethreitz/requests/issues/785"""778 def add_foo_header(args):779 if not args.get('headers'):780 args['headers'] = {}781782 args['headers'].update({783 'X-Foo': 'foo'784 })785786 return args787788 def add_bar_header(args):789 if not args.get('headers'):790 args['headers'] = {}791792 args['headers'].update({793 'X-Bar': 'bar'794 })795796 return args797798 def assert_hooks_are_callable(hooks):799 for h in hooks['args']:800 self.assertTrue(isinstance(h, collections.Callable))801802 hooks = [add_foo_header, add_bar_header]803 r = requests.models.Request()804 r.register_hook('args', hooks)805 assert_hooks_are_callable(r.hooks)806807 r = requests.models.Request(hooks={'args': hooks})808 assert_hooks_are_callable(r.hooks)809810 hooks.append('string that should not be registered')811 r = requests.models.Request(hooks={'args': hooks})812 assert_hooks_are_callable(r.hooks)813814 def test_session_persistent_cookies(self):815816 s = requests.session()817818 # Internally dispatched cookies are sent.819 _c = {'kenneth': 'reitz', 'bessie': 'monke'}820 r = get(httpbin('cookies'), cookies=_c, session=s)821 r = get(httpbin('cookies'), session=s)822823 # Those cookies persist transparently.824 c = json.loads(r.text).get('cookies')825 self.assertEqual(c, _c)826827 # Double check.828 r = get(httpbin('cookies'), cookies={}, session=s)829 c = json.loads(r.text).get('cookies')830 self.assertEqual(c, _c)831832 # Remove a cookie by setting it's value to None.833 r = get(httpbin('cookies'), cookies={'bessie': None}, session=s)834 c = json.loads(r.text).get('cookies')835 del _c['bessie']836 self.assertEqual(c, _c)837838 # Test session-level cookies.839 s = requests.session(cookies=_c)840 r = get(httpbin('cookies'), session=s)841 c = json.loads(r.text).get('cookies')842 self.assertEqual(c, _c)843844 # Have the server set a cookie.845 r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)846 c = json.loads(r.text).get('cookies')847848 self.assertTrue('k' in c)849850 # And server-set cookie persistience.851 r = get(httpbin('cookies'), session=s)852 c = json.loads(r.text).get('cookies')853854 self.assertTrue('k' in c)855856 def test_session_persistent_params(self):857858 params = {'a': 'a_test'}859860 s = requests.session()861 s.params = params862863 # Make 2 requests from Session object, should send header both times864 r1 = get(httpbin('get'), session=s)865 self.assertTrue(params['a'] in r1.text)866867 params2 = {'b': 'b_test'}868869 r2 = get(httpbin('get'), params=params2, session=s)870 for param in (params['a'], params2['b']):871 self.assertTrue(param in r2.text)872873 params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}874875 r3 = get(httpbin('get'), params=params3, session=s)876877 self.assertFalse(params['a'] in r3.text)878879 for param in (params3['b'], params3['c']):880 self.assertTrue(param in r3.text)881882 def test_session_cookies_with_return_response_false(self):883 s = requests.session()884 # return_response=False as it does requests.async.get885 rq = get(httpbin('cookies', 'set', 'k', 'v'), return_response=False,886 allow_redirects=True, session=s)887 rq.send(prefetch=True)888 c = rq.response.json.get('cookies')889 self.assertTrue('k' in c)890 self.assertTrue('k' in s.cookies)891892 def test_session_pickling(self):893894 s = requests.session(895 headers={'header': 'value'},896 cookies={'a-cookie': 'cookie-value'},897 auth=('username', 'password'))898899 ds = pickle.loads(pickle.dumps(s))900901 self.assertEqual(s.headers, ds.headers)902 self.assertEqual(s.auth, ds.auth)903904 # Cookie doesn't have a good __eq__, so verify manually:905 self.assertEqual(len(ds.cookies), 1)906 for cookie in ds.cookies:907 self.assertCookieHas(cookie, name='a-cookie', value='cookie-value')908909 def test_unpickled_session_requests(self):910 s = requests.session()911 r = get(httpbin('cookies', 'set', 'k', 'v'), allow_redirects=True, session=s)912 c = json.loads(r.text).get('cookies')913 self.assertTrue('k' in c)914915 ds = pickle.loads(pickle.dumps(s))916 r = get(httpbin('cookies'), session=ds)917 c = json.loads(r.text).get('cookies')918 self.assertTrue('k' in c)919920 ds1 = pickle.loads(pickle.dumps(requests.session()))921 ds2 = pickle.loads(pickle.dumps(requests.session(prefetch=False)))922 self.assertTrue(ds1.prefetch)923 self.assertFalse(ds2.prefetch)924925 def test_connection_error(self):926 try:927 get('http://localhost:1/nope')928 except requests.ConnectionError:929 pass930 else:931 self.fail()932933 def test_cached_response(self):934935 r1 = get(httpbin('get'), prefetch=False)936 self.assertFalse(r1._content)937 self.assertTrue(r1.content)938 self.assertTrue(r1.text)939940 r2 = get(httpbin('get'), prefetch=True)941 self.assertTrue(r2._content)942 self.assertTrue(r2.content)943 self.assertTrue(r2.text)944945 def test_iter_lines(self):946947 lines = (0, 2, 10, 100)948949 for i in lines:950 r = get(httpbin('stream', str(i)), prefetch=False)951 lines = list(r.iter_lines())952 len_lines = len(lines)953954 self.assertEqual(i, len_lines)955956 # Tests that trailing whitespaces within lines do not get stripped.957 # Tests that a trailing non-terminated line does not get stripped.958 quote = (959 '''Agamemnon \n'''960 '''\tWhy will he not upon our fair request\r\n'''961 '''\tUntent his person and share the air with us?'''962 )963964 # Make a request and monkey-patch its contents965 r = get(httpbin('get'), prefetch=False)966 r.raw = StringIO(quote)967968 lines = list(r.iter_lines())969 len_lines = len(lines)970 self.assertEqual(len_lines, 3)971972 joined = lines[0] + '\n' + lines[1] + '\r\n' + lines[2]973 self.assertEqual(joined, quote)974975 def test_permissive_iter_content(self):976 """Test that iter_content and iter_lines work even after the body has been fetched."""977 r = get(httpbin('stream', '10'), prefetch=True)978 self.assertTrue(r._content_consumed)979 # iter_lines should still work without crashing980 self.assertEqual(len(list(r.iter_lines())), 10)981982 # iter_content should return a one-item iterator over the whole content983 iter_content_list = list(r.iter_content(chunk_size=1))984 self.assertTrue(all(len(item) == 1 for item in iter_content_list))985 # when joined, it should be exactly the original content986 self.assertEqual(bytes().join(iter_content_list), r.content)987988 # test different chunk sizes:989 for chunk_size in range(2, 20):990 self.assertEqual(bytes().join(r.iter_content(chunk_size=chunk_size)), r.content)991992993 def test_upload_binary_data(self):994995 requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')996997 def test_useful_exception_for_invalid_port(self):998 # If we pass a legitimate URL with an invalid port, we should fail.999 self.assertRaises(1000 ValueError,1001 get,1002 'http://google.com:banana')10031004 def test_useful_exception_for_invalid_scheme(self):10051006 # If we pass a legitimate URL with a scheme not supported1007 # by requests, we should fail.1008 self.assertRaises(1009 ValueError,1010 get,1011 'ftp://ftp.kernel.org/pub/')10121013 def test_can_have_none_in_header_values(self):1014 try:1015 # Don't choke on headers with none in the value.1016 requests.get(httpbin('headers'), headers={'Foo': None})1017 except TypeError:1018 self.fail('Not able to have none in header values')101910201021 def test_empty_response(self):1022 r = requests.get(httpbin('status', '404'))1023 r.text10241025 def test_connection_keepalive_and_close(self):1026 """Test that we send 'Connection: close' when keep_alive is disabled."""1027 # keep-alive should be on by default1028 r1 = requests.get(httpbin('get'))1029 # XXX due to proxying issues, test the header sent back by httpbin, rather than1030 # the header reported in its message body. See kennethreitz/httpbin#461031 self.assertEqual(r1.headers['Connection'].lower(), 'keep-alive')10321033 # but when we disable it, we should send a 'Connection: close'1034 # and get the same back:1035 r2 = requests.get(httpbin('get'), config=dict(keep_alive=False))1036 self.assertEqual(r2.headers['Connection'].lower(), 'close')10371038 def test_head_content(self):1039 """Test that empty bodies are properly supported."""10401041 r = requests.head(httpbin('headers'))1042 r.content1043 r.text10441045 def test_post_fields_with_multiple_values_and_files(self):1046 """Test that it is possible to POST using the files argument and a1047 list for a value in the data argument."""10481049 data = {'field': ['a', 'b']}1050 files = {'field': 'Garbled data'}1051 r = post(httpbin('post'), data=data, files=files)1052 t = json.loads(r.text)1053 self.assertEqual(t.get('form'), {'field': ['a', 'b']})1054 self.assertEqual(t.get('files'), files)1055 r = post(httpbin('post'), data=data, files=files.items())1056 self.assertEqual(t.get('files'), files)10571058 def test_str_data_content_type(self):1059 data = 'test string data'1060 r = post(httpbin('post'), data=data)1061 t = json.loads(r.text)1062 self.assertEqual(t.get('headers').get('Content-Type'), '')10631064 def test_prefetch_redirect_bug(self):1065 """Test that prefetch persists across redirections."""1066 res = get(httpbin('redirect/2'), prefetch=False)1067 # prefetch should persist across the redirect;1068 # the content should not have been consumed1069 self.assertFalse(res._content_consumed)1070 first_line = next(res.iter_lines())1071 self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))10721073 def test_prefetch_return_response_interaction(self):1074 """Test that prefetch can be overridden as a kwarg to `send`."""1075 req = requests.get(httpbin('get'), return_response=False)1076 req.send(prefetch=False)1077 # content should not have been prefetched1078 self.assertFalse(req.response._content_consumed)1079 first_line = next(req.response.iter_lines())1080 self.assertTrue(first_line.strip().decode('utf-8').startswith('{'))10811082 def test_accept_objects_with_string_representations_as_urls(self):1083 """Test that URLs can be set to objects with string representations,1084 e.g. for use with furl."""1085 class URL():1086 def __unicode__(self):1087 # Can't have unicode literals in Python3, so avoid them.1088 # TODO: fixup when moving to Python 3.31089 if (sys.version_info[0] == 2):1090 return 'http://httpbin.org/get'.decode('utf-8')1091 else:1092 return 'http://httpbin.org/get'10931094 def __str__(self):1095 return 'http://httpbin.org/get'10961097 r = get(URL())1098 self.assertEqual(r.status_code, 200)10991100 def test_post_fields_with_multiple_values_and_files_as_tuples(self):1101 """Test that it is possible to POST multiple data and file fields1102 with the same name.1103 https://github.com/kennethreitz/requests/pull/7461104 """11051106 fields = [1107 ('__field__', '__value__'),1108 ('__field__', '__value__'),1109 ]11101111 r = post(httpbin('post'), data=fields, files=fields)1112 t = json.loads(r.text)11131114 self.assertEqual(t.get('form'), {1115 '__field__': [1116 '__value__',1117 '__value__',1118 ]1119 })11201121 # It's not currently possible to test for multiple file fields with1122 # the same name against httpbin so we need to inspect the encoded1123 # body manually.1124 request = r.request1125 body, content_type = request._encode_files(request.files)1126 file_field = (b'Content-Disposition: form-data;'1127 b' name="__field__"; filename="__field__"')1128 self.assertEqual(body.count(b'__value__'), 4)1129 self.assertEqual(body.count(file_field), 2)11301131 def test_bytes_files(self):1132 """Test that `bytes` can be used as the values of `files`."""1133 post(httpbin('post'), files={'test': b'test'})11341135 def test_invalid_urls_throw_requests_exception(self):1136 """Test that URLs with invalid labels throw1137 Requests.exceptions.InvalidURL instead of UnicodeError."""1138 self.assertRaises(InvalidURL, get, 'http://.google.com/')11391140 def test_none_vals_in_data_are_deleted(self):1141 """Test that keys with None as the value are removed instead of1142 being posted."""1143 data = {'key1': 'value1', 'key2': None}1144 r = post(httpbin('post'), data=data)1145 vals = r.json['form']1146 self.assertEqual(vals['key1'], 'value1')1147 # The 'key2' key should not have been sent.1148 self.assertTrue(vals.get('key2') is None)11491150if __name__ == '__main__':1151 unittest.main()
deleted:tests/test_utils.py-122 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34import codecs5import os6import sys7import unittest8import random910# Path hack.11sys.path.insert(0, os.path.abspath('..'))12from requests.utils import get_environ_proxies13import requests.utils14from requests.compat import is_py3, bytes151617if is_py3:18 unichr = chr19 byteschr = lambda c: bytes([c])20else:21 byteschr = chr222324class UtilityTests(unittest.TestCase):25 """Tests for the JSON UTF encoding guessing code."""2627 codecs = (28 'utf-8', 'utf-8-sig',29 'utf-16', 'utf-16-le', 'utf-16-be',30 'utf-32', 'utf-32-le', 'utf-32-be'31 )3233 def test_guess_encoding(self):34 # Throw 4-character ASCII strings (encoded to a UTF encoding)35 # at the guess routine; it should correctly guess all codecs.36 guess = requests.utils.guess_json_utf37 for c in range(33, 127): # printable only38 sample = unichr(c) * 439 for codec in self.codecs:40 res = guess(sample.encode(codec))41 self.assertEqual(res, codec)4243 def test_smoke_encoding(self):44 # Throw random 4-byte strings at the guess function.45 # Any guess for a UTF encoding is verified, a decode exception46 # is a test failure.47 guess = requests.utils.guess_json_utf48 for i in range(1000):49 sample = bytes().join(50 [byteschr(random.randrange(256)) for _ in range(4)])51 res = guess(sample)52 if res is not None:53 # This should decode without errors if this is *really*54 # something in this encoding. However, UTF-8 is a lot55 # more picky, so we expect errors there. UTF-16 surrogate56 # pairs also fail57 try:58 sample.decode(res)59 except UnicodeDecodeError as e:60 self.assertEqual(e.args[0].replace('-', '').lower(),61 res.replace('-', '').lower())62 if res == 'utf-8':63 self.assertTrue(e.args[-1], (64 'invalid continuation byte',65 'invalid start byte'))66 continue67 if res == 'utf-16':68 self.assertEqual(e.args[-1], 'unexpected end of data')69 self.assertTrue(sample[:2] in (70 codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE))71 # the second two bytes are in the range \ud800-\udfff72 # if someone wants to add tests for that as well. I don't73 # see the need; we are not testing UTF decoding here.74 continue75 raise7677 def test_get_environ_proxies_respects_no_proxy(self):78 '''This test confirms that the no_proxy environment setting is79 respected by get_environ_proxies().'''8081 # Store the current environment settings.82 try:83 old_http_proxy = os.environ['http_proxy']84 except KeyError:85 old_http_proxy = None8687 try:88 old_no_proxy = os.environ['no_proxy']89 except KeyError:90 old_no_proxy = None9192 # Set up some example environment settings.93 os.environ['http_proxy'] = 'http://www.example.com/'94 os.environ['no_proxy'] = r'localhost,.0.0.1:8080'9596 # Set up expected proxy return values.97 proxy_yes = {'http': 'http://www.example.com/'}98 proxy_no = {}99100 # Check that we get the right things back.101 self.assertEqual(proxy_yes,102 get_environ_proxies('http://www.google.com/'))103 self.assertEqual(proxy_no,104 get_environ_proxies('http://localhost/test'))105 self.assertEqual(proxy_no,106 get_environ_proxies('http://127.0.0.1:8080/'))107 self.assertEqual(proxy_yes,108 get_environ_proxies('http://127.0.0.1:8081/'))109110 # Return the settings to what they were.111 if old_http_proxy:112 os.environ['http_proxy'] = old_http_proxy113 else:114 del os.environ['http_proxy']115116 if old_no_proxy:117 os.environ['no_proxy'] = old_no_proxy118 else:119 del os.environ['no_proxy']120121if __name__ == '__main__':122 unittest.main()
modified:.travis.yml+2 added-2 removed
modified:Makefile+4 added-30 removed
1SHELL := /bin/bash23# test_requests_ext.py depends on external services, and async doesn't work under Python 34# Travis/Jenkins should be ensuring that all other tests pass on all supported versions5CI_TESTS=$(shell find tests/ -name "*.py" ! -name "test_requests_ext.py" ! -name "test_requests_async.py")67iter:8 python test_iteration.py910init:11 python setup.py develop12 pip install -r requirements.txt133test:15 nosetests ./tests/*4 py.test517lazy:18 nosetests --with-color tests/test_requests.py6test-deps:7 pip install py.test820simple:21 nosetests tests/test_requests.py2223citests:24 nosetests ${CI_TESTS} --with-xunit --xunit-file=junit-report.xml2526ci: citests cipyflakes2728travis: citests2930server:31 gunicorn httpbin:app --bind=0.0.0.0:7077 &329deps: urllib3 certs charade1011urllib3:12 rm -fr requests/packages/urllib3
9 unmodified lines
22 mv charade/charade requests/packages/23 rm -fr charade2425certs:50 cd requests && curl -O https://raw.github.com/kennethreitz/certifi/master/certifi/cacert.pem5152docs: site26 cd requests && curl -O https://raw.github.com/kennethreitz/certifi/master/certifi/cacert.pem
modified:requirements.txt+2 added-2 removed
1nose2rudolf21py.test2sphinx
deleted:test_iteration.py-29 removed
1import requests2import unittest345class IterationTestCase(unittest.TestCase):67 def test_assertion(self):8 assert 1910 # def test_dzubia(self):11 # s = requests.Session()12 # r = requests.Request(method='GET', url='http://github.com/')1314 # # r = s.send(r)1516 def test_prepared_request(self):17 s = requests.Session()18 r = requests.Request(method='GET', url='http://github.com/')19 r = r.prepare()2021 r = s.send(r)22 print r232425262728if __name__ == '__main__':29 unittest.main()
added:test_requests.org