test_requests.py
This file
Path
test_requests.py
831 lines · 28.6 KiB · Python
Last changed by
Merge pull request #1575 from jparise/content-encodingKenneth Reitzbefore adoption6c73d86
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 requests13from requests.auth import HTTPDigestAuth14from requests.adapters import HTTPAdapter15from requests.compat import str, cookielib, getproxies, urljoin, urlparse16from requests.cookies import cookiejar_from_dict17from requests.exceptions import InvalidURL, MissingSchema18from requests.structures import CaseInsensitiveDict1920try:21 import StringIO22except ImportError:23 import io as StringIO2425HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')26# Issue #1483: Make sure the URL always has a trailing slash27HTTPBIN = HTTPBIN.rstrip('/') + '/'282930def httpbin(*suffix):31 """Returns url for HTTPBIN resource."""32 return urljoin(HTTPBIN, '/'.join(suffix))333435class RequestsTestCase(unittest.TestCase):3637 _multiprocess_can_split_ = True3839 def setUp(self):40 """Create simple data set with headers."""41 pass4243 def tearDown(self):44 """Teardown."""45 pass4647 def test_entry_points(self):4849 requests.session50 requests.session().get51 requests.session().head52 requests.get53 requests.head54 requests.put55 requests.patch56 requests.post5758 def test_invalid_url(self):59 self.assertRaises(MissingSchema, requests.get, 'hiwpefhipowhefopw')60 self.assertRaises(InvalidURL, requests.get, 'http://')6162 def test_basic_building(self):63 req = requests.Request()64 req.url = 'http://kennethreitz.org/'65 req.data = {'life': '42'}6667 pr = req.prepare()68 assert pr.url == req.url69 assert pr.body == 'life=42'7071 def test_no_content_length(self):72 get_req = requests.Request('GET', httpbin('get')).prepare()73 self.assertTrue('Content-Length' not in get_req.headers)74 head_req = requests.Request('HEAD', httpbin('head')).prepare()75 self.assertTrue('Content-Length' not in head_req.headers)7677 def test_path_is_not_double_encoded(self):78 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()7980 self.assertEqual(request.path_url, "/get/test%20case")8182 def test_params_are_added_before_fragment(self):83 request = requests.Request('GET',84 "http://example.com/path#fragment", params={"a": "b"}).prepare()85 self.assertEqual(request.url,86 "http://example.com/path?a=b#fragment")87 request = requests.Request('GET',88 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()89 self.assertEqual(request.url,90 "http://example.com/path?key=value&a=b#fragment")9192 def test_mixed_case_scheme_acceptable(self):93 s = requests.Session()94 s.proxies = getproxies()95 parts = urlparse(httpbin('get'))96 schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',97 'https://', 'HTTPS://', 'hTTps://', 'HttPs://']98 for scheme in schemes:99 url = scheme + parts.netloc + parts.path100 r = requests.Request('GET', url)101 r = s.send(r.prepare())102 self.assertEqual(r.status_code, 200,103 "failed for scheme %s" % 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 self.assertEqual(r.status_code, 200)113114 def test_HTTP_302_ALLOW_REDIRECT_GET(self):115 r = requests.get(httpbin('redirect', '1'))116 self.assertEqual(r.status_code, 200)117118 # 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 self.assertTrue(heads['User-agent'] in r.text)128 self.assertEqual(r.status_code, 200)129130 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 self.assertEqual(r.status_code, 200)135136 def test_set_cookie_on_301(self):137 s = requests.session()138 url = httpbin('cookies/set?foo=bar')139 r = s.get(url)140 self.assertTrue(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 self.assertTrue("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 self.assertTrue(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 self.assertTrue(s.cookies['foo'] == '"bar:baz"')165166 def test_request_cookie_overrides_session_cookie(self):167 s = requests.session()168 s.cookies['foo'] = 'bar'169 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})170 assert r.json()['cookies']['foo'] == 'baz'171 # Session cookie should not be modified172 assert s.cookies['foo'] == 'bar'173174 def test_generic_cookiejar_works(self):175 cj = cookielib.CookieJar()176 cookiejar_from_dict({'foo': 'bar'}, cj)177 s = requests.session()178 s.cookies = cj179 r = s.get(httpbin('cookies'))180 # Make sure the cookie was sent181 assert r.json()['cookies']['foo'] == 'bar'182 # Make sure the session cj is still the custom one183 assert s.cookies is cj184 185 def test_requests_in_history_are_not_overridden(self):186 resp = requests.get(httpbin('redirect/3'))187 urls = [r.url for r in resp.history]188 req_urls = [r.request.url for r in resp.history]189 self.assertEquals(urls, req_urls)190 191 def test_user_agent_transfers(self):192193 heads = {194 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'195 }196197 r = requests.get(httpbin('user-agent'), headers=heads)198 self.assertTrue(heads['User-agent'] in r.text)199200 heads = {201 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'202 }203204 r = requests.get(httpbin('user-agent'), headers=heads)205 self.assertTrue(heads['user-agent'] in r.text)206207 def test_HTTP_200_OK_HEAD(self):208 r = requests.head(httpbin('get'))209 self.assertEqual(r.status_code, 200)210211 def test_HTTP_200_OK_PUT(self):212 r = requests.put(httpbin('put'))213 self.assertEqual(r.status_code, 200)214215 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):216 auth = ('user', 'pass')217 url = httpbin('basic-auth', 'user', 'pass')218219 r = requests.get(url, auth=auth)220 self.assertEqual(r.status_code, 200)221222 r = requests.get(url)223 self.assertEqual(r.status_code, 401)224225 s = requests.session()226 s.auth = auth227 r = s.get(url)228 self.assertEqual(r.status_code, 200)229230 def test_basicauth_with_netrc(self):231 auth = ('user', 'pass')232 wrong_auth = ('wronguser', 'wrongpass')233 url = httpbin('basic-auth', 'user', 'pass')234235 def get_netrc_auth_mock(url):236 return auth237 requests.sessions.get_netrc_auth = get_netrc_auth_mock238239 # Should use netrc and work.240 r = requests.get(url)241 self.assertEqual(r.status_code, 200)242243 # Given auth should override and fail.244 r = requests.get(url, auth=wrong_auth)245 self.assertEqual(r.status_code, 401)246247 s = requests.session()248 249 # Should use netrc and work.250 r = s.get(url)251 self.assertEqual(r.status_code, 200)252253 # Given auth should override and fail.254 s.auth = wrong_auth255 r = s.get(url)256 self.assertEqual(r.status_code, 401)257258 def test_DIGEST_HTTP_200_OK_GET(self):259260 auth = HTTPDigestAuth('user', 'pass')261 url = httpbin('digest-auth', 'auth', 'user', 'pass')262263 r = requests.get(url, auth=auth)264 self.assertEqual(r.status_code, 200)265266 r = requests.get(url)267 self.assertEqual(r.status_code, 401)268269 s = requests.session()270 s.auth = auth271 r = s.get(url)272 self.assertEqual(r.status_code, 200)273274 def test_DIGEST_STREAM(self):275276 auth = HTTPDigestAuth('user', 'pass')277 url = httpbin('digest-auth', 'auth', 'user', 'pass')278279 r = requests.get(url, auth=auth, stream=True)280 self.assertNotEqual(r.raw.read(), b'')281282 r = requests.get(url, auth=auth, stream=False)283 self.assertEqual(r.raw.read(), b'')284285286 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):287288 auth = HTTPDigestAuth('user', 'wrongpass')289 url = httpbin('digest-auth', 'auth', 'user', 'pass')290291 r = requests.get(url, auth=auth)292 self.assertEqual(r.status_code, 401)293294 r = requests.get(url)295 self.assertEqual(r.status_code, 401)296297 s = requests.session()298 s.auth = auth299 r = s.get(url)300 self.assertEqual(r.status_code, 401)301302 def test_POSTBIN_GET_POST_FILES(self):303304 url = httpbin('post')305 post1 = requests.post(url).raise_for_status()306307 post1 = requests.post(url, data={'some': 'data'})308 self.assertEqual(post1.status_code, 200)309310 with open('requirements.txt') as f:311 post2 = requests.post(url, files={'some': f})312 self.assertEqual(post2.status_code, 200)313314 post4 = requests.post(url, data='[{"some": "json"}]')315 self.assertEqual(post4.status_code, 200)316317 try:318 requests.post(url, files=['bad file data'])319 except ValueError:320 pass321322 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):323324 url = httpbin('post')325 post1 = requests.post(url).raise_for_status()326327 post1 = requests.post(url, data={'some': 'data'})328 self.assertEqual(post1.status_code, 200)329330 with open('requirements.txt') as f:331 post2 = requests.post(url, data={'some': 'data'}, files={'some': f})332 self.assertEqual(post2.status_code, 200)333334 post4 = requests.post(url, data='[{"some": "json"}]')335 self.assertEqual(post4.status_code, 200)336337 try:338 requests.post(url, files=['bad file data'])339 except ValueError:340 pass341342 def test_request_ok_set(self):343 r = requests.get(httpbin('status', '404'))344 self.assertEqual(r.ok, False)345346 def test_status_raising(self):347 r = requests.get(httpbin('status', '404'))348 self.assertRaises(requests.exceptions.HTTPError, r.raise_for_status)349350 r = requests.get(httpbin('status', '500'))351 self.assertFalse(r.ok)352353 def test_decompress_gzip(self):354 r = requests.get(httpbin('gzip'))355 r.content.decode('ascii')356357 def test_unicode_get(self):358 url = httpbin('/get')359 requests.get(url, params={'foo': 'føø'})360 requests.get(url, params={'føø': 'føø'})361 requests.get(url, params={'føø': 'føø'})362 requests.get(url, params={'foo': 'foo'})363 requests.get(httpbin('ø'), params={'foo': 'foo'})364365 def test_unicode_header_name(self):366 requests.put(httpbin('put'), headers={str('Content-Type'): 'application/octet-stream'}, data='\xff') # compat.str is unicode.367368 def test_urlencoded_get_query_multivalued_param(self):369370 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))371 self.assertEqual(r.status_code, 200)372 self.assertEqual(r.url, httpbin('get?test=foo&test=baz'))373374 def test_different_encodings_dont_break_post(self):375 r = requests.post(httpbin('post'),376 data={'stuff': json.dumps({'a': 123})},377 params={'blah': 'asdf1234'},378 files={'file': ('test_requests.py', open(__file__, 'rb'))})379 self.assertEqual(r.status_code, 200)380381 def test_unicode_multipart_post(self):382 r = requests.post(httpbin('post'),383 data={'stuff': u'ëlïxr'},384 files={'file': ('test_requests.py', open(__file__, 'rb'))})385 self.assertEqual(r.status_code, 200)386387 r = requests.post(httpbin('post'),388 data={'stuff': u'ëlïxr'.encode('utf-8')},389 files={'file': ('test_requests.py', open(__file__, 'rb'))})390 self.assertEqual(r.status_code, 200)391392 r = requests.post(httpbin('post'),393 data={'stuff': 'elixr'},394 files={'file': ('test_requests.py', open(__file__, 'rb'))})395 self.assertEqual(r.status_code, 200)396397 r = requests.post(httpbin('post'),398 data={'stuff': 'elixr'.encode('utf-8')},399 files={'file': ('test_requests.py', open(__file__, 'rb'))})400 self.assertEqual(r.status_code, 200)401402 def test_unicode_multipart_post_fieldnames(self):403 filename = os.path.splitext(__file__)[0] + '.py'404 r = requests.Request(method='POST',405 url=httpbin('post'),406 data={'stuff'.encode('utf-8'): 'elixr'},407 files={'file': ('test_requests.py',408 open(filename, 'rb'))})409 prep = r.prepare()410 self.assertTrue(b'name="stuff"' in prep.body)411 self.assertFalse(b'name="b\'stuff\'"' in prep.body)412413 def test_custom_content_type(self):414 r = requests.post(httpbin('post'),415 data={'stuff': json.dumps({'a': 123})},416 files={'file1': ('test_requests.py', open(__file__, 'rb')),417 'file2': ('test_requests', open(__file__, 'rb'),418 'text/py-content-type')})419 self.assertEqual(r.status_code, 200)420 self.assertTrue(b"text/py-content-type" in r.request.body)421422 def test_hook_receives_request_arguments(self):423 def hook(resp, **kwargs):424 assert resp is not None425 assert kwargs != {}426427 requests.Request('GET', HTTPBIN, hooks={'response': hook})428429 def test_prepared_request_hook(self):430 def hook(resp, **kwargs):431 resp.hook_working = True432 return resp433434 req = requests.Request('GET', HTTPBIN, hooks={'response': hook})435 prep = req.prepare()436437 s = requests.Session()438 s.proxies = getproxies()439 resp = s.send(prep)440441 self.assertTrue(hasattr(resp, 'hook_working'))442443 def test_prepared_from_session(self):444 class DummyAuth(requests.auth.AuthBase):445 def __call__(self, r):446 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'447 return r448449 req = requests.Request('GET', httpbin('headers'))450 self.assertEqual(req.auth, None)451452 s = requests.Session()453 s.auth = DummyAuth()454455 prep = s.prepare_request(req)456 resp = s.send(prep)457458 self.assertTrue(resp.json()['headers']['Dummy-Auth-Test'], 'dummy-auth-test-ok')459460 def test_links(self):461 r = requests.Response()462 r.headers = {463 'cache-control': 'public, max-age=60, s-maxage=60',464 'connection': 'keep-alive',465 'content-encoding': 'gzip',466 'content-type': 'application/json; charset=utf-8',467 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',468 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',469 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',470 'link': ('<https://api.github.com/users/kennethreitz/repos?'471 'page=2&per_page=10>; rel="next", <https://api.github.'472 'com/users/kennethreitz/repos?page=7&per_page=10>; '473 ' rel="last"'),474 'server': 'GitHub.com',475 'status': '200 OK',476 'vary': 'Accept',477 'x-content-type-options': 'nosniff',478 'x-github-media-type': 'github.beta',479 'x-ratelimit-limit': '60',480 'x-ratelimit-remaining': '57'481 }482 self.assertEqual(r.links['next']['rel'], 'next')483484 def test_cookie_parameters(self):485 key = 'some_cookie'486 value = 'some_value'487 secure = True488 domain = 'test.com'489 rest = {'HttpOnly': True}490491 jar = requests.cookies.RequestsCookieJar()492 jar.set(key, value, secure=secure, domain=domain, rest=rest)493494 self.assertEqual(len(jar), 1)495 self.assertTrue('some_cookie' in jar)496497 cookie = list(jar)[0]498 self.assertEqual(cookie.secure, secure)499 self.assertEqual(cookie.domain, domain)500 self.assertEqual(cookie._rest['HttpOnly'], rest['HttpOnly'])501502 def test_time_elapsed_blank(self):503 r = requests.get(httpbin('get'))504 td = r.elapsed505 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)506 * 10**6) / 10**6)507 self.assertTrue(total_seconds > 0.0)508509 def test_response_is_iterable(self):510 r = requests.Response()511 io = StringIO.StringIO('abc')512 read_ = io.read513514 def read_mock(amt, decode_content=None):515 return read_(amt)516 setattr(io, 'read', read_mock)517 r.raw = io518 self.assertTrue(next(iter(r)))519 io.close()520521 def test_get_auth_from_url(self):522 url = 'http://user:pass@complex.url.com/path?query=yes'523 self.assertEqual(('user', 'pass'),524 requests.utils.get_auth_from_url(url))525526 def test_cannot_send_unprepared_requests(self):527 r = requests.Request(url=HTTPBIN)528 self.assertRaises(ValueError, requests.Session().send, r)529530 def test_http_error(self):531 error = requests.exceptions.HTTPError()532 self.assertEqual(error.response, None)533 response = requests.Response()534 error = requests.exceptions.HTTPError(response=response)535 self.assertEqual(error.response, response)536 error = requests.exceptions.HTTPError('message', response=response)537 self.assertEqual(str(error), 'message')538 self.assertEqual(error.response, response)539540 def test_session_pickling(self):541 r = requests.Request('GET', httpbin('get'))542 s = requests.Session()543544 s = pickle.loads(pickle.dumps(s))545 s.proxies = getproxies()546547 r = s.send(r.prepare())548 self.assertEqual(r.status_code, 200)549550 def test_fixes_1329(self):551 """552 Ensure that header updates are done case-insensitively.553 """554 s = requests.Session()555 s.headers.update({'ACCEPT': 'BOGUS'})556 s.headers.update({'accept': 'application/json'})557 r = s.get(httpbin('get'))558 headers = r.request.headers559 # ASCII encode because of key comparison changes in py3560 self.assertEqual(561 headers['accept'.encode('ascii')],562 'application/json'563 )564 self.assertEqual(565 headers['Accept'.encode('ascii')],566 'application/json'567 )568 self.assertEqual(569 headers['ACCEPT'.encode('ascii')],570 'application/json'571 )572573 def test_uppercase_scheme_redirect(self):574 parts = urlparse(httpbin('html'))575 url = "HTTP://" + parts.netloc + parts.path576 r = requests.get(httpbin('redirect-to'), params={'url': url})577 self.assertEqual(r.status_code, 200)578 self.assertEqual(r.url.lower(), url.lower())579580 def test_transport_adapter_ordering(self):581 s = requests.Session()582 order = ['https://', 'http://']583 self.assertEqual(order, list(s.adapters))584 s.mount('http://git', HTTPAdapter())585 s.mount('http://github', HTTPAdapter())586 s.mount('http://github.com', HTTPAdapter())587 s.mount('http://github.com/about/', HTTPAdapter())588 order = [589 'http://github.com/about/',590 'http://github.com',591 'http://github',592 'http://git',593 'https://',594 'http://',595 ]596 self.assertEqual(order, list(s.adapters))597 s.mount('http://gittip', HTTPAdapter())598 s.mount('http://gittip.com', HTTPAdapter())599 s.mount('http://gittip.com/about/', HTTPAdapter())600 order = [601 'http://github.com/about/',602 'http://gittip.com/about/',603 'http://github.com',604 'http://gittip.com',605 'http://github',606 'http://gittip',607 'http://git',608 'https://',609 'http://',610 ]611 self.assertEqual(order, list(s.adapters))612 s2 = requests.Session()613 s2.adapters = {'http://': HTTPAdapter()}614 s2.mount('https://', HTTPAdapter())615 self.assertTrue('http://' in s2.adapters)616 self.assertTrue('https://' in s2.adapters)617618 def test_header_remove_is_case_insensitive(self):619 # From issue #1321620 s = requests.Session()621 s.headers['foo'] = 'bar'622 r = s.get(httpbin('get'), headers={'FOO': None})623 assert 'foo' not in r.request.headers624625 def test_params_are_merged_case_sensitive(self):626 s = requests.Session()627 s.params['foo'] = 'bar'628 r = s.get(httpbin('get'), params={'FOO': 'bar'})629 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}630631632 def test_long_authinfo_in_url(self):633 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(634 'E8A3BE87-9E3F-4620-8858-95478E385B5B',635 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',636 'exactly-------------sixty-----------three------------characters',637 )638 r = requests.Request('GET', url).prepare()639 self.assertEqual(r.url, url)640641642class TestContentEncodingDetection(unittest.TestCase):643644 def test_none(self):645 encodings = requests.utils.get_encodings_from_content('')646 self.assertEqual(len(encodings), 0)647648 def test_html_charset(self):649 """HTML5 meta charset attribute"""650 content = '<meta charset="UTF-8">'651 encodings = requests.utils.get_encodings_from_content(content)652 self.assertEqual(len(encodings), 1)653 self.assertEqual(encodings[0], 'UTF-8')654655 def test_html4_pragma(self):656 """HTML4 pragma directive"""657 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'658 encodings = requests.utils.get_encodings_from_content(content)659 self.assertEqual(len(encodings), 1)660 self.assertEqual(encodings[0], 'UTF-8')661662 def test_xhtml_pragma(self):663 """XHTML 1.x served with text/html MIME type"""664 content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'665 encodings = requests.utils.get_encodings_from_content(content)666 self.assertEqual(len(encodings), 1)667 self.assertEqual(encodings[0], 'UTF-8')668669 def test_xml(self):670 """XHTML 1.x served as XML"""671 content = '<?xml version="1.0" encoding="UTF-8"?>'672 encodings = requests.utils.get_encodings_from_content(content)673 self.assertEqual(len(encodings), 1)674 self.assertEqual(encodings[0], 'UTF-8')675676 def test_precedence(self):677 content = '''678 <?xml version="1.0" encoding="XML"?>679 <meta charset="HTML5">680 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />681 '''.strip()682 encodings = requests.utils.get_encodings_from_content(content)683 self.assertEqual(encodings, ['HTML5', 'HTML4', 'XML'])684685686class TestCaseInsensitiveDict(unittest.TestCase):687688 def test_mapping_init(self):689 cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})690 self.assertEqual(len(cid), 2)691 self.assertTrue('foo' in cid)692 self.assertTrue('bar' in cid)693694 def test_iterable_init(self):695 cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])696 self.assertEqual(len(cid), 2)697 self.assertTrue('foo' in cid)698 self.assertTrue('bar' in cid)699700 def test_kwargs_init(self):701 cid = CaseInsensitiveDict(FOO='foo', BAr='bar')702 self.assertEqual(len(cid), 2)703 self.assertTrue('foo' in cid)704 self.assertTrue('bar' in cid)705706 def test_docstring_example(self):707 cid = CaseInsensitiveDict()708 cid['Accept'] = 'application/json'709 self.assertEqual(cid['aCCEPT'], 'application/json')710 self.assertEqual(list(cid), ['Accept'])711712 def test_len(self):713 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})714 cid['A'] = 'a'715 self.assertEqual(len(cid), 2)716717 def test_getitem(self):718 cid = CaseInsensitiveDict({'Spam': 'blueval'})719 self.assertEqual(cid['spam'], 'blueval')720 self.assertEqual(cid['SPAM'], 'blueval')721722 def test_fixes_649(self):723 """__setitem__ should behave case-insensitively."""724 cid = CaseInsensitiveDict()725 cid['spam'] = 'oneval'726 cid['Spam'] = 'twoval'727 cid['sPAM'] = 'redval'728 cid['SPAM'] = 'blueval'729 self.assertEqual(cid['spam'], 'blueval')730 self.assertEqual(cid['SPAM'], 'blueval')731 self.assertEqual(list(cid.keys()), ['SPAM'])732733 def test_delitem(self):734 cid = CaseInsensitiveDict()735 cid['Spam'] = 'someval'736 del cid['sPam']737 self.assertFalse('spam' in cid)738 self.assertEqual(len(cid), 0)739740 def test_contains(self):741 cid = CaseInsensitiveDict()742 cid['Spam'] = 'someval'743 self.assertTrue('Spam' in cid)744 self.assertTrue('spam' in cid)745 self.assertTrue('SPAM' in cid)746 self.assertTrue('sPam' in cid)747 self.assertFalse('notspam' in cid)748749 def test_get(self):750 cid = CaseInsensitiveDict()751 cid['spam'] = 'oneval'752 cid['SPAM'] = 'blueval'753 self.assertEqual(cid.get('spam'), 'blueval')754 self.assertEqual(cid.get('SPAM'), 'blueval')755 self.assertEqual(cid.get('sPam'), 'blueval')756 self.assertEqual(cid.get('notspam', 'default'), 'default')757758 def test_update(self):759 cid = CaseInsensitiveDict()760 cid['spam'] = 'blueval'761 cid.update({'sPam': 'notblueval'})762 self.assertEqual(cid['spam'], 'notblueval')763 cid = CaseInsensitiveDict({'Foo': 'foo','BAr': 'bar'})764 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})765 self.assertEqual(len(cid), 2)766 self.assertEqual(cid['foo'], 'anotherfoo')767 self.assertEqual(cid['bar'], 'anotherbar')768769 def test_update_retains_unchanged(self):770 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})771 cid.update({'foo': 'newfoo'})772 self.assertEquals(cid['bar'], 'bar')773774 def test_iter(self):775 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})776 keys = frozenset(['Spam', 'Eggs'])777 self.assertEqual(frozenset(iter(cid)), keys)778779 def test_equality(self):780 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})781 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})782 self.assertEqual(cid, othercid)783 del othercid['spam']784 self.assertNotEqual(cid, othercid)785 self.assertEqual(cid, {'spam': 'blueval', 'eggs': 'redval'})786787 def test_setdefault(self):788 cid = CaseInsensitiveDict({'Spam': 'blueval'})789 self.assertEqual(790 cid.setdefault('spam', 'notblueval'),791 'blueval'792 )793 self.assertEqual(794 cid.setdefault('notspam', 'notblueval'),795 'notblueval'796 )797798 def test_lower_items(self):799 cid = CaseInsensitiveDict({800 'Accept': 'application/json',801 'user-Agent': 'requests',802 })803 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())804 lowerkeyset = frozenset(['accept', 'user-agent'])805 self.assertEqual(keyset, lowerkeyset)806807 def test_preserve_key_case(self):808 cid = CaseInsensitiveDict({809 'Accept': 'application/json',810 'user-Agent': 'requests',811 })812 keyset = frozenset(['Accept', 'user-Agent'])813 self.assertEqual(frozenset(i[0] for i in cid.items()), keyset)814 self.assertEqual(frozenset(cid.keys()), keyset)815 self.assertEqual(frozenset(cid), keyset)816817 def test_preserve_last_key_case(self):818 cid = CaseInsensitiveDict({819 'Accept': 'application/json',820 'user-Agent': 'requests',821 })822 cid.update({'ACCEPT': 'application/json'})823 cid['USER-AGENT'] = 'requests'824 keyset = frozenset(['ACCEPT', 'USER-AGENT'])825 self.assertEqual(frozenset(i[0] for i in cid.items()), keyset)826 self.assertEqual(frozenset(cid.keys()), keyset)827 self.assertEqual(frozenset(cid), keyset)828829830if __name__ == '__main__':831 unittest.main()