test_requests.py
This file
Path
test_requests.py
949 lines · 32.3 KiB · Python
Last changed by
Merge pull request #1766 from Lukasa/qopKenneth Reitzbefore adoptiona030a58
History of this fileTake it
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import unittest10import pickle1112import requests13import pytest14from requests.auth import HTTPDigestAuth15from requests.adapters import HTTPAdapter16from requests.compat import str, cookielib, getproxies, urljoin, urlparse17from requests.cookies import cookiejar_from_dict18from requests.exceptions import InvalidURL, MissingSchema19from requests.structures import CaseInsensitiveDict2021try:22 import StringIO23except ImportError:24 import io as StringIO2526HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')27# Issue #1483: Make sure the URL always has a trailing slash28HTTPBIN = HTTPBIN.rstrip('/') + '/'293031def httpbin(*suffix):32 """Returns url for HTTPBIN resource."""33 return urljoin(HTTPBIN, '/'.join(suffix))343536class RequestsTestCase(unittest.TestCase):3738 _multiprocess_can_split_ = True3940 def setUp(self):41 """Create simple data set with headers."""42 pass4344 def tearDown(self):45 """Teardown."""46 pass4748 def test_entry_points(self):4950 requests.session51 requests.session().get52 requests.session().head53 requests.get54 requests.head55 requests.put56 requests.patch57 requests.post5859 def test_invalid_url(self):60 with pytest.raises(MissingSchema):61 requests.get('hiwpefhipowhefopw')62 with pytest.raises(InvalidURL):63 requests.get('http://')6465 def test_basic_building(self):66 req = requests.Request()67 req.url = 'http://kennethreitz.org/'68 req.data = {'life': '42'}6970 pr = req.prepare()71 assert pr.url == req.url72 assert pr.body == 'life=42'7374 def test_no_content_length(self):75 get_req = requests.Request('GET', httpbin('get')).prepare()76 assert 'Content-Length' not in get_req.headers77 head_req = requests.Request('HEAD', httpbin('head')).prepare()78 assert 'Content-Length' not in head_req.headers7980 def test_path_is_not_double_encoded(self):81 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()8283 assert request.path_url == '/get/test%20case'8485 def test_params_are_added_before_fragment(self):86 request = requests.Request('GET',87 "http://example.com/path#fragment", params={"a": "b"}).prepare()88 assert request.url == "http://example.com/path?a=b#fragment"89 request = requests.Request('GET',90 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()91 assert request.url == "http://example.com/path?key=value&a=b#fragment"9293 def test_mixed_case_scheme_acceptable(self):94 s = requests.Session()95 s.proxies = getproxies()96 parts = urlparse(httpbin('get'))97 schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',98 'https://', 'HTTPS://', 'hTTps://', 'HttPs://']99 for scheme in schemes:100 url = scheme + parts.netloc + parts.path101 r = requests.Request('GET', url)102 r = s.send(r.prepare())103 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)104105 def test_HTTP_200_OK_GET_ALTERNATIVE(self):106 r = requests.Request('GET', httpbin('get'))107 s = requests.Session()108 s.proxies = getproxies()109110 r = s.send(r.prepare())111112 assert r.status_code == 200113114 def test_HTTP_302_ALLOW_REDIRECT_GET(self):115 r = requests.get(httpbin('redirect', '1'))116 assert r.status_code == 200117118 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):119 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})120 # self.assertEqual(r.status_code, 200)121122 def test_HTTP_200_OK_GET_WITH_PARAMS(self):123 heads = {'User-agent': 'Mozilla/5.0'}124125 r = requests.get(httpbin('user-agent'), headers=heads)126127 assert heads['User-agent'] in r.text128 assert r.status_code == 200129130 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):131 heads = {'User-agent': 'Mozilla/5.0'}132133 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)134 assert r.status_code == 200135136 def test_set_cookie_on_301(self):137 s = requests.session()138 url = httpbin('cookies/set?foo=bar')139 r = s.get(url)140 assert s.cookies['foo'] == 'bar'141142 def test_cookie_sent_on_redirect(self):143 s = requests.session()144 s.get(httpbin('cookies/set?foo=bar'))145 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')146 assert 'Cookie' in r.json()['headers']147148 def test_cookie_removed_on_expire(self):149 s = requests.session()150 s.get(httpbin('cookies/set?foo=bar'))151 assert s.cookies['foo'] == 'bar'152 s.get(153 httpbin('response-headers'),154 params={155 'Set-Cookie':156 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'157 }158 )159 assert 'foo' not in s.cookies160161 def test_cookie_quote_wrapped(self):162 s = requests.session()163 s.get(httpbin('cookies/set?foo="bar:baz"'))164 assert s.cookies['foo'] == '"bar:baz"'165166 def test_cookie_persists_via_api(self):167 s = requests.session()168 r = s.get(httpbin('redirect/1'), cookies={'foo':'bar'})169 assert 'foo' in r.request.headers['Cookie']170 assert 'foo' in r.history[0].request.headers['Cookie']171172 def test_request_cookie_overrides_session_cookie(self):173 s = requests.session()174 s.cookies['foo'] = 'bar'175 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})176 assert r.json()['cookies']['foo'] == 'baz'177 # Session cookie should not be modified178 assert s.cookies['foo'] == 'bar'179180 def test_generic_cookiejar_works(self):181 cj = cookielib.CookieJar()182 cookiejar_from_dict({'foo': 'bar'}, cj)183 s = requests.session()184 s.cookies = cj185 r = s.get(httpbin('cookies'))186 # Make sure the cookie was sent187 assert r.json()['cookies']['foo'] == 'bar'188 # Make sure the session cj is still the custom one189 assert s.cookies is cj190 191 def test_param_cookiejar_works(self):192 cj = cookielib.CookieJar()193 cookiejar_from_dict({'foo' : 'bar'}, cj)194 s = requests.session()195 r = s.get(httpbin('cookies'), cookies=cj)196 # Make sure the cookie was sent197 assert r.json()['cookies']['foo'] == 'bar'198199 def test_requests_in_history_are_not_overridden(self):200 resp = requests.get(httpbin('redirect/3'))201 urls = [r.url for r in resp.history]202 req_urls = [r.request.url for r in resp.history]203 assert urls == req_urls204205 def test_user_agent_transfers(self):206207 heads = {208 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'209 }210211 r = requests.get(httpbin('user-agent'), headers=heads)212 assert heads['User-agent'] in r.text213214 heads = {215 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'216 }217218 r = requests.get(httpbin('user-agent'), headers=heads)219 assert heads['user-agent'] in r.text220221 def test_HTTP_200_OK_HEAD(self):222 r = requests.head(httpbin('get'))223 assert r.status_code == 200224225 def test_HTTP_200_OK_PUT(self):226 r = requests.put(httpbin('put'))227 assert r.status_code == 200228229 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):230 auth = ('user', 'pass')231 url = httpbin('basic-auth', 'user', 'pass')232233 r = requests.get(url, auth=auth)234 assert r.status_code == 200235236 r = requests.get(url)237 assert r.status_code == 401238239 s = requests.session()240 s.auth = auth241 r = s.get(url)242 assert r.status_code == 200243244 def test_basicauth_with_netrc(self):245 auth = ('user', 'pass')246 wrong_auth = ('wronguser', 'wrongpass')247 url = httpbin('basic-auth', 'user', 'pass')248249 def get_netrc_auth_mock(url):250 return auth251 requests.sessions.get_netrc_auth = get_netrc_auth_mock252253 # Should use netrc and work.254 r = requests.get(url)255 assert r.status_code == 200256257 # Given auth should override and fail.258 r = requests.get(url, auth=wrong_auth)259 assert r.status_code == 401260261 s = requests.session()262263 # Should use netrc and work.264 r = s.get(url)265 assert r.status_code == 200266267 # Given auth should override and fail.268 s.auth = wrong_auth269 r = s.get(url)270 assert r.status_code == 401271272 def test_DIGEST_HTTP_200_OK_GET(self):273274 auth = HTTPDigestAuth('user', 'pass')275 url = httpbin('digest-auth', 'auth', 'user', 'pass')276277 r = requests.get(url, auth=auth)278 assert r.status_code == 200279280 r = requests.get(url)281 assert r.status_code == 401282283 s = requests.session()284 s.auth = HTTPDigestAuth('user', 'pass')285 r = s.get(url)286 assert r.status_code == 200287288 def test_DIGEST_AUTH_RETURNS_COOKIE(self):289 url = httpbin('digest-auth', 'auth', 'user', 'pass')290 auth = HTTPDigestAuth('user', 'pass')291 r = requests.get(url)292 assert r.cookies['fake'] == 'fake_value'293294 r = requests.get(url, auth=auth)295 assert r.status_code == 200296297 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):298 url = httpbin('digest-auth', 'auth', 'user', 'pass')299 auth = HTTPDigestAuth('user', 'pass')300 s = requests.Session()301 s.get(url, auth=auth)302 assert s.cookies['fake'] == 'fake_value'303304 def test_DIGEST_STREAM(self):305306 auth = HTTPDigestAuth('user', 'pass')307 url = httpbin('digest-auth', 'auth', 'user', 'pass')308309 r = requests.get(url, auth=auth, stream=True)310 assert r.raw.read() != b''311312 r = requests.get(url, auth=auth, stream=False)313 assert r.raw.read() == b''314315 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):316317 auth = HTTPDigestAuth('user', 'wrongpass')318 url = httpbin('digest-auth', 'auth', 'user', 'pass')319320 r = requests.get(url, auth=auth)321 assert r.status_code == 401322323 r = requests.get(url)324 assert r.status_code == 401325326 s = requests.session()327 s.auth = auth328 r = s.get(url)329 assert r.status_code == 401330331 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):332333 auth = HTTPDigestAuth('user', 'pass')334 url = httpbin('digest-auth', 'auth', 'user', 'pass')335336 r = requests.get(url, auth=auth)337 assert '"auth"' in r.request.headers['Authorization']338339 def test_POSTBIN_GET_POST_FILES(self):340341 url = httpbin('post')342 post1 = requests.post(url).raise_for_status()343344 post1 = requests.post(url, data={'some': 'data'})345 assert post1.status_code == 200346347 with open('requirements.txt') as f:348 post2 = requests.post(url, files={'some': f})349 assert post2.status_code == 200350351 post4 = requests.post(url, data='[{"some": "json"}]')352 assert post4.status_code == 200353354 with pytest.raises(ValueError):355 requests.post(url, files = ['bad file data'])356357 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):358359 url = httpbin('post')360 post1 = requests.post(url).raise_for_status()361362 post1 = requests.post(url, data={'some': 'data'})363 assert post1.status_code == 200364365 with open('requirements.txt') as f:366 post2 = requests.post(url, data={'some': 'data'}, files={'some': f})367 assert post2.status_code == 200368369 post4 = requests.post(url, data='[{"some": "json"}]')370 assert post4.status_code == 200371372 with pytest.raises(ValueError):373 requests.post(url, files = ['bad file data'])374375 def test_conflicting_post_params(self):376 url = httpbin('post')377 with open('requirements.txt') as f:378 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")379 pytest.raises(ValueError, "requests.post(url, data=u'[{\"some\": \"data\"}]', files={'some': f})")380381 def test_request_ok_set(self):382 r = requests.get(httpbin('status', '404'))383 assert not r.ok384385 def test_status_raising(self):386 r = requests.get(httpbin('status', '404'))387 with pytest.raises(requests.exceptions.HTTPError):388 r.raise_for_status()389390 r = requests.get(httpbin('status', '500'))391 assert not r.ok392393 def test_decompress_gzip(self):394 r = requests.get(httpbin('gzip'))395 r.content.decode('ascii')396397 def test_unicode_get(self):398 url = httpbin('/get')399 requests.get(url, params={'foo': 'føø'})400 requests.get(url, params={'føø': 'føø'})401 requests.get(url, params={'føø': 'føø'})402 requests.get(url, params={'foo': 'foo'})403 requests.get(httpbin('ø'), params={'foo': 'foo'})404405 def test_unicode_header_name(self):406 requests.put(httpbin('put'), headers={str('Content-Type'): 'application/octet-stream'}, data='\xff') # compat.str is unicode.407408 def test_urlencoded_get_query_multivalued_param(self):409410 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))411 assert r.status_code == 200412 assert r.url == httpbin('get?test=foo&test=baz')413414 def test_different_encodings_dont_break_post(self):415 r = requests.post(httpbin('post'),416 data={'stuff': json.dumps({'a': 123})},417 params={'blah': 'asdf1234'},418 files={'file': ('test_requests.py', open(__file__, 'rb'))})419 assert r.status_code == 200420421 def test_unicode_multipart_post(self):422 r = requests.post(httpbin('post'),423 data={'stuff': u'ëlïxr'},424 files={'file': ('test_requests.py', open(__file__, 'rb'))})425 assert r.status_code == 200426427 r = requests.post(httpbin('post'),428 data={'stuff': u'ëlïxr'.encode('utf-8')},429 files={'file': ('test_requests.py', open(__file__, 'rb'))})430 assert r.status_code == 200431432 r = requests.post(httpbin('post'),433 data={'stuff': 'elixr'},434 files={'file': ('test_requests.py', open(__file__, 'rb'))})435 assert r.status_code == 200436437 r = requests.post(httpbin('post'),438 data={'stuff': 'elixr'.encode('utf-8')},439 files={'file': ('test_requests.py', open(__file__, 'rb'))})440 assert r.status_code == 200441442 def test_unicode_multipart_post_fieldnames(self):443 filename = os.path.splitext(__file__)[0] + '.py'444 r = requests.Request(method='POST',445 url=httpbin('post'),446 data={'stuff'.encode('utf-8'): 'elixr'},447 files={'file': ('test_requests.py',448 open(filename, 'rb'))})449 prep = r.prepare()450 assert b'name="stuff"' in prep.body451 assert b'name="b\'stuff\'"' not in prep.body452453 def test_unicode_method_name(self):454 files = {'file': open('test_requests.py', 'rb')}455 r = requests.request(method=u'POST', url=httpbin('post'), files=files)456 assert r.status_code == 200457458 def test_custom_content_type(self):459 r = requests.post(httpbin('post'),460 data={'stuff': json.dumps({'a': 123})},461 files={'file1': ('test_requests.py', open(__file__, 'rb')),462 'file2': ('test_requests', open(__file__, 'rb'),463 'text/py-content-type')})464 assert r.status_code == 200465 assert b"text/py-content-type" in r.request.body466467 def test_hook_receives_request_arguments(self):468 def hook(resp, **kwargs):469 assert resp is not None470 assert kwargs != {}471472 requests.Request('GET', HTTPBIN, hooks={'response': hook})473474 def test_session_hooks_are_used_with_no_request_hooks(self):475 hook = lambda x, *args, **kwargs: x476 s = requests.Session()477 s.hooks['response'].append(hook)478 r = requests.Request('GET', HTTPBIN)479 prep = s.prepare_request(r)480 assert prep.hooks['response'] != []481 assert prep.hooks['response'] == [hook]482483 def test_session_hooks_are_overriden_by_request_hooks(self):484 hook1 = lambda x, *args, **kwargs: x485 hook2 = lambda x, *args, **kwargs: x486 assert hook1 is not hook2487 s = requests.Session()488 s.hooks['response'].append(hook2)489 r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})490 prep = s.prepare_request(r)491 assert prep.hooks['response'] == [hook1]492493 def test_prepared_request_hook(self):494 def hook(resp, **kwargs):495 resp.hook_working = True496 return resp497498 req = requests.Request('GET', HTTPBIN, hooks={'response': hook})499 prep = req.prepare()500501 s = requests.Session()502 s.proxies = getproxies()503 resp = s.send(prep)504505 assert hasattr(resp, 'hook_working')506507 def test_prepared_from_session(self):508 class DummyAuth(requests.auth.AuthBase):509 def __call__(self, r):510 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'511 return r512513 req = requests.Request('GET', httpbin('headers'))514 assert not req.auth515516 s = requests.Session()517 s.auth = DummyAuth()518519 prep = s.prepare_request(req)520 resp = s.send(prep)521522 assert resp.json()['headers']['Dummy-Auth-Test'] == 'dummy-auth-test-ok'523524 def test_links(self):525 r = requests.Response()526 r.headers = {527 'cache-control': 'public, max-age=60, s-maxage=60',528 'connection': 'keep-alive',529 'content-encoding': 'gzip',530 'content-type': 'application/json; charset=utf-8',531 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',532 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',533 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',534 'link': ('<https://api.github.com/users/kennethreitz/repos?'535 'page=2&per_page=10>; rel="next", <https://api.github.'536 'com/users/kennethreitz/repos?page=7&per_page=10>; '537 ' rel="last"'),538 'server': 'GitHub.com',539 'status': '200 OK',540 'vary': 'Accept',541 'x-content-type-options': 'nosniff',542 'x-github-media-type': 'github.beta',543 'x-ratelimit-limit': '60',544 'x-ratelimit-remaining': '57'545 }546 assert r.links['next']['rel'] == 'next'547548 def test_cookie_parameters(self):549 key = 'some_cookie'550 value = 'some_value'551 secure = True552 domain = 'test.com'553 rest = {'HttpOnly': True}554555 jar = requests.cookies.RequestsCookieJar()556 jar.set(key, value, secure=secure, domain=domain, rest=rest)557558 assert len(jar) == 1559 assert 'some_cookie' in jar560561 cookie = list(jar)[0]562 assert cookie.secure == secure563 assert cookie.domain == domain564 assert cookie._rest['HttpOnly'] == rest['HttpOnly']565566 def test_time_elapsed_blank(self):567 r = requests.get(httpbin('get'))568 td = r.elapsed569 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)570 * 10**6) / 10**6)571 assert total_seconds > 0.0572573 def test_response_is_iterable(self):574 r = requests.Response()575 io = StringIO.StringIO('abc')576 read_ = io.read577578 def read_mock(amt, decode_content=None):579 return read_(amt)580 setattr(io, 'read', read_mock)581 r.raw = io582 assert next(iter(r))583 io.close()584585 def test_request_and_response_are_pickleable(self):586 r = requests.get(httpbin('get'))587588 # verify we can pickle the original request589 assert pickle.loads(pickle.dumps(r.request))590591 # verify we can pickle the response and that we have access to592 # the original request.593 pr = pickle.loads(pickle.dumps(r))594 assert r.request.url == pr.request.url595 assert r.request.headers == pr.request.headers596597 def test_get_auth_from_url(self):598 url = 'http://user:pass@complex.url.com/path?query=yes'599 assert ('user', 'pass') == requests.utils.get_auth_from_url(url)600601 def test_cannot_send_unprepared_requests(self):602 r = requests.Request(url=HTTPBIN)603 with pytest.raises(ValueError):604 requests.Session().send(r)605606 def test_http_error(self):607 error = requests.exceptions.HTTPError()608 assert not error.response609 response = requests.Response()610 error = requests.exceptions.HTTPError(response=response)611 assert error.response == response612 error = requests.exceptions.HTTPError('message', response=response)613 assert str(error) == 'message'614 assert error.response == response615616 def test_session_pickling(self):617 r = requests.Request('GET', httpbin('get'))618 s = requests.Session()619620 s = pickle.loads(pickle.dumps(s))621 s.proxies = getproxies()622623 r = s.send(r.prepare())624 assert r.status_code == 200625626 def test_fixes_1329(self):627 """628 Ensure that header updates are done case-insensitively.629 """630 s = requests.Session()631 s.headers.update({'ACCEPT': 'BOGUS'})632 s.headers.update({'accept': 'application/json'})633 r = s.get(httpbin('get'))634 headers = r.request.headers635 assert headers['accept'] == 'application/json'636 assert headers['Accept'] == 'application/json'637 assert headers['ACCEPT'] == 'application/json'638639 def test_uppercase_scheme_redirect(self):640 parts = urlparse(httpbin('html'))641 url = "HTTP://" + parts.netloc + parts.path642 r = requests.get(httpbin('redirect-to'), params={'url': url})643 assert r.status_code == 200644 assert r.url.lower() == url.lower()645646 def test_transport_adapter_ordering(self):647 s = requests.Session()648 order = ['https://', 'http://']649 assert order == list(s.adapters)650 s.mount('http://git', HTTPAdapter())651 s.mount('http://github', HTTPAdapter())652 s.mount('http://github.com', HTTPAdapter())653 s.mount('http://github.com/about/', HTTPAdapter())654 order = [655 'http://github.com/about/',656 'http://github.com',657 'http://github',658 'http://git',659 'https://',660 'http://',661 ]662 assert order == list(s.adapters)663 s.mount('http://gittip', HTTPAdapter())664 s.mount('http://gittip.com', HTTPAdapter())665 s.mount('http://gittip.com/about/', HTTPAdapter())666 order = [667 'http://github.com/about/',668 'http://gittip.com/about/',669 'http://github.com',670 'http://gittip.com',671 'http://github',672 'http://gittip',673 'http://git',674 'https://',675 'http://',676 ]677 assert order == list(s.adapters)678 s2 = requests.Session()679 s2.adapters = {'http://': HTTPAdapter()}680 s2.mount('https://', HTTPAdapter())681 assert 'http://' in s2.adapters682 assert 'https://' in s2.adapters683684 def test_header_remove_is_case_insensitive(self):685 # From issue #1321686 s = requests.Session()687 s.headers['foo'] = 'bar'688 r = s.get(httpbin('get'), headers={'FOO': None})689 assert 'foo' not in r.request.headers690691 def test_params_are_merged_case_sensitive(self):692 s = requests.Session()693 s.params['foo'] = 'bar'694 r = s.get(httpbin('get'), params={'FOO': 'bar'})695 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}696697698 def test_long_authinfo_in_url(self):699 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(700 'E8A3BE87-9E3F-4620-8858-95478E385B5B',701 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',702 'exactly-------------sixty-----------three------------characters',703 )704 r = requests.Request('GET', url).prepare()705 assert r.url == url706707 def test_header_keys_are_native(self):708 headers = {u'unicode': 'blah', 'byte'.encode('ascii'): 'blah'}709 r = requests.Request('GET', httpbin('get'), headers=headers)710 p = r.prepare()711712 # This is testing that they are builtin strings. A bit weird, but there713 # we go.714 assert 'unicode' in p.headers.keys()715 assert 'byte' in p.headers.keys()716717 def test_can_send_nonstring_objects_with_files(self):718 data = {'a': 0.0}719 files = {'b': 'foo'}720 r = requests.Request('POST', httpbin('post'), data=data, files=files)721 p = r.prepare()722723 assert 'multipart/form-data' in p.headers['Content-Type']724725 def test_autoset_header_values_are_native(self):726 data = 'this is a string'727 length = '16'728 req = requests.Request('POST', httpbin('post'), data=data)729 p = req.prepare()730731 assert p.headers['Content-Length'] == length732733 def test_oddball_schemes_dont_check_URLs(self):734 test_urls = (735 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',736 'file:///etc/passwd',737 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',738 )739 for test_url in test_urls:740 req = requests.Request('GET', test_url)741 preq = req.prepare()742 assert test_url == preq.url743744745class TestContentEncodingDetection(unittest.TestCase):746747 def test_none(self):748 encodings = requests.utils.get_encodings_from_content('')749 assert not len(encodings)750751 def test_html_charset(self):752 """HTML5 meta charset attribute"""753 content = '<meta charset="UTF-8">'754 encodings = requests.utils.get_encodings_from_content(content)755 assert len(encodings) == 1756 assert encodings[0] == 'UTF-8'757758 def test_html4_pragma(self):759 """HTML4 pragma directive"""760 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'761 encodings = requests.utils.get_encodings_from_content(content)762 assert len(encodings) == 1763 assert encodings[0] == 'UTF-8'764765 def test_xhtml_pragma(self):766 """XHTML 1.x served with text/html MIME type"""767 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'768 encodings = requests.utils.get_encodings_from_content(content)769 assert len(encodings) == 1770 assert encodings[0] == 'UTF-8'771772 def test_xml(self):773 """XHTML 1.x served as XML"""774 content = '<?xml version="1.0" encoding="UTF-8"?>'775 encodings = requests.utils.get_encodings_from_content(content)776 assert len(encodings) == 1777 assert encodings[0] == 'UTF-8'778779 def test_precedence(self):780 content = '''781 <?xml version="1.0" encoding="XML"?>782 <meta charset="HTML5">783 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />784 '''.strip()785 encodings = requests.utils.get_encodings_from_content(content)786 assert encodings == ['HTML5', 'HTML4', 'XML']787788789class TestCaseInsensitiveDict(unittest.TestCase):790791 def test_mapping_init(self):792 cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})793 assert len(cid) == 2794 assert 'foo' in cid795 assert 'bar' in cid796797 def test_iterable_init(self):798 cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])799 assert len(cid) == 2800 assert 'foo' in cid801 assert 'bar' in cid802803 def test_kwargs_init(self):804 cid = CaseInsensitiveDict(FOO='foo', BAr='bar')805 assert len(cid) == 2806 assert 'foo' in cid807 assert 'bar' in cid808809 def test_docstring_example(self):810 cid = CaseInsensitiveDict()811 cid['Accept'] = 'application/json'812 assert cid['aCCEPT'] == 'application/json'813 assert list(cid) == ['Accept']814815 def test_len(self):816 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})817 cid['A'] = 'a'818 assert len(cid) == 2819820 def test_getitem(self):821 cid = CaseInsensitiveDict({'Spam': 'blueval'})822 assert cid['spam'] == 'blueval'823 assert cid['SPAM'] == 'blueval'824825 def test_fixes_649(self):826 """__setitem__ should behave case-insensitively."""827 cid = CaseInsensitiveDict()828 cid['spam'] = 'oneval'829 cid['Spam'] = 'twoval'830 cid['sPAM'] = 'redval'831 cid['SPAM'] = 'blueval'832 assert cid['spam'] == 'blueval'833 assert cid['SPAM'] == 'blueval'834 assert list(cid.keys()) == ['SPAM']835836 def test_delitem(self):837 cid = CaseInsensitiveDict()838 cid['Spam'] = 'someval'839 del cid['sPam']840 assert 'spam' not in cid841 assert len(cid) == 0842843 def test_contains(self):844 cid = CaseInsensitiveDict()845 cid['Spam'] = 'someval'846 assert 'Spam' in cid847 assert 'spam' in cid848 assert 'SPAM' in cid849 assert 'sPam' in cid850 assert 'notspam' not in cid851852 def test_get(self):853 cid = CaseInsensitiveDict()854 cid['spam'] = 'oneval'855 cid['SPAM'] = 'blueval'856 assert cid.get('spam') == 'blueval'857 assert cid.get('SPAM') == 'blueval'858 assert cid.get('sPam') == 'blueval'859 assert cid.get('notspam', 'default') == 'default'860861 def test_update(self):862 cid = CaseInsensitiveDict()863 cid['spam'] = 'blueval'864 cid.update({'sPam': 'notblueval'})865 assert cid['spam'] == 'notblueval'866 cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})867 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})868 assert len(cid) == 2869 assert cid['foo'] == 'anotherfoo'870 assert cid['bar'] == 'anotherbar'871872 def test_update_retains_unchanged(self):873 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})874 cid.update({'foo': 'newfoo'})875 assert cid['bar'] == 'bar'876877 def test_iter(self):878 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})879 keys = frozenset(['Spam', 'Eggs'])880 assert frozenset(iter(cid)) == keys881882 def test_equality(self):883 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})884 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})885 assert cid == othercid886 del othercid['spam']887 assert cid != othercid888 assert cid == {'spam': 'blueval', 'eggs': 'redval'}889890 def test_setdefault(self):891 cid = CaseInsensitiveDict({'Spam': 'blueval'})892 assert cid.setdefault('spam', 'notblueval') == 'blueval'893 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'894895 def test_lower_items(self):896 cid = CaseInsensitiveDict({897 'Accept': 'application/json',898 'user-Agent': 'requests',899 })900 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())901 lowerkeyset = frozenset(['accept', 'user-agent'])902 assert keyset == lowerkeyset903904 def test_preserve_key_case(self):905 cid = CaseInsensitiveDict({906 'Accept': 'application/json',907 'user-Agent': 'requests',908 })909 keyset = frozenset(['Accept', 'user-Agent'])910 assert frozenset(i[0] for i in cid.items()) == keyset911 assert frozenset(cid.keys()) == keyset912 assert frozenset(cid) == keyset913914 def test_preserve_last_key_case(self):915 cid = CaseInsensitiveDict({916 'Accept': 'application/json',917 'user-Agent': 'requests',918 })919 cid.update({'ACCEPT': 'application/json'})920 cid['USER-AGENT'] = 'requests'921 keyset = frozenset(['ACCEPT', 'USER-AGENT'])922 assert frozenset(i[0] for i in cid.items()) == keyset923 assert frozenset(cid.keys()) == keyset924 assert frozenset(cid) == keyset925926927class UtilsTestCase(unittest.TestCase):928929 def test_super_len_io_streams(self):930 """ Ensures that we properly deal with different kinds of IO streams. """931 # uses StringIO or io.StringIO (see import above)932 from io import BytesIO933 from requests.utils import super_len934935 assert super_len(StringIO.StringIO()) == 0936 assert super_len(StringIO.StringIO('with so much drama in the LBC')) == 29937938 assert super_len(BytesIO()) == 0939 assert super_len(BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 40940941 try:942 import cStringIO943 except ImportError:944 pass945 else:946 assert super_len(cStringIO.StringIO('but some how, some way...')) == 25947948if __name__ == '__main__':949 unittest.main()