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
Provenance
- Commit
e4c4c80- Tree
df62bd9- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
a982b0d
14 files changed+8 added−1907 removed
deleted:tests/informal/test_leaked_connections.py-31 removed
1-"""2-This is an informal test originally written by Bluehorn;3-it verifies that Requests does not leak connections when4-the body of the request is not read.5-"""6-7-import gc8-import os9-import requests10-import subprocess11-import sys12-13-14-def main():15- gc.disable()16-17- for x in range(20):18- requests.head("http://www.google.com/")19-20- print("Open sockets after 20 head requests:")21- pid = os.getpid()22- subprocess.call("lsof -p%d -a -iTCP" % (pid,), shell=True)23-24- gcresult = gc.collect()25- print("Garbage collection result: %s" % (gcresult,))26-27- print("Open sockets after garbage collection:")28- subprocess.call("lsof -p%d -a -iTCP" % (pid,), shell=True)29-30-if __name__ == '__main__':31- sys.exit(main())deleted:tests/dummy_server.py-46 removed
1-import asyncore2-import threading3-import socket4-5-class HttpServer(threading.Thread):6- def __init__(self, port):7- threading.Thread.__init__(self)8- self.dispatcher = HttpServerDispatcher(port)9-10- def run(self):11- asyncore.loop()12-13- @property14- def connection_count(self):15- return self.dispatcher.connection_count16-17- def close(self):18- asyncore.close_all()19-20-class 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 = 028-29- def handle_accept(self):30- self.connection_count += 131- self.handler = RequestHandler(self.accept()[0])32-33- def handle_close(self):34- self.close()35-36-37-class 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")43-44- 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 -*-3-4-import sys5-import json6-import os7-import tempfile8-import unittest9-10-# Path hack.11-sys.path.insert(0, os.path.abspath('..'))12-import requests13-from requests.compat import cookielib14-15-# More hacks16-sys.path.append('.')17-from test_requests import httpbin, TestBaseMixin18-19-20-class CookieTests(TestBaseMixin, unittest.TestCase):21-22- 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'))25-26- # 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')34-35- q = requests.get(httpbin('cookies'), cookies=jar)36- self.assertEqual(json.loads(q.text)['cookies'], {'myname': 'myvalue'})37-38- 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)44-45- # 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'], {})48-49- # 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'})58-59- 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'})73-74- 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)80-81- 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)85-86- 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'])90-91- 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)98-99- 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'})102-103- 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, {})106-107- 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()))116-117- # 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())124-125- 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'))129-130- # 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')])134-135- # 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())139-140-141-class LWPCookieJarTest(TestBaseMixin, unittest.TestCase):142- """Check store/load of cookies to FileCookieJar's, specifically LWPCookieJar's."""143-144- COOKIEJAR_CLASS = cookielib.LWPCookieJar145-146- 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()152-153- def tearDown(self):154- try:155- self.cookiejar_file.close()156- except OSError:157- pass158-159- 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)165-166- 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')171-172- # 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='/')181-182- # 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)187-188- 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)193-194- # 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)203-204- # 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'})211-212- 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)219-220- requests.get(url, cookies=cookiejar)221- self.assertEqual(len(cookiejar), 1)222- self.assertCookieHas(list(cookiejar)[0], name='Persistent', value='CookiesAreScary')223-224- 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)228-229- # 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')236-237-238-class MozCookieJarTest(LWPCookieJarTest):239- """Same test, but substitute MozillaCookieJar."""240-241- COOKIEJAR_CLASS = cookielib.MozillaCookieJar242-243-if __name__ == '__main__':244- unittest.main()deleted:tests/test_keep_alive.py-65 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-4-import os5-import sys6-import unittest7-8-# Path hack.9-sys.path.insert(0, os.path.abspath('..'))10-import requests11-import dummy_server12-13-class 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}18-19- 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()23-24- def tearDown(self):25- self.proxy_server.close()26-27- def test_keep_alive_with_direct_connection(self):28- self.make_requests()29- self.check_each_request_are_in_same_connection()30-31- 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()35-36- def test_keep_alive_with_proxy_connection(self):37- self.make_proxy_requests()38- self.check_each_request_are_in_same_connection()39-40- 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()44-45- def make_proxy_requests(self):46- self.make_requests(self.proxies)47-48- def make_requests(self, proxies=None):49- for _ in range(self.request_count):50- self.session.get(self.url, proxies=proxies).text51-52- 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)55-56- 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)59-60- def disable_keep_alive_in_session(self):61- self.session.config['keep_alive'] = False62-63-64-if __name__ == '__main__':65- unittest.main()deleted:tests/test_proxies.py-29 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-4-import os5-import sys6-import unittest7-8-# Path hack.9-sys.path.insert(0, os.path.abspath('..'))10-import requests11-12-13-class HTTPSProxyTest(unittest.TestCase):14- """Smoke test for https functionality."""15-16- smoke_url = "https://github.com"17-18- 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)22-23- 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)27-28-if __name__ == '__main__':29- unittest.main()deleted:tests/test_requests_ext.py-124 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-4-# Path hack.5-import os6-import sys7-sys.path.insert(0, os.path.abspath('..'))8-9-import unittest10-11-import requests12-from requests.compat import is_py2, is_py313-14-try:15- import omnijson as json16-except ImportError:17- import json18-19-20-class RequestsTestSuite(unittest.TestCase):21- """Requests test cases."""22-23- # It goes to eleven.24- _multiprocess_can_split_ = True25-26- def test_addition(self):27- self.assertEqual(2, 1 + 1)28-29- def test_ssl_hostname_ok(self):30- requests.get('https://github.com', verify=True)31-32- def test_ssl_hostname_not_ok(self):33- requests.get('https://kennethreitz.com', verify=False)34-35- self.assertRaises(requests.exceptions.SSLError, requests.get, 'https://kennethreitz.com')36-37- def test_ssl_hostname_session_not_ok(self):38-39- s = requests.session()40-41- self.assertRaises(requests.exceptions.SSLError, s.get, 'https://kennethreitz.com')42-43- s.get('https://kennethreitz.com', verify=False)44-45- 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- '''49-50- 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)58-59- def test_unicode_error(self):60- url = 'http://blip.fm/~1abvfu'61- requests.get(url)62-63- 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)67-68- def test_unicode_redirect(self):69- '''This url redirects to a location that has a nonstandard70- character in it, that breaks requests in python2.771-72- After some research, the cause was identified as an unintended73- sideeffect of overriding of str with unicode.74-75- 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)83-84- 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)91-92- def test_redirect_encoding(self):93- '''This url redirects to94- http://www.dealipedia.com/deal_view_investment.php?r=20012'''95-96- r = requests.get('http://feedproxy.google.com/~r/Dealipedia' +97- 'News/~3/BQtUJRJeZlo/deal_view_investment.' +98- 'php')99- self.assertTrue(r.ok)100-101- 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')111-112- # 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'])116-117- # 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'])122-123-if __name__ == '__main__':124- unittest.main()deleted:tests/test_requests_https.py-32 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-4-import os5-import sys6-import unittest7-8-# Path hack.9-sys.path.insert(0, os.path.abspath('..'))10-import requests11-12-13-class HTTPSTest(unittest.TestCase):14- """Smoke test for https functionality."""15-16- smoke_url = "https://github.com"17-18- def perform_smoke_test(self, verify=False):19- result = requests.get(self.smoke_url, verify=verify)20- self.assertEqual(result.status_code, 200)21-22- def test_smoke(self):23- """Smoke test without verification."""24- self.perform_smoke_test(verify=False)25-26- def test_smoke_verified(self):27- """Smoke test with SSL verification."""28- self.perform_smoke_test(verify=True)29-30-31-if __name__ == '__main__':32- unittest.main()deleted:tests/test_requests.py-1151 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-4-# from __future__ import unicode_literals5-6-# Path hack.7-import sys8-import os9-sys.path.insert(0, os.path.abspath('..'))10-import json11-import unittest12-import pickle13-import tempfile14-import collections15-16-import requests17-from requests.compat import str, StringIO18-# import envoy19-from requests import HTTPError20-from requests import get, post, head, put21-from requests.auth import HTTPBasicAuth, HTTPDigestAuth22-from requests.exceptions import InvalidURL23-24-if 'HTTPBIN_URL' not in os.environ:25- os.environ['HTTPBIN_URL'] = 'http://httpbin.org/'26-27-HTTPBIN_URL = os.environ.get('HTTPBIN_URL')28-29-30-def httpbin(*suffix):31- """Returns url for HTTPBIN resource."""32- return HTTPBIN_URL + '/'.join(suffix)33-34-35-SERVICES = (httpbin, )36-37-_httpbin = False38-39-40-class TestSetup(object):41- """Requests test cases."""42-43- # It goes to eleven.44- _multiprocess_can_split_ = True45-46- def setUp(self):47-48- global _httpbin49-50- if (not 'HTTPBIN_URL' in os.environ) and not _httpbin:51- # c = envoy.connect('httpbin %s' % (PORT))52- # time.sleep(1)53- _httpbin = True54-55-56-class TestBaseMixin(object):57-58- 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)64-65-66-class RequestsTestSuite(TestSetup, TestBaseMixin, unittest.TestCase):67- """Requests test cases."""68-69- def test_entry_points(self):70-71- requests.session72- requests.session().get73- requests.session().head74- requests.get75- requests.head76- requests.put77- requests.patch78- requests.post79-80- def test_invalid_url(self):81- self.assertRaises(ValueError, get, 'hiwpefhipowhefopw')82-83- def test_path_is_not_double_encoded(self):84- request = requests.Request("http://0.0.0.0/get/test case")85-86- self.assertEqual(request.path_url, "/get/test%20case")87-88- 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")97-98- 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')102-103- def test_HTTP_200_OK_GET(self):104- r = get(httpbin('get'))105- self.assertEqual(r.status_code, 200)106-107- def test_response_sent(self):108- r = get(httpbin('get'))109-110- self.assertTrue(r.request.sent)111-112- def test_HTTP_302_ALLOW_REDIRECT_GET(self):113- r = get(httpbin('redirect', '1'))114- self.assertEqual(r.status_code, 200)115-116- def test_HTTP_302_GET(self):117- r = get(httpbin('redirect', '1'), allow_redirects=False)118- self.assertEqual(r.status_code, 302)119-120- def test_HTTP_200_OK_GET_WITH_PARAMS(self):121- heads = {'User-agent': 'Mozilla/5.0'}122-123- r = get(httpbin('user-agent'), headers=heads)124-125- self.assertTrue(heads['User-agent'] in r.text)126- self.assertEqual(r.status_code, 200)127-128- def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):129- heads = {'User-agent': 'Mozilla/5.0'}130-131- r = get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)132- self.assertEqual(r.status_code, 200)133-134- # 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)139-140- # # 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)144-145- # 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))156-157- # # 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))165-166- # # 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))179-180- # # 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))187-188- # # 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))193-194- # 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))198-199- # # 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))204-205- # 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))210-211- def test_user_agent_transfers(self):212- """Issue XX"""213-214- heads = {215- 'User-agent':216- 'Mozilla/5.0 (github.com/kennethreitz/requests)'217- }218-219- r = get(httpbin('user-agent'), headers=heads)220- self.assertTrue(heads['User-agent'] in r.text)221-222- heads = {223- 'user-agent':224- 'Mozilla/5.0 (github.com/kennethreitz/requests)'225- }226-227- r = get(httpbin('user-agent'), headers=heads)228- self.assertTrue(heads['user-agent'] in r.text)229-230- def test_HTTP_200_OK_HEAD(self):231- r = head(httpbin('get'))232- self.assertEqual(r.status_code, 200)233-234- def test_HTTP_200_OK_PUT(self):235- r = put(httpbin('put'))236- self.assertEqual(r.status_code, 200)237-238- def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):239-240- for service in SERVICES:241-242- auth = ('user', 'pass')243- url = service('basic-auth', 'user', 'pass')244-245- r = get(url, auth=auth)246- self.assertEqual(r.status_code, 200)247-248- r = get(url)249- self.assertEqual(r.status_code, 401)250-251- s = requests.session(auth=auth)252- r = get(url, session=s)253- self.assertEqual(r.status_code, 200)254-255- def test_BASICAUTH_HTTP_200_OK_GET(self):256-257- for service in SERVICES:258-259- auth = HTTPBasicAuth('user', 'pass')260- url = service('basic-auth', 'user', 'pass')261-262- r = get(url, auth=auth)263- self.assertEqual(r.status_code, 200)264-265- auth = ('user', 'pass')266- r = get(url, auth=auth)267- self.assertEqual(r.status_code, 200)268-269- r = get(url)270- self.assertEqual(r.status_code, 401)271-272- s = requests.session(auth=auth)273- r = get(url, session=s)274- self.assertEqual(r.status_code, 200)275-276- def test_DIGESTAUTH_HTTP_200_OK_GET(self):277-278- for service in SERVICES:279-280- auth = HTTPDigestAuth('user', 'pass')281- url = service('digest-auth', 'auth', 'user', 'pass')282-283- r = get(url, auth=auth)284- self.assertEqual(r.status_code, 200)285- self.assertEqual(len(r.history), 1)286-287- r = get(url, auth=auth)288- self.assertEqual(r.status_code, 200)289- self.assertEqual(len(r.history), 0)290-291- r = get(url)292- self.assertEqual(r.status_code, 401)293-294- s = requests.session(auth=auth)295- r = get(url, session=s)296- self.assertEqual(r.status_code, 200)297-298- def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):299-300- for service in SERVICES:301-302- auth = HTTPDigestAuth('user', 'wrongpass')303- url = service('digest-auth', 'auth', 'user', 'pass')304-305- r = get(url, auth=auth)306- self.assertEqual(r.status_code, 401)307-308- s = requests.session(auth=auth)309- r = get(url, session=s)310- self.assertEqual(r.status_code, 401)311-312- def test_POSTBIN_GET_POST_FILES(self):313-314- for service in SERVICES:315-316- url = service('post')317- post1 = post(url).raise_for_status()318-319- post1 = post(url, data={'some': 'data'})320- self.assertEqual(post1.status_code, 200)321-322- 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)327-328- post4 = post(url, data='[{"some": "json"}]')329- self.assertEqual(post4.status_code, 200)330-331- try:332- post(url, files=['bad file data'])333- except ValueError:334- pass335-336- def test_POSTBIN_GET_POST_FILES_WITH_PARAMS(self):337-338- for service in SERVICES:339-340- 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)])345-346- self.assertEqual(post1.status_code, 200)347- self.assertEqual(post2.status_code, 200)348- self.assertEqual(post3.status_code, 200)349-350- def test_POSTBIN_GET_POST_FILES_WITH_CJK_PARAMS(self):351-352- for service in SERVICES:353-354- 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)])359-360- self.assertEqual(post1.status_code, 200)361- self.assertEqual(post2.status_code, 200)362- self.assertEqual(post3.status_code, 200)363-364- def test_POSTBIN_GET_POST_FILES_WITH_HEADERS(self):365-366- for service in SERVICES:367-368- url = service('post')369-370- with open(__file__) as f:371-372- post2 = post(url,373- files={'some': f},374- headers={'User-Agent': 'requests-tests'})375-376- self.assertEqual(post2.status_code, 200)377-378- def test_POSTBIN_GET_POST_FILES_STRINGS(self):379-380- for service in SERVICES:381-382- url = service('post')383-384- post1 = post(url, files={'fname.txt': 'fdata'})385- self.assertEqual(post1.status_code, 200)386-387- post2 = post(url, files={'fname.txt': 'fdata',388- 'fname2.txt': 'more fdata'})389- self.assertEqual(post2.status_code, 200)390-391- post3 = post(url, files={'fname.txt': 'fdata',392- 'fname2.txt': open(__file__, 'rb')})393- self.assertEqual(post3.status_code, 200)394-395- post4 = post(url, files={'fname.txt': 'fdata'})396- self.assertEqual(post4.status_code, 200)397-398- post5 = post(url, files={'file': ('file.txt', 'more fdata')})399- self.assertEqual(post5.status_code, 200)400-401- # 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'407-408- post6 = post(url, files={'fname.txt': fdata})409- self.assertEqual(post6.status_code, 200)410-411- 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')416-417- 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')423-424- post9 = post(url, files=[('fname.txt', fdata)])425- self.assertEqual(post9.status_code, 200)426-427- post10 = post(url, files=[('file',428- ('file.txt', 'more file data'))])429- self.assertEqual(post10.status_code, 200)430-431- 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)437-438- def test_nonzero_evaluation(self):439-440- for service in SERVICES:441-442- r = get(service('status', '500'))443- self.assertEqual(bool(r), False)444-445- r = get(service('/get'))446- self.assertEqual(bool(r), True)447-448- def test_request_ok_set(self):449-450- for service in SERVICES:451-452- r = get(service('status', '404'))453- # print r.status_code454- # r.raise_for_status()455- self.assertEqual(r.ok, False)456-457- def test_status_raising(self):458- r = get(httpbin('status', '404'))459- self.assertRaises(HTTPError, r.raise_for_status)460-461- r = get(httpbin('status', '200'))462- self.assertFalse(r.error)463- r.raise_for_status()464-465- def test_decompress_gzip(self):466-467- r = get(httpbin('gzip'))468- r.content.decode('ascii')469-470- def test_response_has_unicode_url(self):471-472- for service in SERVICES:473-474- url = service('get')475-476- response = get(url)477-478- self.assertTrue(isinstance(response.url, str))479-480- def test_unicode_get(self):481-482- for service in SERVICES:483-484- url = service('/get')485-486- 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'})491-492- def test_httpauth_recursion(self):493-494- http_auth = HTTPBasicAuth('user', 'BADpass')495-496- for service in SERVICES:497- r = get(service('basic-auth', 'user', 'pass'), auth=http_auth)498- self.assertEqual(r.status_code, 401)499-500- def test_urlencoded_post_data(self):501-502- for service in SERVICES:503-504- r = post(service('post'), data=dict(test='fooaowpeuf'))505-506- self.assertEqual(r.status_code, 200)507- self.assertEqual(r.headers['content-type'], 'application/json')508- self.assertEqual(r.url, service('post'))509-510- rbody = json.loads(r.text)511-512- self.assertEqual(rbody.get('form'), dict(test='fooaowpeuf'))513- self.assertEqual(rbody.get('data'), '')514-515- def test_nonurlencoded_post_data(self):516-517- for service in SERVICES:518-519- r = post(service('post'), data='fooaowpeuf')520-521- self.assertEqual(r.status_code, 200)522- self.assertEqual(r.headers['content-type'], 'application/json')523- self.assertEqual(r.url, service('post'))524-525- 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".528-529- self.assertTrue(rbody.get('form') in (None, {}))530- self.assertEqual(rbody.get('data'), 'fooaowpeuf')531-532- def test_file_post_data(self):533-534- filecontent = b"fooaowpeufbarasjhf"535- testfile = tempfile.NamedTemporaryFile(delete=False)536- testfile.write(filecontent)537- testfile.flush()538- testfile.close()539-540- for service in SERVICES:541-542- data = open(testfile.name, "rb")543- r = post(service('post'), data=data,544- headers={"content-type": "application/octet-stream"})545-546- 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'))550-551- 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)555-556- def test_urlencoded_post_querystring(self):557-558- for service in SERVICES:559-560- r = post(service('post'), params=dict(test='fooaowpeuf'))561-562- self.assertEqual(r.status_code, 200)563- self.assertEqual(r.headers['content-type'], 'application/json')564- self.assertEqual(r.url, service('post?test=fooaowpeuf'))565-566- rbody = json.loads(r.text)567- self.assertEqual(rbody.get('form'), {}) # No form supplied568- self.assertEqual(rbody.get('data'), '')569-570- def test_urlencoded_post_query_and_data(self):571-572- for service in SERVICES:573-574- r = post(575- service('post'),576- params=dict(test='fooaowpeuf'),577- data=dict(test2="foobar"))578-579- self.assertEqual(r.status_code, 200)580- self.assertEqual(r.headers['content-type'], 'application/json')581- self.assertEqual(r.url, service('post?test=fooaowpeuf'))582-583- rbody = json.loads(r.text)584- self.assertEqual(rbody.get('form'), dict(test2='foobar'))585- self.assertEqual(rbody.get('data'), '')586-587- def test_nonurlencoded_postdata(self):588-589- for service in SERVICES:590-591- r = post(service('post'), data="foobar")592-593- self.assertEqual(r.status_code, 200)594- self.assertEqual(r.headers['content-type'], 'application/json')595-596- rbody = json.loads(r.text)597-598- self.assertTrue(rbody.get('form') in (None, {}))599- self.assertEqual(rbody.get('data'), 'foobar')600-601- def test_urlencoded_get_query_multivalued_param(self):602-603- for service in SERVICES:604-605- 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'))608-609- def test_urlencoded_post_querystring_multivalued(self):610-611- for service in SERVICES:612-613- 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'))617-618- rbody = json.loads(r.text)619- self.assertEqual(rbody.get('form'), {}) # No form supplied620- self.assertEqual(rbody.get('data'), '')621-622- def test_urlencoded_post_query_multivalued_and_data(self):623-624- for service in SERVICES:625-626- r = post(627- service('post'),628- params=dict(test=['foo', 'baz']),629- data=dict(test2="foobar", test3=['foo', 'baz']))630-631- 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'))634-635- # print(r.text)636- # print('-----------------------')637-638- rbody = json.loads(r.text)639- self.assertEqual(rbody.get('form'), dict(test2='foobar', test3=['foo', 'baz']))640- self.assertEqual(rbody.get('data'), '')641-642- 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'654-655- r = post(656- service('post'),657- data=dict(test=('foo', nonascii)))658-659- self.assertEqual(r.status_code, 200)660- self.assertEqual(r.headers['content-type'], 'application/json')661-662- rbody = json.loads(r.text)663- self.assertEqual(rbody.get('form'),664- dict(test=['foo', nonascii]))665-666- def test_GET_no_redirect(self):667-668- for service in SERVICES:669-670- r = get(service('redirect', '3'), allow_redirects=False)671- self.assertEqual(r.status_code, 302)672- self.assertEqual(len(r.history), 0)673-674- def test_HEAD_no_redirect(self):675-676- for service in SERVICES:677-678- r = head(service('redirect', '3'), allow_redirects=False)679- self.assertEqual(r.status_code, 302)680- self.assertEqual(len(r.history), 0)681-682- def test_redirect_history(self):683-684- for service in SERVICES:685-686- r = get(service('redirect', '3'))687- self.assertEqual(r.status_code, 200)688- self.assertEqual(len(r.history), 3)689-690- def test_relative_redirect_history(self):691-692- for service in SERVICES:693-694- r = get(service('relative-redirect', '3'))695- self.assertEqual(r.status_code, 200)696- self.assertEqual(len(r.history), 3)697-698- def test_session_HTTP_200_OK_GET(self):699-700- s = requests.session()701- r = get(httpbin('get'), session=s)702- self.assertEqual(r.status_code, 200)703-704- def test_session_persistent_headers(self):705-706- heads = {'User-agent': 'Mozilla/5.0'}707-708- s = requests.session()709- s.headers = heads710-711- # 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)714-715- r2 = get(httpbin('user-agent'), session=s)716- self.assertTrue(heads['User-agent'] in r2.text)717-718- 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)721-722- self.assertEqual(r2.status_code, 200)723-724- def test_single_hook(self):725-726- def add_foo_header(args):727- if not args.get('headers'):728- args['headers'] = {}729-730- args['headers'].update({731- 'X-Foo': 'foo'732- })733-734- return args735-736- for service in SERVICES:737- url = service('headers')738- response = get(url=url, hooks={'args': add_foo_header})739-740- self.assertTrue('foo' in response.text)741-742- def test_multiple_hooks(self):743-744- def add_foo_header(args):745- if not args.get('headers'):746- args['headers'] = {}747-748- args['headers'].update({749- 'X-Foo': 'foo'750- })751-752- return args753-754- def add_bar_header(args):755- if not args.get('headers'):756- args['headers'] = {}757-758- args['headers'].update({759- 'X-Bar': 'bar'760- })761-762- return args763-764- for service in SERVICES:765- url = service('headers')766-767- response = get(url=url,768- hooks={769- 'args': [add_foo_header, add_bar_header]770- }771- )772-773- for text in ('foo', 'bar'):774- self.assertTrue(text in response.text)775-776- 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'] = {}781-782- args['headers'].update({783- 'X-Foo': 'foo'784- })785-786- return args787-788- def add_bar_header(args):789- if not args.get('headers'):790- args['headers'] = {}791-792- args['headers'].update({793- 'X-Bar': 'bar'794- })795-796- return args797-798- def assert_hooks_are_callable(hooks):799- for h in hooks['args']:800- self.assertTrue(isinstance(h, collections.Callable))801-802- 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)806-807- r = requests.models.Request(hooks={'args': hooks})808- assert_hooks_are_callable(r.hooks)809-810- hooks.append('string that should not be registered')811- r = requests.models.Request(hooks={'args': hooks})812- assert_hooks_are_callable(r.hooks)813-814- def test_session_persistent_cookies(self):815-816- s = requests.session()817-818- # 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)822-823- # Those cookies persist transparently.824- c = json.loads(r.text).get('cookies')825- self.assertEqual(c, _c)826-827- # Double check.828- r = get(httpbin('cookies'), cookies={}, session=s)829- c = json.loads(r.text).get('cookies')830- self.assertEqual(c, _c)831-832- # 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)837-838- # 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)843-844- # 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')847-848- self.assertTrue('k' in c)849-850- # And server-set cookie persistience.851- r = get(httpbin('cookies'), session=s)852- c = json.loads(r.text).get('cookies')853-854- self.assertTrue('k' in c)855-856- def test_session_persistent_params(self):857-858- params = {'a': 'a_test'}859-860- s = requests.session()861- s.params = params862-863- # 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)866-867- params2 = {'b': 'b_test'}868-869- r2 = get(httpbin('get'), params=params2, session=s)870- for param in (params['a'], params2['b']):871- self.assertTrue(param in r2.text)872-873- params3 = {'b': 'b_test', 'a': None, 'c': 'c_test'}874-875- r3 = get(httpbin('get'), params=params3, session=s)876-877- self.assertFalse(params['a'] in r3.text)878-879- for param in (params3['b'], params3['c']):880- self.assertTrue(param in r3.text)881-882- 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)891-892- def test_session_pickling(self):893-894- s = requests.session(895- headers={'header': 'value'},896- cookies={'a-cookie': 'cookie-value'},897- auth=('username', 'password'))898-899- ds = pickle.loads(pickle.dumps(s))900-901- self.assertEqual(s.headers, ds.headers)902- self.assertEqual(s.auth, ds.auth)903-904- # 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')908-909- 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)914-915- 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)919-920- 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)924-925- def test_connection_error(self):926- try:927- get('http://localhost:1/nope')928- except requests.ConnectionError:929- pass930- else:931- self.fail()932-933- def test_cached_response(self):934-935- r1 = get(httpbin('get'), prefetch=False)936- self.assertFalse(r1._content)937- self.assertTrue(r1.content)938- self.assertTrue(r1.text)939-940- r2 = get(httpbin('get'), prefetch=True)941- self.assertTrue(r2._content)942- self.assertTrue(r2.content)943- self.assertTrue(r2.text)944-945- def test_iter_lines(self):946-947- lines = (0, 2, 10, 100)948-949- for i in lines:950- r = get(httpbin('stream', str(i)), prefetch=False)951- lines = list(r.iter_lines())952- len_lines = len(lines)953-954- self.assertEqual(i, len_lines)955-956- # 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- )963-964- # Make a request and monkey-patch its contents965- r = get(httpbin('get'), prefetch=False)966- r.raw = StringIO(quote)967-968- lines = list(r.iter_lines())969- len_lines = len(lines)970- self.assertEqual(len_lines, 3)971-972- joined = lines[0] + '\n' + lines[1] + '\r\n' + lines[2]973- self.assertEqual(joined, quote)974-975- 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)981-982- # 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)987-988- # 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)991-992-993- def test_upload_binary_data(self):994-995- requests.get(httpbin('post'), auth=('a', 'b'), data='\xff')996-997- 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')1003-1004- def test_useful_exception_for_invalid_scheme(self):1005-1006- # 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/')1012-1013- 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')1019-1020-1021- def test_empty_response(self):1022- r = requests.get(httpbin('status', '404'))1023- r.text1024-1025- 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')1032-1033- # 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')1037-1038- def test_head_content(self):1039- """Test that empty bodies are properly supported."""1040-1041- r = requests.head(httpbin('headers'))1042- r.content1043- r.text1044-1045- 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."""1048-1049- 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)1057-1058- 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'), '')1063-1064- 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('{'))1072-1073- 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('{'))1081-1082- 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'1093-1094- def __str__(self):1095- return 'http://httpbin.org/get'1096-1097- r = get(URL())1098- self.assertEqual(r.status_code, 200)1099-1100- 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- """1105-1106- fields = [1107- ('__field__', '__value__'),1108- ('__field__', '__value__'),1109- ]1110-1111- r = post(httpbin('post'), data=fields, files=fields)1112- t = json.loads(r.text)1113-1114- self.assertEqual(t.get('form'), {1115- '__field__': [1116- '__value__',1117- '__value__',1118- ]1119- })1120-1121- # 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)1130-1131- 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'})1134-1135- 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/')1139-1140- 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)1149-1150-if __name__ == '__main__':1151- unittest.main()deleted:tests/test_utils.py-122 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-4-import codecs5-import os6-import sys7-import unittest8-import random9-10-# Path hack.11-sys.path.insert(0, os.path.abspath('..'))12-from requests.utils import get_environ_proxies13-import requests.utils14-from requests.compat import is_py3, bytes15-16-17-if is_py3:18- unichr = chr19- byteschr = lambda c: bytes([c])20-else:21- byteschr = chr22-23-24-class UtilityTests(unittest.TestCase):25- """Tests for the JSON UTF encoding guessing code."""26-27- 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- )32-33- 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)42-43- 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- raise76-77- 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().'''80-81- # Store the current environment settings.82- try:83- old_http_proxy = os.environ['http_proxy']84- except KeyError:85- old_http_proxy = None86-87- try:88- old_no_proxy = os.environ['no_proxy']89- except KeyError:90- old_no_proxy = None91-92- # 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'95-96- # Set up expected proxy return values.97- proxy_yes = {'http': 'http://www.example.com/'}98- proxy_no = {}99-100- # 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/'))109-110- # 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']115-116- if old_no_proxy:117- os.environ['no_proxy'] = old_no_proxy118- else:119- del os.environ['no_proxy']120-121-if __name__ == '__main__':122- unittest.main()modified:.travis.yml+2 added-2 removed
2 unmodified lines345677899102 unmodified lines - 2.6 - 2.7 - 3.2env: HTTPBIN_URL=http://httpbin.org/script: make travisscript: make testinstall: - pip install nose - make test-deps - pip install . --use-mirrorsmodified:Makefile+4 added-30 removed
1 SHELL := /bin/bash2 3-# 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 versions5-CI_TESTS=$(shell find tests/ -name "*.py" ! -name "test_requests_ext.py" ! -name "test_requests_async.py")6-7-iter:8- python test_iteration.py9-10-init:11- python setup.py develop12- pip install -r requirements.txt13-3 test:15- nosetests ./tests/*4+ py.test5 17-lazy:18- nosetests --with-color tests/test_requests.py6+test-deps:7+ pip install py.test8 20-simple:21- nosetests tests/test_requests.py22-23-citests:24- nosetests ${CI_TESTS} --with-xunit --xunit-file=junit-report.xml25-26-ci: citests cipyflakes27-28-travis: citests29-30-server:31- gunicorn httpbin:app --bind=0.0.0.0:7077 &32-9 deps: urllib3 certs charade10 11 urllib3:12 rm -fr requests/packages/urllib39 unmodified lines22 mv charade/charade requests/packages/23 rm -fr charade24 25 certs:50- cd requests && curl -O https://raw.github.com/kennethreitz/certifi/master/certifi/cacert.pem51-52-docs: site26+ cd requests && curl -O https://raw.github.com/kennethreitz/certifi/master/certifi/cacert.pemmodified:requirements.txt+2 added-2 removed
1-nose2-rudolf21+py.test2+sphinxdeleted:test_iteration.py-29 removed
1-import requests2-import unittest3-4-5-class IterationTestCase(unittest.TestCase):6-7- def test_assertion(self):8- assert 19-10- # def test_dzubia(self):11- # s = requests.Session()12- # r = requests.Request(method='GET', url='http://github.com/')13-14- # # r = s.send(r)15-16- def test_prepared_request(self):17- s = requests.Session()18- r = requests.Request(method='GET', url='http://github.com/')19- r = r.prepare()20-21- r = s.send(r)22- print r23-24-25-26-27-28-if __name__ == '__main__':29- unittest.main()added:test_requests.org