aboutsummaryrefslogtreecommitdiff
path: root/test_requests.py
diff options
context:
space:
mode:
authorSVN-Git Migration <python-modules-team@lists.alioth.debian.org>2015-10-08 13:41:29 -0700
committerSVN-Git Migration <python-modules-team@lists.alioth.debian.org>2015-10-08 13:41:29 -0700
commit224200a9815f792f93632d03a38e4f0763ae69ef (patch)
tree161977259a7d8aa262aab60d7c8fce757ad3bb0f /test_requests.py
parent653256249d44c67a0852d57a166948a9dc712ef4 (diff)
downloadpython-requests-224200a9815f792f93632d03a38e4f0763ae69ef.tar
python-requests-224200a9815f792f93632d03a38e4f0763ae69ef.tar.gz
Imported Upstream version 2.0.0
Diffstat (limited to 'test_requests.py')
-rwxr-xr-xtest_requests.py179
1 files changed, 172 insertions, 7 deletions
diff --git a/test_requests.py b/test_requests.py
index 4a4831e..d1e6ed0 100755
--- a/test_requests.py
+++ b/test_requests.py
@@ -10,9 +10,10 @@ import unittest
import pickle
import requests
+import pytest
from requests.auth import HTTPDigestAuth
from requests.adapters import HTTPAdapter
-from requests.compat import str, cookielib
+from requests.compat import str, cookielib, getproxies, urljoin, urlparse
from requests.cookies import cookiejar_from_dict
from requests.exceptions import InvalidURL, MissingSchema
from requests.structures import CaseInsensitiveDict
@@ -23,11 +24,13 @@ except ImportError:
import io as StringIO
HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')
+# Issue #1483: Make sure the URL always has a trailing slash
+HTTPBIN = HTTPBIN.rstrip('/') + '/'
def httpbin(*suffix):
"""Returns url for HTTPBIN resource."""
- return HTTPBIN + '/'.join(suffix)
+ return urljoin(HTTPBIN, '/'.join(suffix))
class RequestsTestCase(unittest.TestCase):
@@ -87,9 +90,23 @@ class RequestsTestCase(unittest.TestCase):
self.assertEqual(request.url,
"http://example.com/path?key=value&a=b#fragment")
+ def test_mixed_case_scheme_acceptable(self):
+ s = requests.Session()
+ s.proxies = getproxies()
+ parts = urlparse(httpbin('get'))
+ schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',
+ 'https://', 'HTTPS://', 'hTTps://', 'HttPs://']
+ for scheme in schemes:
+ url = scheme + parts.netloc + parts.path
+ r = requests.Request('GET', url)
+ r = s.send(r.prepare())
+ self.assertEqual(r.status_code, 200,
+ "failed for scheme %s" % scheme)
+
def test_HTTP_200_OK_GET_ALTERNATIVE(self):
r = requests.Request('GET', httpbin('get'))
s = requests.Session()
+ s.proxies = getproxies()
r = s.send(r.prepare())
@@ -142,6 +159,11 @@ class RequestsTestCase(unittest.TestCase):
)
assert 'foo' not in s.cookies
+ def test_cookie_quote_wrapped(self):
+ s = requests.session()
+ s.get(httpbin('cookies/set?foo="bar:baz"'))
+ self.assertTrue(s.cookies['foo'] == '"bar:baz"')
+
def test_request_cookie_overrides_session_cookie(self):
s = requests.session()
s.cookies['foo'] = 'bar'
@@ -161,6 +183,12 @@ class RequestsTestCase(unittest.TestCase):
# Make sure the session cj is still the custom one
assert s.cookies is cj
+ def test_requests_in_history_are_not_overridden(self):
+ resp = requests.get(httpbin('redirect/3'))
+ urls = [r.url for r in resp.history]
+ req_urls = [r.request.url for r in resp.history]
+ self.assertEquals(urls, req_urls)
+
def test_user_agent_transfers(self):
heads = {
@@ -200,6 +228,34 @@ class RequestsTestCase(unittest.TestCase):
r = s.get(url)
self.assertEqual(r.status_code, 200)
+ def test_basicauth_with_netrc(self):
+ auth = ('user', 'pass')
+ wrong_auth = ('wronguser', 'wrongpass')
+ url = httpbin('basic-auth', 'user', 'pass')
+
+ def get_netrc_auth_mock(url):
+ return auth
+ requests.sessions.get_netrc_auth = get_netrc_auth_mock
+
+ # Should use netrc and work.
+ r = requests.get(url)
+ self.assertEqual(r.status_code, 200)
+
+ # Given auth should override and fail.
+ r = requests.get(url, auth=wrong_auth)
+ self.assertEqual(r.status_code, 401)
+
+ s = requests.session()
+
+ # Should use netrc and work.
+ r = s.get(url)
+ self.assertEqual(r.status_code, 200)
+
+ # Given auth should override and fail.
+ s.auth = wrong_auth
+ r = s.get(url)
+ self.assertEqual(r.status_code, 401)
+
def test_DIGEST_HTTP_200_OK_GET(self):
auth = HTTPDigestAuth('user', 'pass')
@@ -212,10 +268,26 @@ class RequestsTestCase(unittest.TestCase):
self.assertEqual(r.status_code, 401)
s = requests.session()
- s.auth = auth
+ s.auth = HTTPDigestAuth('user', 'pass')
r = s.get(url)
self.assertEqual(r.status_code, 200)
+ def test_DIGEST_AUTH_RETURNS_COOKIE(self):
+ url = httpbin('digest-auth', 'auth', 'user', 'pass')
+ auth = HTTPDigestAuth('user', 'pass')
+ r = requests.get(url)
+ assert r.cookies['fake'] == 'fake_value'
+
+ r = requests.get(url, auth=auth)
+ assert r.status_code == 200
+
+ def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):
+ url = httpbin('digest-auth', 'auth', 'user', 'pass')
+ auth = HTTPDigestAuth('user', 'pass')
+ s = requests.Session()
+ s.get(url, auth=auth)
+ assert s.cookies['fake'] == 'fake_value'
+
def test_DIGEST_STREAM(self):
auth = HTTPDigestAuth('user', 'pass')
@@ -284,6 +356,12 @@ class RequestsTestCase(unittest.TestCase):
except ValueError:
pass
+ def test_conflicting_post_params(self):
+ url = httpbin('post')
+ with open('requirements.txt') as f:
+ pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")
+ pytest.raises(ValueError, "requests.post(url, data=u'[{\"some\": \"data\"}]', files={'some': f})")
+
def test_request_ok_set(self):
r = requests.get(httpbin('status', '404'))
self.assertEqual(r.ok, False)
@@ -380,10 +458,28 @@ class RequestsTestCase(unittest.TestCase):
prep = req.prepare()
s = requests.Session()
+ s.proxies = getproxies()
resp = s.send(prep)
self.assertTrue(hasattr(resp, 'hook_working'))
+ def test_prepared_from_session(self):
+ class DummyAuth(requests.auth.AuthBase):
+ def __call__(self, r):
+ r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'
+ return r
+
+ req = requests.Request('GET', httpbin('headers'))
+ self.assertEqual(req.auth, None)
+
+ s = requests.Session()
+ s.auth = DummyAuth()
+
+ prep = s.prepare_request(req)
+ resp = s.send(prep)
+
+ self.assertTrue(resp.json()['headers']['Dummy-Auth-Test'], 'dummy-auth-test-ok')
+
def test_links(self):
r = requests.Response()
r.headers = {
@@ -469,6 +565,7 @@ class RequestsTestCase(unittest.TestCase):
s = requests.Session()
s = pickle.loads(pickle.dumps(s))
+ s.proxies = getproxies()
r = s.send(r.prepare())
self.assertEqual(r.status_code, 200)
@@ -482,20 +579,26 @@ class RequestsTestCase(unittest.TestCase):
s.headers.update({'accept': 'application/json'})
r = s.get(httpbin('get'))
headers = r.request.headers
- # ASCII encode because of key comparison changes in py3
self.assertEqual(
- headers['accept'.encode('ascii')],
+ headers['accept'],
'application/json'
)
self.assertEqual(
- headers['Accept'.encode('ascii')],
+ headers['Accept'],
'application/json'
)
self.assertEqual(
- headers['ACCEPT'.encode('ascii')],
+ headers['ACCEPT'],
'application/json'
)
+ def test_uppercase_scheme_redirect(self):
+ parts = urlparse(httpbin('html'))
+ url = "HTTP://" + parts.netloc + parts.path
+ r = requests.get(httpbin('redirect-to'), params={'url': url})
+ self.assertEqual(r.status_code, 200)
+ self.assertEqual(r.url.lower(), url.lower())
+
def test_transport_adapter_ordering(self):
s = requests.Session()
order = ['https://', 'http://']
@@ -557,6 +660,68 @@ class RequestsTestCase(unittest.TestCase):
r = requests.Request('GET', url).prepare()
self.assertEqual(r.url, url)
+ def test_header_keys_are_native(self):
+ headers = {u'unicode': 'blah', 'byte'.encode('ascii'): 'blah'}
+ r = requests.Request('GET', httpbin('get'), headers=headers)
+ p = r.prepare()
+
+ # This is testing that they are builtin strings. A bit weird, but there
+ # we go.
+ self.assertTrue('unicode' in p.headers.keys())
+ self.assertTrue('byte' in p.headers.keys())
+
+ def test_can_send_nonstring_objects_with_files(self):
+ data = {'a': 0.0}
+ files = {'b': 'foo'}
+ r = requests.Request('POST', httpbin('post'), data=data, files=files)
+ p = r.prepare()
+
+ self.assertTrue('multipart/form-data' in p.headers['Content-Type'])
+
+
+class TestContentEncodingDetection(unittest.TestCase):
+
+ def test_none(self):
+ encodings = requests.utils.get_encodings_from_content('')
+ self.assertEqual(len(encodings), 0)
+
+ def test_html_charset(self):
+ """HTML5 meta charset attribute"""
+ content = '<meta charset="UTF-8">'
+ encodings = requests.utils.get_encodings_from_content(content)
+ self.assertEqual(len(encodings), 1)
+ self.assertEqual(encodings[0], 'UTF-8')
+
+ def test_html4_pragma(self):
+ """HTML4 pragma directive"""
+ content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'
+ encodings = requests.utils.get_encodings_from_content(content)
+ self.assertEqual(len(encodings), 1)
+ self.assertEqual(encodings[0], 'UTF-8')
+
+ def test_xhtml_pragma(self):
+ """XHTML 1.x served with text/html MIME type"""
+ content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'
+ encodings = requests.utils.get_encodings_from_content(content)
+ self.assertEqual(len(encodings), 1)
+ self.assertEqual(encodings[0], 'UTF-8')
+
+ def test_xml(self):
+ """XHTML 1.x served as XML"""
+ content = '<?xml version="1.0" encoding="UTF-8"?>'
+ encodings = requests.utils.get_encodings_from_content(content)
+ self.assertEqual(len(encodings), 1)
+ self.assertEqual(encodings[0], 'UTF-8')
+
+ def test_precedence(self):
+ content = '''
+ <?xml version="1.0" encoding="XML"?>
+ <meta charset="HTML5">
+ <meta http-equiv="Content-type" content="text/html;charset=HTML4" />
+ '''.strip()
+ encodings = requests.utils.get_encodings_from_content(content)
+ self.assertEqual(encodings, ['HTML5', 'HTML4', 'XML'])
+
class TestCaseInsensitiveDict(unittest.TestCase):