Skip to content
Myr

Added tests module.

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

authored by Dmitry Dygalo · committed by Dmitry Dygalo · parent 6143b7e · Browse files · 7 files+1755 added−1727 removed
This commit

State

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

Diff stats

7 files+1755 added−1727 removed

  • tests:+1753 added−0 removed
  • other:+2 added−1727 removed

7 files+1755 added−1727 removed

added:tests/__init__.py+1 added
1# coding: utf-8
added:tests/compat.py+20 added
1# coding: utf-82from requests.compat import is_py3345try:6 import StringIO7except ImportError:8 import io as StringIO910try:11 from cStringIO import StringIO as cStringIO12except ImportError:13 cStringIO = None1415if is_py3:16 def u(s):17 return s18else:19 def u(s):20 return s.decode('unicode-escape')
added:tests/conftest.py+23 added
1# coding: utf-82import pytest3from requests.compat import urljoin456def prepare_url(value):7 # Issue #1483: Make sure the URL always has a trailing slash8 httpbin_url = value.url.rstrip('/') + '/'910 def inner(*suffix):11 return urljoin(httpbin_url, '/'.join(suffix))1213 return inner141516@pytest.fixture17def httpbin(httpbin):18 return prepare_url(httpbin)192021@pytest.fixture22def httpbin_secure(httpbin_secure):23 return prepare_url(httpbin_secure)
added:tests/test_requests.py+1467 added
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import collections11import contextlib1213import io14import requests15import pytest16from requests.adapters import HTTPAdapter17from requests.auth import HTTPDigestAuth, _basic_auth_str18from requests.compat import (19 Morsel, cookielib, getproxies, str, urlparse,20 builtin_str, OrderedDict)21from requests.cookies import cookiejar_from_dict, morsel_to_cookie22from requests.exceptions import (23 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,24 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects)25from requests.models import PreparedRequest26from requests.structures import CaseInsensitiveDict27from requests.sessions import SessionRedirectMixin28from requests.models import urlencode29from requests.hooks import default_hooks3031from .compat import StringIO, u3233# Requests to this URL should always fail with a connection timeout (nothing34# listening on that port)35TARPIT = "http://10.255.255.1"363738class TestRequests:3940 def test_entry_points(self):4142 requests.session43 requests.session().get44 requests.session().head45 requests.get46 requests.head47 requests.put48 requests.patch49 requests.post5051 @pytest.mark.parametrize('exception, url',52 (53 (MissingSchema, 'hiwpefhipowhefopw'),54 (InvalidSchema, 'localhost:3128'),55 (InvalidSchema, 'localhost.localdomain:3128/'),56 (InvalidSchema, '10.122.1.1:3128/'),57 (InvalidURL, 'http://'),58 )59 )60 def test_invalid_url(self, exception, url):61 with pytest.raises(exception):62 requests.get(url)6364 def test_basic_building(self):65 req = requests.Request()66 req.url = 'http://kennethreitz.org/'67 req.data = {'life': '42'}6869 pr = req.prepare()70 assert pr.url == req.url71 assert pr.body == 'life=42'7273 @pytest.mark.parametrize('method', ('GET', 'HEAD'))74 def test_no_content_length(self, httpbin, method):75 req = requests.Request(method, httpbin(method.lower())).prepare()76 assert 'Content-Length' not in req.headers7778 def test_override_content_length(self, httpbin):79 headers = {80 'Content-Length': 'not zero'81 }82 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()83 assert 'Content-Length' in r.headers84 assert r.headers['Content-Length'] == 'not zero'8586 def test_path_is_not_double_encoded(self):87 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()8889 assert request.path_url == '/get/test%20case'9091 @pytest.mark.parametrize('url, expected',92 (93 ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),94 ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')95 )96 )97 def test_params_are_added_before_fragment(self, url, expected):98 request = requests.Request('GET', url, params={"a": "b"}).prepare()99 assert request.url == expected100101 def test_params_original_order_is_preserved_by_default(self):102 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))103 session = requests.Session()104 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)105 prep = session.prepare_request(request)106 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'107108 def test_params_bytes_are_encoded(self):109 request = requests.Request('GET', 'http://example.com',110 params=b'test=foo').prepare()111 assert request.url == 'http://example.com/?test=foo'112113 def test_binary_put(self):114 request = requests.Request('PUT', 'http://example.com',115 data=u"ööö".encode("utf-8")).prepare()116 assert isinstance(request.body, bytes)117118 @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))119 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):120 s = requests.Session()121 s.proxies = getproxies()122 parts = urlparse(httpbin('get'))123 url = scheme + parts.netloc + parts.path124 r = requests.Request('GET', url)125 r = s.send(r.prepare())126 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)127128 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):129 r = requests.Request('GET', httpbin('get'))130 s = requests.Session()131 s.proxies = getproxies()132133 r = s.send(r.prepare())134135 assert r.status_code == 200136137 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):138 r = requests.get(httpbin('redirect', '1'))139 assert r.status_code == 200140 assert r.history[0].status_code == 302141 assert r.history[0].is_redirect142143 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):144 try:145 requests.get(httpbin('relative-redirect', '50'))146 except TooManyRedirects as e:147 url = httpbin('relative-redirect', '20')148 assert e.request.url == url149 assert e.response.url == url150 assert len(e.response.history) == 30151 else:152 pytest.fail('Expected redirect to raise TooManyRedirects but it did not')153154 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):155 s = requests.session()156 s.max_redirects = 5157 try:158 s.get(httpbin('relative-redirect', '50'))159 except TooManyRedirects as e:160 url = httpbin('relative-redirect', '45')161 assert e.request.url == url162 assert e.response.url == url163 assert len(e.response.history) == 5164 else:165 pytest.fail('Expected custom max number of redirects to be respected but was not')166167 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):168 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})169 # self.assertEqual(r.status_code, 200)170171 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):172 heads = {'User-agent': 'Mozilla/5.0'}173174 r = requests.get(httpbin('user-agent'), headers=heads)175176 assert heads['User-agent'] in r.text177 assert r.status_code == 200178179 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):180 heads = {'User-agent': 'Mozilla/5.0'}181182 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)183 assert r.status_code == 200184185 def test_set_cookie_on_301(self, httpbin):186 s = requests.session()187 url = httpbin('cookies/set?foo=bar')188 s.get(url)189 assert s.cookies['foo'] == 'bar'190191 def test_cookie_sent_on_redirect(self, httpbin):192 s = requests.session()193 s.get(httpbin('cookies/set?foo=bar'))194 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')195 assert 'Cookie' in r.json()['headers']196197 def test_cookie_removed_on_expire(self, httpbin):198 s = requests.session()199 s.get(httpbin('cookies/set?foo=bar'))200 assert s.cookies['foo'] == 'bar'201 s.get(202 httpbin('response-headers'),203 params={204 'Set-Cookie':205 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'206 }207 )208 assert 'foo' not in s.cookies209210 def test_cookie_quote_wrapped(self, httpbin):211 s = requests.session()212 s.get(httpbin('cookies/set?foo="bar:baz"'))213 assert s.cookies['foo'] == '"bar:baz"'214215 def test_cookie_persists_via_api(self, httpbin):216 s = requests.session()217 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})218 assert 'foo' in r.request.headers['Cookie']219 assert 'foo' in r.history[0].request.headers['Cookie']220221 def test_request_cookie_overrides_session_cookie(self, httpbin):222 s = requests.session()223 s.cookies['foo'] = 'bar'224 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})225 assert r.json()['cookies']['foo'] == 'baz'226 # Session cookie should not be modified227 assert s.cookies['foo'] == 'bar'228229 def test_request_cookies_not_persisted(self, httpbin):230 s = requests.session()231 s.get(httpbin('cookies'), cookies={'foo': 'baz'})232 # Sending a request with cookies should not add cookies to the session233 assert not s.cookies234235 def test_generic_cookiejar_works(self, httpbin):236 cj = cookielib.CookieJar()237 cookiejar_from_dict({'foo': 'bar'}, cj)238 s = requests.session()239 s.cookies = cj240 r = s.get(httpbin('cookies'))241 # Make sure the cookie was sent242 assert r.json()['cookies']['foo'] == 'bar'243 # Make sure the session cj is still the custom one244 assert s.cookies is cj245246 def test_param_cookiejar_works(self, httpbin):247 cj = cookielib.CookieJar()248 cookiejar_from_dict({'foo': 'bar'}, cj)249 s = requests.session()250 r = s.get(httpbin('cookies'), cookies=cj)251 # Make sure the cookie was sent252 assert r.json()['cookies']['foo'] == 'bar'253254 def test_requests_in_history_are_not_overridden(self, httpbin):255 resp = requests.get(httpbin('redirect/3'))256 urls = [r.url for r in resp.history]257 req_urls = [r.request.url for r in resp.history]258 assert urls == req_urls259260 def test_history_is_always_a_list(self, httpbin):261 """Show that even with redirects, Response.history is always a list."""262 resp = requests.get(httpbin('get'))263 assert isinstance(resp.history, list)264 resp = requests.get(httpbin('redirect/1'))265 assert isinstance(resp.history, list)266 assert not isinstance(resp.history, tuple)267268 def test_headers_on_session_with_None_are_not_sent(self, httpbin):269 """Do not send headers in Session.headers with None values."""270 ses = requests.Session()271 ses.headers['Accept-Encoding'] = None272 req = requests.Request('GET', httpbin('get'))273 prep = ses.prepare_request(req)274 assert 'Accept-Encoding' not in prep.headers275276 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))277 def test_user_agent_transfers(self, httpbin, key):278279 heads = {280 key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'281 }282283 r = requests.get(httpbin('user-agent'), headers=heads)284 assert heads[key] in r.text285286 def test_HTTP_200_OK_HEAD(self, httpbin):287 r = requests.head(httpbin('get'))288 assert r.status_code == 200289290 def test_HTTP_200_OK_PUT(self, httpbin):291 r = requests.put(httpbin('put'))292 assert r.status_code == 200293294 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):295 auth = ('user', 'pass')296 url = httpbin('basic-auth', 'user', 'pass')297298 r = requests.get(url, auth=auth)299 assert r.status_code == 200300301 r = requests.get(url)302 assert r.status_code == 401303304 s = requests.session()305 s.auth = auth306 r = s.get(url)307 assert r.status_code == 200308309 @pytest.mark.parametrize(310 'url, exception', (311 # Connecting to an unknown domain should raise a ConnectionError312 ('http://doesnotexist.google.com', ConnectionError),313 # Connecting to an invalid port should raise a ConnectionError314 ('http://localhost:1', ConnectionError),315 # Inputing a URL that cannot be parsed should raise an InvalidURL error316 ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)317 )318 )319 def test_errors(self, url, exception):320 with pytest.raises(exception):321 requests.get(url, timeout=1)322323 def test_basicauth_with_netrc(self, httpbin):324 auth = ('user', 'pass')325 wrong_auth = ('wronguser', 'wrongpass')326 url = httpbin('basic-auth', 'user', 'pass')327328 old_auth = requests.sessions.get_netrc_auth329330 try:331 def get_netrc_auth_mock(url):332 return auth333 requests.sessions.get_netrc_auth = get_netrc_auth_mock334335 # Should use netrc and work.336 r = requests.get(url)337 assert r.status_code == 200338339 # Given auth should override and fail.340 r = requests.get(url, auth=wrong_auth)341 assert r.status_code == 401342343 s = requests.session()344345 # Should use netrc and work.346 r = s.get(url)347 assert r.status_code == 200348349 # Given auth should override and fail.350 s.auth = wrong_auth351 r = s.get(url)352 assert r.status_code == 401353 finally:354 requests.sessions.get_netrc_auth = old_auth355356 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):357358 auth = HTTPDigestAuth('user', 'pass')359 url = httpbin('digest-auth', 'auth', 'user', 'pass')360361 r = requests.get(url, auth=auth)362 assert r.status_code == 200363364 r = requests.get(url)365 assert r.status_code == 401366367 s = requests.session()368 s.auth = HTTPDigestAuth('user', 'pass')369 r = s.get(url)370 assert r.status_code == 200371372 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):373 url = httpbin('digest-auth', 'auth', 'user', 'pass')374 auth = HTTPDigestAuth('user', 'pass')375 r = requests.get(url)376 assert r.cookies['fake'] == 'fake_value'377378 r = requests.get(url, auth=auth)379 assert r.status_code == 200380381 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):382 url = httpbin('digest-auth', 'auth', 'user', 'pass')383 auth = HTTPDigestAuth('user', 'pass')384 s = requests.Session()385 s.get(url, auth=auth)386 assert s.cookies['fake'] == 'fake_value'387388 def test_DIGEST_STREAM(self, httpbin):389390 auth = HTTPDigestAuth('user', 'pass')391 url = httpbin('digest-auth', 'auth', 'user', 'pass')392393 r = requests.get(url, auth=auth, stream=True)394 assert r.raw.read() != b''395396 r = requests.get(url, auth=auth, stream=False)397 assert r.raw.read() == b''398399 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):400401 auth = HTTPDigestAuth('user', 'wrongpass')402 url = httpbin('digest-auth', 'auth', 'user', 'pass')403404 r = requests.get(url, auth=auth)405 assert r.status_code == 401406407 r = requests.get(url)408 assert r.status_code == 401409410 s = requests.session()411 s.auth = auth412 r = s.get(url)413 assert r.status_code == 401414415 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):416417 auth = HTTPDigestAuth('user', 'pass')418 url = httpbin('digest-auth', 'auth', 'user', 'pass')419420 r = requests.get(url, auth=auth)421 assert '"auth"' in r.request.headers['Authorization']422423 def test_POSTBIN_GET_POST_FILES(self, httpbin):424425 url = httpbin('post')426 requests.post(url).raise_for_status()427428 post1 = requests.post(url, data={'some': 'data'})429 assert post1.status_code == 200430431 with open('requirements.txt') as f:432 post2 = requests.post(url, files={'some': f})433 assert post2.status_code == 200434435 post4 = requests.post(url, data='[{"some": "json"}]')436 assert post4.status_code == 200437438 with pytest.raises(ValueError):439 requests.post(url, files=['bad file data'])440441 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):442443 url = httpbin('post')444 requests.post(url).raise_for_status()445446 post1 = requests.post(url, data={'some': 'data'})447 assert post1.status_code == 200448449 with open('requirements.txt') as f:450 post2 = requests.post(url,451 data={'some': 'data'}, files={'some': f})452 assert post2.status_code == 200453454 post4 = requests.post(url, data='[{"some": "json"}]')455 assert post4.status_code == 200456457 with pytest.raises(ValueError):458 requests.post(url, files=['bad file data'])459460 def test_conflicting_post_params(self, httpbin):461 url = httpbin('post')462 with open('requirements.txt') as f:463 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")464 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")465466 def test_request_ok_set(self, httpbin):467 r = requests.get(httpbin('status', '404'))468 assert not r.ok469470 def test_status_raising(self, httpbin):471 r = requests.get(httpbin('status', '404'))472 with pytest.raises(requests.exceptions.HTTPError):473 r.raise_for_status()474475 r = requests.get(httpbin('status', '500'))476 assert not r.ok477478 def test_decompress_gzip(self, httpbin):479 r = requests.get(httpbin('gzip'))480 r.content.decode('ascii')481482 @pytest.mark.parametrize(483 'url, params',484 (485 ('/get', {'foo': 'føø'}),486 ('/get', {'føø': 'føø'}),487 ('/get', {'føø': 'føø'}),488 ('/get', {'foo': 'foo'}),489 ('ø', {'foo': 'foo'}),490 )491 )492 def test_unicode_get(self, httpbin, url, params):493 requests.get(httpbin(url), params=params)494495 def test_unicode_header_name(self, httpbin):496 requests.put(497 httpbin('put'),498 headers={str('Content-Type'): 'application/octet-stream'},499 data='\xff') # compat.str is unicode.500501 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):502 requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)503504 def test_urlencoded_get_query_multivalued_param(self, httpbin):505506 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))507 assert r.status_code == 200508 assert r.url == httpbin('get?test=foo&test=baz')509510 def test_different_encodings_dont_break_post(self, httpbin):511 r = requests.post(httpbin('post'),512 data={'stuff': json.dumps({'a': 123})},513 params={'blah': 'asdf1234'},514 files={'file': ('test_requests.py', open(__file__, 'rb'))})515 assert r.status_code == 200516517 @pytest.mark.parametrize(518 'data', (519 {'stuff': u('ëlïxr')},520 {'stuff': u('ëlïxr').encode('utf-8')},521 {'stuff': 'elixr'},522 {'stuff': 'elixr'.encode('utf-8')},523 )524 )525 def test_unicode_multipart_post(self, httpbin, data):526 r = requests.post(httpbin('post'),527 data=data,528 files={'file': ('test_requests.py', open(__file__, 'rb'))})529 assert r.status_code == 200530531 def test_unicode_multipart_post_fieldnames(self, httpbin):532 filename = os.path.splitext(__file__)[0] + '.py'533 r = requests.Request(method='POST',534 url=httpbin('post'),535 data={'stuff'.encode('utf-8'): 'elixr'},536 files={'file': ('test_requests.py',537 open(filename, 'rb'))})538 prep = r.prepare()539 assert b'name="stuff"' in prep.body540 assert b'name="b\'stuff\'"' not in prep.body541542 def test_unicode_method_name(self, httpbin):543 files = {'file': open(__file__, 'rb')}544 r = requests.request(545 method=u('POST'), url=httpbin('post'), files=files)546 assert r.status_code == 200547548 def test_unicode_method_name_with_request_object(self, httpbin):549 files = {'file': open(__file__, 'rb')}550 s = requests.Session()551 req = requests.Request(u("POST"), httpbin('post'), files=files)552 prep = s.prepare_request(req)553 assert isinstance(prep.method, builtin_str)554 assert prep.method == "POST"555556 resp = s.send(prep)557 assert resp.status_code == 200558559 def test_custom_content_type(self, httpbin):560 r = requests.post(561 httpbin('post'),562 data={'stuff': json.dumps({'a': 123})},563 files={'file1': ('test_requests.py', open(__file__, 'rb')),564 'file2': ('test_requests', open(__file__, 'rb'),565 'text/py-content-type')})566 assert r.status_code == 200567 assert b"text/py-content-type" in r.request.body568569 def test_hook_receives_request_arguments(self, httpbin):570 def hook(resp, **kwargs):571 assert resp is not None572 assert kwargs != {}573574 s = requests.Session()575 r = requests.Request('GET', httpbin(), hooks={'response': hook})576 prep = s.prepare_request(r)577 s.send(prep)578579 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):580 hook = lambda x, *args, **kwargs: x581 s = requests.Session()582 s.hooks['response'].append(hook)583 r = requests.Request('GET', httpbin())584 prep = s.prepare_request(r)585 assert prep.hooks['response'] != []586 assert prep.hooks['response'] == [hook]587588 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):589 hook1 = lambda x, *args, **kwargs: x590 hook2 = lambda x, *args, **kwargs: x591 assert hook1 is not hook2592 s = requests.Session()593 s.hooks['response'].append(hook2)594 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})595 prep = s.prepare_request(r)596 assert prep.hooks['response'] == [hook1]597598 def test_prepared_request_hook(self, httpbin):599 def hook(resp, **kwargs):600 resp.hook_working = True601 return resp602603 req = requests.Request('GET', httpbin(), hooks={'response': hook})604 prep = req.prepare()605606 s = requests.Session()607 s.proxies = getproxies()608 resp = s.send(prep)609610 assert hasattr(resp, 'hook_working')611612 def test_prepared_from_session(self, httpbin):613 class DummyAuth(requests.auth.AuthBase):614 def __call__(self, r):615 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'616 return r617618 req = requests.Request('GET', httpbin('headers'))619 assert not req.auth620621 s = requests.Session()622 s.auth = DummyAuth()623624 prep = s.prepare_request(req)625 resp = s.send(prep)626627 assert resp.json()['headers'][628 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'629630 def test_prepare_request_with_bytestring_url(self):631 req = requests.Request('GET', b'https://httpbin.org/')632 s = requests.Session()633 prep = s.prepare_request(req)634 assert prep.url == "https://httpbin.org/"635636 def test_links(self):637 r = requests.Response()638 r.headers = {639 'cache-control': 'public, max-age=60, s-maxage=60',640 'connection': 'keep-alive',641 'content-encoding': 'gzip',642 'content-type': 'application/json; charset=utf-8',643 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',644 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',645 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',646 'link': ('<https://api.github.com/users/kennethreitz/repos?'647 'page=2&per_page=10>; rel="next", <https://api.github.'648 'com/users/kennethreitz/repos?page=7&per_page=10>; '649 ' rel="last"'),650 'server': 'GitHub.com',651 'status': '200 OK',652 'vary': 'Accept',653 'x-content-type-options': 'nosniff',654 'x-github-media-type': 'github.beta',655 'x-ratelimit-limit': '60',656 'x-ratelimit-remaining': '57'657 }658 assert r.links['next']['rel'] == 'next'659660 def test_cookie_parameters(self):661 key = 'some_cookie'662 value = 'some_value'663 secure = True664 domain = 'test.com'665 rest = {'HttpOnly': True}666667 jar = requests.cookies.RequestsCookieJar()668 jar.set(key, value, secure=secure, domain=domain, rest=rest)669670 assert len(jar) == 1671 assert 'some_cookie' in jar672673 cookie = list(jar)[0]674 assert cookie.secure == secure675 assert cookie.domain == domain676 assert cookie._rest['HttpOnly'] == rest['HttpOnly']677678 def test_cookie_as_dict_keeps_len(self):679 key = 'some_cookie'680 value = 'some_value'681682 key1 = 'some_cookie1'683 value1 = 'some_value1'684685 jar = requests.cookies.RequestsCookieJar()686 jar.set(key, value)687 jar.set(key1, value1)688689 d1 = dict(jar)690 d2 = dict(jar.iteritems())691 d3 = dict(jar.items())692693 assert len(jar) == 2694 assert len(d1) == 2695 assert len(d2) == 2696 assert len(d3) == 2697698 def test_cookie_as_dict_keeps_items(self):699 key = 'some_cookie'700 value = 'some_value'701702 key1 = 'some_cookie1'703 value1 = 'some_value1'704705 jar = requests.cookies.RequestsCookieJar()706 jar.set(key, value)707 jar.set(key1, value1)708709 d1 = dict(jar)710 d2 = dict(jar.iteritems())711 d3 = dict(jar.items())712713 assert d1['some_cookie'] == 'some_value'714 assert d2['some_cookie'] == 'some_value'715 assert d3['some_cookie1'] == 'some_value1'716717 def test_cookie_as_dict_keys(self):718 key = 'some_cookie'719 value = 'some_value'720721 key1 = 'some_cookie1'722 value1 = 'some_value1'723724 jar = requests.cookies.RequestsCookieJar()725 jar.set(key, value)726 jar.set(key1, value1)727728 keys = jar.keys()729 assert keys == list(keys)730 # make sure one can use keys multiple times731 assert list(keys) == list(keys)732733 def test_cookie_as_dict_values(self):734 key = 'some_cookie'735 value = 'some_value'736737 key1 = 'some_cookie1'738 value1 = 'some_value1'739740 jar = requests.cookies.RequestsCookieJar()741 jar.set(key, value)742 jar.set(key1, value1)743744 values = jar.values()745 assert values == list(values)746 # make sure one can use values multiple times747 assert list(values) == list(values)748749 def test_cookie_as_dict_items(self):750 key = 'some_cookie'751 value = 'some_value'752753 key1 = 'some_cookie1'754 value1 = 'some_value1'755756 jar = requests.cookies.RequestsCookieJar()757 jar.set(key, value)758 jar.set(key1, value1)759760 items = jar.items()761 assert items == list(items)762 # make sure one can use items multiple times763 assert list(items) == list(items)764765 def test_time_elapsed_blank(self, httpbin):766 r = requests.get(httpbin('get'))767 td = r.elapsed768 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)769 * 10**6) / 10**6)770 assert total_seconds > 0.0771772 def test_response_is_iterable(self):773 r = requests.Response()774 io = StringIO.StringIO('abc')775 read_ = io.read776777 def read_mock(amt, decode_content=None):778 return read_(amt)779 setattr(io, 'read', read_mock)780 r.raw = io781 assert next(iter(r))782 io.close()783784 def test_response_decode_unicode(self):785 """786 When called with decode_unicode, Response.iter_content should always787 return unicode.788 """789 r = requests.Response()790 r._content_consumed = True791 r._content = b'the content'792 r.encoding = 'ascii'793794 chunks = r.iter_content(decode_unicode=True)795 assert all(isinstance(chunk, str) for chunk in chunks)796797 # also for streaming798 r = requests.Response()799 r.raw = io.BytesIO(b'the content')800 r.encoding = 'ascii'801 chunks = r.iter_content(decode_unicode=True)802 assert all(isinstance(chunk, str) for chunk in chunks)803804 def test_request_and_response_are_pickleable(self, httpbin):805 r = requests.get(httpbin('get'))806807 # verify we can pickle the original request808 assert pickle.loads(pickle.dumps(r.request))809810 # verify we can pickle the response and that we have access to811 # the original request.812 pr = pickle.loads(pickle.dumps(r))813 assert r.request.url == pr.request.url814 assert r.request.headers == pr.request.headers815816 def test_cannot_send_unprepared_requests(self, httpbin):817 r = requests.Request(url=httpbin())818 with pytest.raises(ValueError):819 requests.Session().send(r)820821 def test_http_error(self):822 error = requests.exceptions.HTTPError()823 assert not error.response824 response = requests.Response()825 error = requests.exceptions.HTTPError(response=response)826 assert error.response == response827 error = requests.exceptions.HTTPError('message', response=response)828 assert str(error) == 'message'829 assert error.response == response830831 def test_session_pickling(self, httpbin):832 r = requests.Request('GET', httpbin('get'))833 s = requests.Session()834835 s = pickle.loads(pickle.dumps(s))836 s.proxies = getproxies()837838 r = s.send(r.prepare())839 assert r.status_code == 200840841 def test_fixes_1329(self, httpbin):842 """843 Ensure that header updates are done case-insensitively.844 """845 s = requests.Session()846 s.headers.update({'ACCEPT': 'BOGUS'})847 s.headers.update({'accept': 'application/json'})848 r = s.get(httpbin('get'))849 headers = r.request.headers850 assert headers['accept'] == 'application/json'851 assert headers['Accept'] == 'application/json'852 assert headers['ACCEPT'] == 'application/json'853854 def test_uppercase_scheme_redirect(self, httpbin):855 parts = urlparse(httpbin('html'))856 url = "HTTP://" + parts.netloc + parts.path857 r = requests.get(httpbin('redirect-to'), params={'url': url})858 assert r.status_code == 200859 assert r.url.lower() == url.lower()860861 def test_transport_adapter_ordering(self):862 s = requests.Session()863 order = ['https://', 'http://']864 assert order == list(s.adapters)865 s.mount('http://git', HTTPAdapter())866 s.mount('http://github', HTTPAdapter())867 s.mount('http://github.com', HTTPAdapter())868 s.mount('http://github.com/about/', HTTPAdapter())869 order = [870 'http://github.com/about/',871 'http://github.com',872 'http://github',873 'http://git',874 'https://',875 'http://',876 ]877 assert order == list(s.adapters)878 s.mount('http://gittip', HTTPAdapter())879 s.mount('http://gittip.com', HTTPAdapter())880 s.mount('http://gittip.com/about/', HTTPAdapter())881 order = [882 'http://github.com/about/',883 'http://gittip.com/about/',884 'http://github.com',885 'http://gittip.com',886 'http://github',887 'http://gittip',888 'http://git',889 'https://',890 'http://',891 ]892 assert order == list(s.adapters)893 s2 = requests.Session()894 s2.adapters = {'http://': HTTPAdapter()}895 s2.mount('https://', HTTPAdapter())896 assert 'http://' in s2.adapters897 assert 'https://' in s2.adapters898899 def test_header_remove_is_case_insensitive(self, httpbin):900 # From issue #1321901 s = requests.Session()902 s.headers['foo'] = 'bar'903 r = s.get(httpbin('get'), headers={'FOO': None})904 assert 'foo' not in r.request.headers905906 def test_params_are_merged_case_sensitive(self, httpbin):907 s = requests.Session()908 s.params['foo'] = 'bar'909 r = s.get(httpbin('get'), params={'FOO': 'bar'})910 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}911912 def test_long_authinfo_in_url(self):913 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(914 'E8A3BE87-9E3F-4620-8858-95478E385B5B',915 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',916 'exactly-------------sixty-----------three------------characters',917 )918 r = requests.Request('GET', url).prepare()919 assert r.url == url920921 def test_header_keys_are_native(self, httpbin):922 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}923 r = requests.Request('GET', httpbin('get'), headers=headers)924 p = r.prepare()925926 # This is testing that they are builtin strings. A bit weird, but there927 # we go.928 assert 'unicode' in p.headers.keys()929 assert 'byte' in p.headers.keys()930931 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))932 def test_can_send_objects_with_files(self, httpbin, files):933 data = {'a': 'this is a string'}934 files = {'b': files}935 r = requests.Request('POST', httpbin('post'), data=data, files=files)936 p = r.prepare()937 assert 'multipart/form-data' in p.headers['Content-Type']938939 def test_can_send_file_object_with_non_string_filename(self, httpbin):940 f = io.BytesIO()941 f.name = 2942 r = requests.Request('POST', httpbin('post'), files={'f': f})943 p = r.prepare()944945 assert 'multipart/form-data' in p.headers['Content-Type']946947 def test_autoset_header_values_are_native(self, httpbin):948 data = 'this is a string'949 length = '16'950 req = requests.Request('POST', httpbin('post'), data=data)951 p = req.prepare()952953 assert p.headers['Content-Length'] == length954955 def test_nonhttp_schemes_dont_check_URLs(self):956 test_urls = (957 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',958 'file:///etc/passwd',959 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',960 )961 for test_url in test_urls:962 req = requests.Request('GET', test_url)963 preq = req.prepare()964 assert test_url == preq.url965966 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):967 r = requests.get(968 httpbin('redirect-to'),969 params={'url': 'http://www.google.co.uk'},970 auth=('user', 'pass'),971 )972 assert r.history[0].request.headers['Authorization']973 assert not r.request.headers.get('Authorization', '')974975 def test_auth_is_retained_for_redirect_on_host(self, httpbin):976 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))977 h1 = r.history[0].request.headers['Authorization']978 h2 = r.request.headers['Authorization']979980 assert h1 == h2981982 def test_manual_redirect_with_partial_body_read(self, httpbin):983 s = requests.Session()984 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)985 assert r1.is_redirect986 rg = s.resolve_redirects(r1, r1.request, stream=True)987988 # read only the first eight bytes of the response body,989 # then follow the redirect990 r1.iter_content(8)991 r2 = next(rg)992 assert r2.is_redirect993994 # read all of the response via iter_content,995 # then follow the redirect996 for _ in r2.iter_content():997 pass998 r3 = next(rg)999 assert not r3.is_redirect10001001 def _patch_adapter_gzipped_redirect(self, session, url):1002 adapter = session.get_adapter(url=url)1003 org_build_response = adapter.build_response1004 self._patched_response = False10051006 def build_response(*args, **kwargs):1007 resp = org_build_response(*args, **kwargs)1008 if not self._patched_response:1009 resp.raw.headers['content-encoding'] = 'gzip'1010 self._patched_response = True1011 return resp10121013 adapter.build_response = build_response10141015 def test_redirect_with_wrong_gzipped_header(self, httpbin):1016 s = requests.Session()1017 url = httpbin('redirect/1')1018 self._patch_adapter_gzipped_redirect(s, url)1019 s.get(url)10201021 def test_basic_auth_str_is_always_native(self):1022 s = _basic_auth_str("test", "test")1023 assert isinstance(s, builtin_str)1024 assert s == "Basic dGVzdDp0ZXN0"10251026 def test_requests_history_is_saved(self, httpbin):1027 r = requests.get(httpbin('redirect/5'))1028 total = r.history[-1].history1029 i = 01030 for item in r.history:1031 assert item.history == total[0:i]1032 i += 110331034 def test_json_param_post_content_type_works(self, httpbin):1035 r = requests.post(1036 httpbin('post'),1037 json={'life': 42}1038 )1039 assert r.status_code == 2001040 assert 'application/json' in r.request.headers['Content-Type']1041 assert {'life': 42} == r.json()['json']10421043 def test_json_param_post_should_not_override_data_param(self, httpbin):1044 r = requests.Request(method='POST', url=httpbin('post'),1045 data={'stuff': 'elixr'},1046 json={'music': 'flute'})1047 prep = r.prepare()1048 assert 'stuff=elixr' == prep.body10491050 def test_response_iter_lines(self, httpbin):1051 r = requests.get(httpbin('stream/4'), stream=True)1052 assert r.status_code == 20010531054 it = r.iter_lines()1055 next(it)1056 assert len(list(it)) == 310571058 def test_unconsumed_session_response_closes_connection(self, httpbin):1059 s = requests.session()10601061 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1062 pass10631064 assert response._content_consumed is False1065 assert response.raw.closed10661067 @pytest.mark.xfail1068 def test_response_iter_lines_reentrant(self, httpbin):1069 """Response.iter_lines() is not reentrant safe"""1070 r = requests.get(httpbin('stream/4'), stream=True)1071 assert r.status_code == 20010721073 next(r.iter_lines())1074 assert len(list(r.iter_lines())) == 3107510761077class TestCaseInsensitiveDict:10781079 @pytest.mark.parametrize(1080 'cid', (1081 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1082 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1083 CaseInsensitiveDict(FOO='foo', BAr='bar'),1084 )1085 )1086 def test_init(self, cid):1087 assert len(cid) == 21088 assert 'foo' in cid1089 assert 'bar' in cid10901091 def test_docstring_example(self):1092 cid = CaseInsensitiveDict()1093 cid['Accept'] = 'application/json'1094 assert cid['aCCEPT'] == 'application/json'1095 assert list(cid) == ['Accept']10961097 def test_len(self):1098 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1099 cid['A'] = 'a'1100 assert len(cid) == 211011102 def test_getitem(self):1103 cid = CaseInsensitiveDict({'Spam': 'blueval'})1104 assert cid['spam'] == 'blueval'1105 assert cid['SPAM'] == 'blueval'11061107 def test_fixes_649(self):1108 """__setitem__ should behave case-insensitively."""1109 cid = CaseInsensitiveDict()1110 cid['spam'] = 'oneval'1111 cid['Spam'] = 'twoval'1112 cid['sPAM'] = 'redval'1113 cid['SPAM'] = 'blueval'1114 assert cid['spam'] == 'blueval'1115 assert cid['SPAM'] == 'blueval'1116 assert list(cid.keys()) == ['SPAM']11171118 def test_delitem(self):1119 cid = CaseInsensitiveDict()1120 cid['Spam'] = 'someval'1121 del cid['sPam']1122 assert 'spam' not in cid1123 assert len(cid) == 011241125 def test_contains(self):1126 cid = CaseInsensitiveDict()1127 cid['Spam'] = 'someval'1128 assert 'Spam' in cid1129 assert 'spam' in cid1130 assert 'SPAM' in cid1131 assert 'sPam' in cid1132 assert 'notspam' not in cid11331134 def test_get(self):1135 cid = CaseInsensitiveDict()1136 cid['spam'] = 'oneval'1137 cid['SPAM'] = 'blueval'1138 assert cid.get('spam') == 'blueval'1139 assert cid.get('SPAM') == 'blueval'1140 assert cid.get('sPam') == 'blueval'1141 assert cid.get('notspam', 'default') == 'default'11421143 def test_update(self):1144 cid = CaseInsensitiveDict()1145 cid['spam'] = 'blueval'1146 cid.update({'sPam': 'notblueval'})1147 assert cid['spam'] == 'notblueval'1148 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1149 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1150 assert len(cid) == 21151 assert cid['foo'] == 'anotherfoo'1152 assert cid['bar'] == 'anotherbar'11531154 def test_update_retains_unchanged(self):1155 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1156 cid.update({'foo': 'newfoo'})1157 assert cid['bar'] == 'bar'11581159 def test_iter(self):1160 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1161 keys = frozenset(['Spam', 'Eggs'])1162 assert frozenset(iter(cid)) == keys11631164 def test_equality(self):1165 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1166 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1167 assert cid == othercid1168 del othercid['spam']1169 assert cid != othercid1170 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1171 assert cid != object()11721173 def test_setdefault(self):1174 cid = CaseInsensitiveDict({'Spam': 'blueval'})1175 assert cid.setdefault('spam', 'notblueval') == 'blueval'1176 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'11771178 def test_lower_items(self):1179 cid = CaseInsensitiveDict({1180 'Accept': 'application/json',1181 'user-Agent': 'requests',1182 })1183 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1184 lowerkeyset = frozenset(['accept', 'user-agent'])1185 assert keyset == lowerkeyset11861187 def test_preserve_key_case(self):1188 cid = CaseInsensitiveDict({1189 'Accept': 'application/json',1190 'user-Agent': 'requests',1191 })1192 keyset = frozenset(['Accept', 'user-Agent'])1193 assert frozenset(i[0] for i in cid.items()) == keyset1194 assert frozenset(cid.keys()) == keyset1195 assert frozenset(cid) == keyset11961197 def test_preserve_last_key_case(self):1198 cid = CaseInsensitiveDict({1199 'Accept': 'application/json',1200 'user-Agent': 'requests',1201 })1202 cid.update({'ACCEPT': 'application/json'})1203 cid['USER-AGENT'] = 'requests'1204 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1205 assert frozenset(i[0] for i in cid.items()) == keyset1206 assert frozenset(cid.keys()) == keyset1207 assert frozenset(cid) == keyset12081209 def test_copy(self):1210 cid = CaseInsensitiveDict({1211 'Accept': 'application/json',1212 'user-Agent': 'requests',1213 })1214 cid_copy = cid.copy()1215 assert cid == cid_copy1216 cid['changed'] = True1217 assert cid != cid_copy121812191220class TestMorselToCookieExpires:1221 """Tests for morsel_to_cookie when morsel contains expires."""12221223 def test_expires_valid_str(self):1224 """Test case where we convert expires from string time."""12251226 morsel = Morsel()1227 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1228 cookie = morsel_to_cookie(morsel)1229 assert cookie.expires == 112301231 @pytest.mark.parametrize(1232 'value, exception', (1233 (100, TypeError),1234 ('woops', ValueError),1235 )1236 )1237 def test_expires_invalid_int(self, value, exception):1238 """Test case where an invalid type is passed for expires."""1239 morsel = Morsel()1240 morsel['expires'] = value1241 with pytest.raises(exception):1242 morsel_to_cookie(morsel)12431244 def test_expires_none(self):1245 """Test case where expires is None."""12461247 morsel = Morsel()1248 morsel['expires'] = None1249 cookie = morsel_to_cookie(morsel)1250 assert cookie.expires is None125112521253class TestMorselToCookieMaxAge:12541255 """Tests for morsel_to_cookie when morsel contains max-age."""12561257 def test_max_age_valid_int(self):1258 """Test case where a valid max age in seconds is passed."""12591260 morsel = Morsel()1261 morsel['max-age'] = 601262 cookie = morsel_to_cookie(morsel)1263 assert isinstance(cookie.expires, int)12641265 def test_max_age_invalid_str(self):1266 """Test case where a invalid max age is passed."""12671268 morsel = Morsel()1269 morsel['max-age'] = 'woops'1270 with pytest.raises(TypeError):1271 morsel_to_cookie(morsel)127212731274class TestTimeout:12751276 def test_stream_timeout(self, httpbin):1277 try:1278 requests.get(httpbin('delay/10'), timeout=2.0)1279 except requests.exceptions.Timeout as e:1280 assert 'Read timed out' in e.args[0].args[0]12811282 @pytest.mark.parametrize(1283 'timeout, error_text', (1284 ((3, 4, 5), '(connect, read)'),1285 ('foo', 'must be an int or float'),1286 )1287 )1288 def test_invalid_timeout(self, httpbin, timeout, error_text):1289 with pytest.raises(ValueError) as e:1290 requests.get(httpbin('get'), timeout=timeout)1291 assert error_text in str(e)12921293 def test_none_timeout(self, httpbin):1294 """ Check that you can set None as a valid timeout value.12951296 To actually test this behavior, we'd want to check that setting the1297 timeout to None actually lets the request block past the system default1298 timeout. However, this would make the test suite unbearably slow.1299 Instead we verify that setting the timeout to None does not prevent the1300 request from succeeding.1301 """1302 r = requests.get(httpbin('get'), timeout=None)1303 assert r.status_code == 20013041305 def test_read_timeout(self, httpbin):1306 try:1307 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1308 pytest.fail('The recv() request should time out.')1309 except ReadTimeout:1310 pass13111312 def test_connect_timeout(self):1313 try:1314 requests.get(TARPIT, timeout=(0.1, None))1315 pytest.fail('The connect() request should time out.')1316 except ConnectTimeout as e:1317 assert isinstance(e, ConnectionError)1318 assert isinstance(e, Timeout)13191320 def test_total_timeout_connect(self):1321 try:1322 requests.get(TARPIT, timeout=(0.1, 0.1))1323 pytest.fail('The connect() request should time out.')1324 except ConnectTimeout:1325 pass13261327 def test_encoded_methods(self, httpbin):1328 """See: https://github.com/kennethreitz/requests/issues/2316"""1329 r = requests.request(b'GET', httpbin('get'))1330 assert r.ok133113321333SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))133413351336class RedirectSession(SessionRedirectMixin):1337 def __init__(self, order_of_redirects):1338 self.redirects = order_of_redirects1339 self.calls = []1340 self.max_redirects = 301341 self.cookies = {}1342 self.trust_env = False13431344 def send(self, *args, **kwargs):1345 self.calls.append(SendCall(args, kwargs))1346 return self.build_response()13471348 def build_response(self):1349 request = self.calls[-1].args[0]1350 r = requests.Response()13511352 try:1353 r.status_code = int(self.redirects.pop(0))1354 except IndexError:1355 r.status_code = 20013561357 r.headers = CaseInsensitiveDict({'Location': '/'})1358 r.raw = self._build_raw()1359 r.request = request1360 return r13611362 def _build_raw(self):1363 string = StringIO.StringIO('')1364 setattr(string, 'release_conn', lambda *args: args)1365 return string136613671368def test_requests_are_updated_each_time(httpbin):1369 session = RedirectSession([303, 307])1370 prep = requests.Request('POST', httpbin('post')).prepare()1371 r0 = session.send(prep)1372 assert r0.request.method == 'POST'1373 assert session.calls[-1] == SendCall((r0.request,), {})1374 redirect_generator = session.resolve_redirects(r0, prep)1375 default_keyword_args = {1376 'stream': False,1377 'verify': True,1378 'cert': None,1379 'timeout': None,1380 'allow_redirects': False,1381 'proxies': {},1382 }1383 for response in redirect_generator:1384 assert response.request.method == 'GET'1385 send_call = SendCall((response.request,), default_keyword_args)1386 assert session.calls[-1] == send_call138713881389@pytest.mark.parametrize(1390 'data', (1391 (('a', 'b'), ('c', 'd')),1392 (('c', 'd'), ('a', 'b')),1393 (('a', 'b'), ('c', 'd'), ('e', 'f')),1394 )1395)1396def test_data_argument_accepts_tuples(data):1397 """Ensure that the data argument will accept tuples of strings1398 and properly encode them.1399 """1400 p = PreparedRequest()1401 p.prepare(1402 method='GET',1403 url='http://www.example.com',1404 data=data,1405 hooks=default_hooks()1406 )1407 assert p.body == urlencode(data)140814091410@pytest.mark.parametrize(1411 'kwargs', (1412 None,1413 {1414 'method': 'GET',1415 'url': 'http://www.example.com',1416 'data': 'foo=bar',1417 'hooks': default_hooks()1418 },1419 {1420 'method': 'GET',1421 'url': 'http://www.example.com',1422 'data': 'foo=bar',1423 'hooks': default_hooks(),1424 'cookies': {'foo': 'bar'}1425 },1426 {1427 'method': 'GET',1428 'url': u('http://www.example.com/üniçø∂é')1429 },1430 )1431)1432def test_prepared_copy(kwargs):1433 p = PreparedRequest()1434 if kwargs:1435 p.prepare(**kwargs)1436 copy = p.copy()1437 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1438 assert getattr(p, attr) == getattr(copy, attr)143914401441def test_urllib3_retries(httpbin):1442 from requests.packages.urllib3.util import Retry1443 s = requests.Session()1444 s.mount('http://', HTTPAdapter(max_retries=Retry(1445 total=2, status_forcelist=[500]1446 )))14471448 with pytest.raises(RetryError):1449 s.get(httpbin('status/500'))145014511452def test_urllib3_pool_connection_closed(httpbin):1453 s = requests.Session()1454 s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))14551456 try:1457 s.get(httpbin('status/200'))1458 except ConnectionError as e:1459 assert u"Pool is closed." in str(e)146014611462def test_vendor_aliases():1463 from requests.packages import urllib31464 from requests.packages import chardet14651466 with pytest.raises(ImportError):1467 from requests.packages import webbrowser
added:tests/test_utils.py+242 added
1# coding: utf-82import os3from io import BytesIO45import pytest6from requests import compat7from requests.utils import (8 address_in_network, dotted_netmask,9 get_auth_from_url, get_encodings_from_content,10 get_environ_proxies, guess_filename,11 is_ipv4_address, is_valid_cidr, requote_uri,12 select_proxy, super_len)1314from .compat import StringIO, cStringIO151617class TestSuperLen:1819 @pytest.mark.parametrize(20 'stream, value', (21 (StringIO.StringIO, 'Test'),22 (BytesIO, b'Test'),23 pytest.mark.skipif('cStringIO is None')(24 (cStringIO, 'Test')25 ),26 ))27 def test_io_streams(self, stream, value):28 """ Ensures that we properly deal with different kinds of IO streams. """29 assert super_len(stream()) == 030 assert super_len(stream(value)) == 43132 def test_super_len_correctly_calculates_len_of_partially_read_file(self):33 """Ensure that we handle partially consumed file like objects."""34 s = StringIO.StringIO()35 s.write('foobarbogus')36 assert super_len(s) == 0373839class TestGetEnvironProxies:40 """Ensures that IP addresses are correctly matches with ranges41 in no_proxy variable."""4243 @pytest.yield_fixture(scope='class', autouse=True, params=['no_proxy', 'NO_PROXY'])44 def no_proxy(self, request):45 os.environ[request.param] = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'46 yield47 del os.environ[request.param]4849 @pytest.mark.parametrize(50 'url', (51 'http://192.168.0.1:5000/',52 'http://192.168.0.1/',53 'http://172.16.1.1/',54 'http://172.16.1.1:5000/',55 'http://localhost.localdomain:5000/v1.0/',56 )57 )58 def test_bypass(self, url):59 assert get_environ_proxies(url) == {}6061 @pytest.mark.parametrize(62 'url', (63 'http://192.168.1.1:5000/',64 'http://192.168.1.1/',65 'http://www.requests.com/',66 )67 )68 def test_not_bypass(self, url):69 assert get_environ_proxies(url) != {}707172class TestIsIPv4Address:7374 def test_valid(self):75 assert is_ipv4_address('8.8.8.8')7677 @pytest.mark.parametrize('value', ('8.8.8.8.8', 'localhost.localdomain'))78 def test_invalid(self, value):79 assert not is_ipv4_address(value)808182class TestIsValidCIDR:8384 def test_valid(self):85 assert is_valid_cidr('192.168.1.0/24')8687 @pytest.mark.parametrize(88 'value', (89 '8.8.8.8',90 '192.168.1.0/a',91 '192.168.1.0/128',92 '192.168.1.0/-1',93 '192.168.1.999/24',94 )95 )96 def test_invalid(self, value):97 assert not is_valid_cidr(value)9899100class TestAddressInNetwork:101102 def test_valid(self):103 assert address_in_network('192.168.1.1', '192.168.1.0/24')104105 def test_invalid(self):106 assert not address_in_network('172.16.0.1', '192.168.1.0/24')107108109class TestGuessFilename:110111 @pytest.mark.parametrize(112 'value', (1, type('Fake', (object,), {'name': 1})()),113 )114 def test_guess_filename_invalid(self, value):115 assert guess_filename(value) is None116117 @pytest.mark.parametrize(118 'value, expected_type', (119 (b'value', compat.bytes),120 (b'value'.decode('utf-8'), compat.str)121 )122 )123 def test_guess_filename_valid(self, value, expected_type):124 obj = type('Fake', (object,), {'name': value})()125 result = guess_filename(obj)126 assert result == value127 assert isinstance(result, expected_type)128129130class TestContentEncodingDetection:131132 def test_none(self):133 encodings = get_encodings_from_content('')134 assert not len(encodings)135136 @pytest.mark.parametrize(137 'content', (138 # HTML5 meta charset attribute139 '<meta charset="UTF-8">',140 # HTML4 pragma directive141 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',142 # XHTML 1.x served with text/html MIME type143 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',144 # XHTML 1.x served as XML145 '<?xml version="1.0" encoding="UTF-8"?>',146 )147 )148 def test_pragmas(self, content):149 encodings = get_encodings_from_content(content)150 assert len(encodings) == 1151 assert encodings[0] == 'UTF-8'152153 def test_precedence(self):154 content = '''155 <?xml version="1.0" encoding="XML"?>156 <meta charset="HTML5">157 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />158 '''.strip()159 assert get_encodings_from_content(content) == ['HTML5', 'HTML4', 'XML']160161162USER = PASSWORD = "%!*'();:@&=+$,/?#[] "163ENCODED_USER = compat.quote(USER, '')164ENCODED_PASSWORD = compat.quote(PASSWORD, '')165166167@pytest.mark.parametrize(168 'url, auth', (169 (170 'http://' + ENCODED_USER + ':' + ENCODED_PASSWORD + '@' +171 'request.com/url.html#test',172 (USER, PASSWORD)173 ),174 (175 'http://user:pass@complex.url.com/path?query=yes',176 ('user', 'pass')177 ),178 (179 'http://user:pass%20pass@complex.url.com/path?query=yes',180 ('user', 'pass pass')181 ),182 (183 'http://user:pass pass@complex.url.com/path?query=yes',184 ('user', 'pass pass')185 ),186 (187 'http://user%25user:pass@complex.url.com/path?query=yes',188 ('user%user', 'pass')189 ),190 (191 'http://user:pass%23pass@complex.url.com/path?query=yes',192 ('user', 'pass#pass')193 ),194 )195)196def test_get_auth_from_url(url, auth):197 assert get_auth_from_url(url) == auth198199200@pytest.mark.parametrize(201 'uri, expected', (202 (203 # Ensure requoting doesn't break expectations204 'http://example.com/fiz?buz=%25ppicture',205 'http://example.com/fiz?buz=%25ppicture',206 ),207 (208 # Ensure we handle unquoted percent signs in redirects209 'http://example.com/fiz?buz=%ppicture',210 'http://example.com/fiz?buz=%25ppicture',211 ),212 )213)214def test_requote_uri_with_unquoted_percents(uri, expected):215 """See: https://github.com/kennethreitz/requests/issues/2356216 """217 assert requote_uri(uri) == expected218219220@pytest.mark.parametrize(221 'mask, expected', (222 (8, '255.0.0.0'),223 (24, '255.255.255.0'),224 (25, '255.255.255.128'),225 )226)227def test_dotted_netmask(mask, expected):228 assert dotted_netmask(mask) == expected229230231@pytest.mark.parametrize(232 'url, expected', (233 ('hTTp://u:p@Some.Host/path', 'http://some.host.proxy'),234 ('hTTp://u:p@Other.Host/path', 'http://http.proxy'),235 ('hTTps://Other.Host', None),236 )237)238def test_select_proxies(url, expected):239 """Make sure we can select per-host proxies correctly."""240 proxies = {'http': 'http://http.proxy',241 'http://some.host': 'http://some.host.proxy'}242 assert select_proxy(url, proxies) == expected
modified:Makefile+2 added-2 removed
4 unmodified lines
56test:7 # This runs all of the tests. To run an individual test, run py.test with8 # the -k flag, like "py.test -k test_path_is_not_double_encoded"9 py.test test_requests.py9 py.test tests1011coverage:12 py.test --verbose --cov-report term --cov=requests test_requests.py12 py.test --verbose --cov-report term --cov=requests tests1314ci: init15 py.test --junitxml=junit.xml16
23 unmodified lines
deleted:test_requests.py-1725 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import collections11import contextlib1213import io14import requests15import pytest16from requests.adapters import HTTPAdapter17from requests.auth import HTTPDigestAuth, _basic_auth_str18from requests.compat import (19 Morsel, cookielib, getproxies, str, urljoin, urlparse, is_py3,20 builtin_str, OrderedDict)21from requests.cookies import cookiejar_from_dict, morsel_to_cookie22from requests.exceptions import (23 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,24 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects)25from requests.models import PreparedRequest26from requests.structures import CaseInsensitiveDict27from requests.sessions import SessionRedirectMixin28from requests.models import urlencode29from requests.hooks import default_hooks3031try:32 import StringIO33except ImportError:34 import io as StringIO3536try:37 from multiprocessing.pool import ThreadPool38except ImportError:39 ThreadPool = None4041if is_py3:42 def u(s):43 return s44else:45 def u(s):46 return s.decode('unicode-escape')474849@pytest.fixture50def httpbin(httpbin):51 # Issue #1483: Make sure the URL always has a trailing slash52 httpbin_url = httpbin.url.rstrip('/') + '/'5354 def inner(*suffix):55 return urljoin(httpbin_url, '/'.join(suffix))5657 return inner585960@pytest.fixture61def httpsbin_url(httpbin_secure):62 # Issue #1483: Make sure the URL always has a trailing slash63 httpbin_url = httpbin_secure.url.rstrip('/') + '/'6465 def inner(*suffix):66 return urljoin(httpbin_url, '/'.join(suffix))6768 return inner697071# Requests to this URL should always fail with a connection timeout (nothing72# listening on that port)73TARPIT = "http://10.255.255.1"747576class TestRequests:7778 def test_entry_points(self):7980 requests.session81 requests.session().get82 requests.session().head83 requests.get84 requests.head85 requests.put86 requests.patch87 requests.post8889 @pytest.mark.parametrize('exception, url',90 (91 (MissingSchema, 'hiwpefhipowhefopw'),92 (InvalidSchema, 'localhost:3128'),93 (InvalidSchema, 'localhost.localdomain:3128/'),94 (InvalidSchema, '10.122.1.1:3128/'),95 (InvalidURL, 'http://'),96 )97 )98 def test_invalid_url(self, exception, url):99 with pytest.raises(exception):100 requests.get(url)101102 def test_basic_building(self):103 req = requests.Request()104 req.url = 'http://kennethreitz.org/'105 req.data = {'life': '42'}106107 pr = req.prepare()108 assert pr.url == req.url109 assert pr.body == 'life=42'110111 @pytest.mark.parametrize('method', ('GET', 'HEAD'))112 def test_no_content_length(self, httpbin, method):113 req = requests.Request(method, httpbin(method.lower())).prepare()114 assert 'Content-Length' not in req.headers115116 def test_override_content_length(self, httpbin):117 headers = {118 'Content-Length': 'not zero'119 }120 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()121 assert 'Content-Length' in r.headers122 assert r.headers['Content-Length'] == 'not zero'123124 def test_path_is_not_double_encoded(self):125 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()126127 assert request.path_url == '/get/test%20case'128129 @pytest.mark.parametrize('url, expected',130 (131 ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),132 ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')133 )134 )135 def test_params_are_added_before_fragment(self, url, expected):136 request = requests.Request('GET', url, params={"a": "b"}).prepare()137 assert request.url == expected138139 def test_params_original_order_is_preserved_by_default(self):140 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))141 session = requests.Session()142 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)143 prep = session.prepare_request(request)144 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'145146 def test_params_bytes_are_encoded(self):147 request = requests.Request('GET', 'http://example.com',148 params=b'test=foo').prepare()149 assert request.url == 'http://example.com/?test=foo'150151 def test_binary_put(self):152 request = requests.Request('PUT', 'http://example.com',153 data=u"ööö".encode("utf-8")).prepare()154 assert isinstance(request.body, bytes)155156 @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))157 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):158 s = requests.Session()159 s.proxies = getproxies()160 parts = urlparse(httpbin('get'))161 url = scheme + parts.netloc + parts.path162 r = requests.Request('GET', url)163 r = s.send(r.prepare())164 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)165166 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):167 r = requests.Request('GET', httpbin('get'))168 s = requests.Session()169 s.proxies = getproxies()170171 r = s.send(r.prepare())172173 assert r.status_code == 200174175 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):176 r = requests.get(httpbin('redirect', '1'))177 assert r.status_code == 200178 assert r.history[0].status_code == 302179 assert r.history[0].is_redirect180181 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):182 try:183 requests.get(httpbin('relative-redirect', '50'))184 except TooManyRedirects as e:185 url = httpbin('relative-redirect', '20')186 assert e.request.url == url187 assert e.response.url == url188 assert len(e.response.history) == 30189 else:190 pytest.fail('Expected redirect to raise TooManyRedirects but it did not')191192 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):193 s = requests.session()194 s.max_redirects = 5195 try:196 s.get(httpbin('relative-redirect', '50'))197 except TooManyRedirects as e:198 url = httpbin('relative-redirect', '45')199 assert e.request.url == url200 assert e.response.url == url201 assert len(e.response.history) == 5202 else:203 pytest.fail('Expected custom max number of redirects to be respected but was not')204205 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):206 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})207 # self.assertEqual(r.status_code, 200)208209 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):210 heads = {'User-agent': 'Mozilla/5.0'}211212 r = requests.get(httpbin('user-agent'), headers=heads)213214 assert heads['User-agent'] in r.text215 assert r.status_code == 200216217 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):218 heads = {'User-agent': 'Mozilla/5.0'}219220 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)221 assert r.status_code == 200222223 def test_set_cookie_on_301(self, httpbin):224 s = requests.session()225 url = httpbin('cookies/set?foo=bar')226 s.get(url)227 assert s.cookies['foo'] == 'bar'228229 def test_cookie_sent_on_redirect(self, httpbin):230 s = requests.session()231 s.get(httpbin('cookies/set?foo=bar'))232 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')233 assert 'Cookie' in r.json()['headers']234235 def test_cookie_removed_on_expire(self, httpbin):236 s = requests.session()237 s.get(httpbin('cookies/set?foo=bar'))238 assert s.cookies['foo'] == 'bar'239 s.get(240 httpbin('response-headers'),241 params={242 'Set-Cookie':243 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'244 }245 )246 assert 'foo' not in s.cookies247248 def test_cookie_quote_wrapped(self, httpbin):249 s = requests.session()250 s.get(httpbin('cookies/set?foo="bar:baz"'))251 assert s.cookies['foo'] == '"bar:baz"'252253 def test_cookie_persists_via_api(self, httpbin):254 s = requests.session()255 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})256 assert 'foo' in r.request.headers['Cookie']257 assert 'foo' in r.history[0].request.headers['Cookie']258259 def test_request_cookie_overrides_session_cookie(self, httpbin):260 s = requests.session()261 s.cookies['foo'] = 'bar'262 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})263 assert r.json()['cookies']['foo'] == 'baz'264 # Session cookie should not be modified265 assert s.cookies['foo'] == 'bar'266267 def test_request_cookies_not_persisted(self, httpbin):268 s = requests.session()269 s.get(httpbin('cookies'), cookies={'foo': 'baz'})270 # Sending a request with cookies should not add cookies to the session271 assert not s.cookies272273 def test_generic_cookiejar_works(self, httpbin):274 cj = cookielib.CookieJar()275 cookiejar_from_dict({'foo': 'bar'}, cj)276 s = requests.session()277 s.cookies = cj278 r = s.get(httpbin('cookies'))279 # Make sure the cookie was sent280 assert r.json()['cookies']['foo'] == 'bar'281 # Make sure the session cj is still the custom one282 assert s.cookies is cj283284 def test_param_cookiejar_works(self, httpbin):285 cj = cookielib.CookieJar()286 cookiejar_from_dict({'foo': 'bar'}, cj)287 s = requests.session()288 r = s.get(httpbin('cookies'), cookies=cj)289 # Make sure the cookie was sent290 assert r.json()['cookies']['foo'] == 'bar'291292 def test_requests_in_history_are_not_overridden(self, httpbin):293 resp = requests.get(httpbin('redirect/3'))294 urls = [r.url for r in resp.history]295 req_urls = [r.request.url for r in resp.history]296 assert urls == req_urls297298 def test_history_is_always_a_list(self, httpbin):299 """Show that even with redirects, Response.history is always a list."""300 resp = requests.get(httpbin('get'))301 assert isinstance(resp.history, list)302 resp = requests.get(httpbin('redirect/1'))303 assert isinstance(resp.history, list)304 assert not isinstance(resp.history, tuple)305306 def test_headers_on_session_with_None_are_not_sent(self, httpbin):307 """Do not send headers in Session.headers with None values."""308 ses = requests.Session()309 ses.headers['Accept-Encoding'] = None310 req = requests.Request('GET', httpbin('get'))311 prep = ses.prepare_request(req)312 assert 'Accept-Encoding' not in prep.headers313314 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))315 def test_user_agent_transfers(self, httpbin, key):316317 heads = {318 key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'319 }320321 r = requests.get(httpbin('user-agent'), headers=heads)322 assert heads[key] in r.text323324 def test_HTTP_200_OK_HEAD(self, httpbin):325 r = requests.head(httpbin('get'))326 assert r.status_code == 200327328 def test_HTTP_200_OK_PUT(self, httpbin):329 r = requests.put(httpbin('put'))330 assert r.status_code == 200331332 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):333 auth = ('user', 'pass')334 url = httpbin('basic-auth', 'user', 'pass')335336 r = requests.get(url, auth=auth)337 assert r.status_code == 200338339 r = requests.get(url)340 assert r.status_code == 401341342 s = requests.session()343 s.auth = auth344 r = s.get(url)345 assert r.status_code == 200346347 @pytest.mark.parametrize('url, exception',348 (349 # Connecting to an unknown domain should raise a ConnectionError350 ('http://doesnotexist.google.com', ConnectionError),351 # Connecting to an invalid port should raise a ConnectionError352 ('http://localhost:1', ConnectionError),353 # Inputing a URL that cannot be parsed should raise an InvalidURL error354 ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)355 )356 )357 def test_errors(self, url, exception):358 with pytest.raises(exception):359 requests.get(url, timeout=1)360361 def test_basicauth_with_netrc(self, httpbin):362 auth = ('user', 'pass')363 wrong_auth = ('wronguser', 'wrongpass')364 url = httpbin('basic-auth', 'user', 'pass')365366 old_auth = requests.sessions.get_netrc_auth367368 try:369 def get_netrc_auth_mock(url):370 return auth371 requests.sessions.get_netrc_auth = get_netrc_auth_mock372373 # Should use netrc and work.374 r = requests.get(url)375 assert r.status_code == 200376377 # Given auth should override and fail.378 r = requests.get(url, auth=wrong_auth)379 assert r.status_code == 401380381 s = requests.session()382383 # Should use netrc and work.384 r = s.get(url)385 assert r.status_code == 200386387 # Given auth should override and fail.388 s.auth = wrong_auth389 r = s.get(url)390 assert r.status_code == 401391 finally:392 requests.sessions.get_netrc_auth = old_auth393394 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):395396 auth = HTTPDigestAuth('user', 'pass')397 url = httpbin('digest-auth', 'auth', 'user', 'pass')398399 r = requests.get(url, auth=auth)400 assert r.status_code == 200401402 r = requests.get(url)403 assert r.status_code == 401404405 s = requests.session()406 s.auth = HTTPDigestAuth('user', 'pass')407 r = s.get(url)408 assert r.status_code == 200409410 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):411 url = httpbin('digest-auth', 'auth', 'user', 'pass')412 auth = HTTPDigestAuth('user', 'pass')413 r = requests.get(url)414 assert r.cookies['fake'] == 'fake_value'415416 r = requests.get(url, auth=auth)417 assert r.status_code == 200418419 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):420 url = httpbin('digest-auth', 'auth', 'user', 'pass')421 auth = HTTPDigestAuth('user', 'pass')422 s = requests.Session()423 s.get(url, auth=auth)424 assert s.cookies['fake'] == 'fake_value'425426 def test_DIGEST_STREAM(self, httpbin):427428 auth = HTTPDigestAuth('user', 'pass')429 url = httpbin('digest-auth', 'auth', 'user', 'pass')430431 r = requests.get(url, auth=auth, stream=True)432 assert r.raw.read() != b''433434 r = requests.get(url, auth=auth, stream=False)435 assert r.raw.read() == b''436437 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):438439 auth = HTTPDigestAuth('user', 'wrongpass')440 url = httpbin('digest-auth', 'auth', 'user', 'pass')441442 r = requests.get(url, auth=auth)443 assert r.status_code == 401444445 r = requests.get(url)446 assert r.status_code == 401447448 s = requests.session()449 s.auth = auth450 r = s.get(url)451 assert r.status_code == 401452453 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):454455 auth = HTTPDigestAuth('user', 'pass')456 url = httpbin('digest-auth', 'auth', 'user', 'pass')457458 r = requests.get(url, auth=auth)459 assert '"auth"' in r.request.headers['Authorization']460461 def test_POSTBIN_GET_POST_FILES(self, httpbin):462463 url = httpbin('post')464 requests.post(url).raise_for_status()465466 post1 = requests.post(url, data={'some': 'data'})467 assert post1.status_code == 200468469 with open('requirements.txt') as f:470 post2 = requests.post(url, files={'some': f})471 assert post2.status_code == 200472473 post4 = requests.post(url, data='[{"some": "json"}]')474 assert post4.status_code == 200475476 with pytest.raises(ValueError):477 requests.post(url, files=['bad file data'])478479 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):480481 url = httpbin('post')482 requests.post(url).raise_for_status()483484 post1 = requests.post(url, data={'some': 'data'})485 assert post1.status_code == 200486487 with open('requirements.txt') as f:488 post2 = requests.post(url,489 data={'some': 'data'}, files={'some': f})490 assert post2.status_code == 200491492 post4 = requests.post(url, data='[{"some": "json"}]')493 assert post4.status_code == 200494495 with pytest.raises(ValueError):496 requests.post(url, files=['bad file data'])497498 def test_conflicting_post_params(self, httpbin):499 url = httpbin('post')500 with open('requirements.txt') as f:501 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")502 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")503504 def test_request_ok_set(self, httpbin):505 r = requests.get(httpbin('status', '404'))506 assert not r.ok507508 def test_status_raising(self, httpbin):509 r = requests.get(httpbin('status', '404'))510 with pytest.raises(requests.exceptions.HTTPError):511 r.raise_for_status()512513 r = requests.get(httpbin('status', '500'))514 assert not r.ok515516 def test_decompress_gzip(self, httpbin):517 r = requests.get(httpbin('gzip'))518 r.content.decode('ascii')519520 @pytest.mark.parametrize(521 'url, params',522 (523 ('/get', {'foo': 'føø'}),524 ('/get', {'føø': 'føø'}),525 ('/get', {'føø': 'føø'}),526 ('/get', {'foo': 'foo'}),527 ('ø', {'foo': 'foo'}),528 )529 )530 def test_unicode_get(self, httpbin, url, params):531 requests.get(httpbin(url), params=params)532533 def test_unicode_header_name(self, httpbin):534 requests.put(535 httpbin('put'),536 headers={str('Content-Type'): 'application/octet-stream'},537 data='\xff') # compat.str is unicode.538539 def test_pyopenssl_redirect(self, httpsbin_url, httpbin_ca_bundle):540 requests.get(httpsbin_url('status', '301'), verify=httpbin_ca_bundle)541542 def test_urlencoded_get_query_multivalued_param(self, httpbin):543544 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))545 assert r.status_code == 200546 assert r.url == httpbin('get?test=foo&test=baz')547548 def test_different_encodings_dont_break_post(self, httpbin):549 r = requests.post(httpbin('post'),550 data={'stuff': json.dumps({'a': 123})},551 params={'blah': 'asdf1234'},552 files={'file': ('test_requests.py', open(__file__, 'rb'))})553 assert r.status_code == 200554555 @pytest.mark.parametrize(556 'data', (557 {'stuff': u('ëlïxr')},558 {'stuff': u('ëlïxr').encode('utf-8')},559 {'stuff': 'elixr'},560 {'stuff': 'elixr'.encode('utf-8')},561 )562 )563 def test_unicode_multipart_post(self, httpbin, data):564 r = requests.post(httpbin('post'),565 data=data,566 files={'file': ('test_requests.py', open(__file__, 'rb'))})567 assert r.status_code == 200568569 def test_unicode_multipart_post_fieldnames(self, httpbin):570 filename = os.path.splitext(__file__)[0] + '.py'571 r = requests.Request(method='POST',572 url=httpbin('post'),573 data={'stuff'.encode('utf-8'): 'elixr'},574 files={'file': ('test_requests.py',575 open(filename, 'rb'))})576 prep = r.prepare()577 assert b'name="stuff"' in prep.body578 assert b'name="b\'stuff\'"' not in prep.body579580 def test_unicode_method_name(self, httpbin):581 files = {'file': open('test_requests.py', 'rb')}582 r = requests.request(583 method=u('POST'), url=httpbin('post'), files=files)584 assert r.status_code == 200585586 def test_unicode_method_name_with_request_object(self, httpbin):587 files = {'file': open('test_requests.py', 'rb')}588 s = requests.Session()589 req = requests.Request(u("POST"), httpbin('post'), files=files)590 prep = s.prepare_request(req)591 assert isinstance(prep.method, builtin_str)592 assert prep.method == "POST"593594 resp = s.send(prep)595 assert resp.status_code == 200596597 def test_custom_content_type(self, httpbin):598 r = requests.post(599 httpbin('post'),600 data={'stuff': json.dumps({'a': 123})},601 files={'file1': ('test_requests.py', open(__file__, 'rb')),602 'file2': ('test_requests', open(__file__, 'rb'),603 'text/py-content-type')})604 assert r.status_code == 200605 assert b"text/py-content-type" in r.request.body606607 def test_hook_receives_request_arguments(self, httpbin):608 def hook(resp, **kwargs):609 assert resp is not None610 assert kwargs != {}611612 s = requests.Session()613 r = requests.Request('GET', httpbin(), hooks={'response': hook})614 prep = s.prepare_request(r)615 s.send(prep)616617 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):618 hook = lambda x, *args, **kwargs: x619 s = requests.Session()620 s.hooks['response'].append(hook)621 r = requests.Request('GET', httpbin())622 prep = s.prepare_request(r)623 assert prep.hooks['response'] != []624 assert prep.hooks['response'] == [hook]625626 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):627 hook1 = lambda x, *args, **kwargs: x628 hook2 = lambda x, *args, **kwargs: x629 assert hook1 is not hook2630 s = requests.Session()631 s.hooks['response'].append(hook2)632 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})633 prep = s.prepare_request(r)634 assert prep.hooks['response'] == [hook1]635636 def test_prepared_request_hook(self, httpbin):637 def hook(resp, **kwargs):638 resp.hook_working = True639 return resp640641 req = requests.Request('GET', httpbin(), hooks={'response': hook})642 prep = req.prepare()643644 s = requests.Session()645 s.proxies = getproxies()646 resp = s.send(prep)647648 assert hasattr(resp, 'hook_working')649650 def test_prepared_from_session(self, httpbin):651 class DummyAuth(requests.auth.AuthBase):652 def __call__(self, r):653 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'654 return r655656 req = requests.Request('GET', httpbin('headers'))657 assert not req.auth658659 s = requests.Session()660 s.auth = DummyAuth()661662 prep = s.prepare_request(req)663 resp = s.send(prep)664665 assert resp.json()['headers'][666 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'667668 def test_prepare_request_with_bytestring_url(self):669 req = requests.Request('GET', b'https://httpbin.org/')670 s = requests.Session()671 prep = s.prepare_request(req)672 assert prep.url == "https://httpbin.org/"673674 def test_links(self):675 r = requests.Response()676 r.headers = {677 'cache-control': 'public, max-age=60, s-maxage=60',678 'connection': 'keep-alive',679 'content-encoding': 'gzip',680 'content-type': 'application/json; charset=utf-8',681 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',682 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',683 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',684 'link': ('<https://api.github.com/users/kennethreitz/repos?'685 'page=2&per_page=10>; rel="next", <https://api.github.'686 'com/users/kennethreitz/repos?page=7&per_page=10>; '687 ' rel="last"'),688 'server': 'GitHub.com',689 'status': '200 OK',690 'vary': 'Accept',691 'x-content-type-options': 'nosniff',692 'x-github-media-type': 'github.beta',693 'x-ratelimit-limit': '60',694 'x-ratelimit-remaining': '57'695 }696 assert r.links['next']['rel'] == 'next'697698 def test_cookie_parameters(self):699 key = 'some_cookie'700 value = 'some_value'701 secure = True702 domain = 'test.com'703 rest = {'HttpOnly': True}704705 jar = requests.cookies.RequestsCookieJar()706 jar.set(key, value, secure=secure, domain=domain, rest=rest)707708 assert len(jar) == 1709 assert 'some_cookie' in jar710711 cookie = list(jar)[0]712 assert cookie.secure == secure713 assert cookie.domain == domain714 assert cookie._rest['HttpOnly'] == rest['HttpOnly']715716 def test_cookie_as_dict_keeps_len(self):717 key = 'some_cookie'718 value = 'some_value'719720 key1 = 'some_cookie1'721 value1 = 'some_value1'722723 jar = requests.cookies.RequestsCookieJar()724 jar.set(key, value)725 jar.set(key1, value1)726727 d1 = dict(jar)728 d2 = dict(jar.iteritems())729 d3 = dict(jar.items())730731 assert len(jar) == 2732 assert len(d1) == 2733 assert len(d2) == 2734 assert len(d3) == 2735736 def test_cookie_as_dict_keeps_items(self):737 key = 'some_cookie'738 value = 'some_value'739740 key1 = 'some_cookie1'741 value1 = 'some_value1'742743 jar = requests.cookies.RequestsCookieJar()744 jar.set(key, value)745 jar.set(key1, value1)746747 d1 = dict(jar)748 d2 = dict(jar.iteritems())749 d3 = dict(jar.items())750751 assert d1['some_cookie'] == 'some_value'752 assert d2['some_cookie'] == 'some_value'753 assert d3['some_cookie1'] == 'some_value1'754755 def test_cookie_as_dict_keys(self):756 key = 'some_cookie'757 value = 'some_value'758759 key1 = 'some_cookie1'760 value1 = 'some_value1'761762 jar = requests.cookies.RequestsCookieJar()763 jar.set(key, value)764 jar.set(key1, value1)765766 keys = jar.keys()767 assert keys == list(keys)768 # make sure one can use keys multiple times769 assert list(keys) == list(keys)770771 def test_cookie_as_dict_values(self):772 key = 'some_cookie'773 value = 'some_value'774775 key1 = 'some_cookie1'776 value1 = 'some_value1'777778 jar = requests.cookies.RequestsCookieJar()779 jar.set(key, value)780 jar.set(key1, value1)781782 values = jar.values()783 assert values == list(values)784 # make sure one can use values multiple times785 assert list(values) == list(values)786787 def test_cookie_as_dict_items(self):788 key = 'some_cookie'789 value = 'some_value'790791 key1 = 'some_cookie1'792 value1 = 'some_value1'793794 jar = requests.cookies.RequestsCookieJar()795 jar.set(key, value)796 jar.set(key1, value1)797798 items = jar.items()799 assert items == list(items)800 # make sure one can use items multiple times801 assert list(items) == list(items)802803 def test_time_elapsed_blank(self, httpbin):804 r = requests.get(httpbin('get'))805 td = r.elapsed806 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)807 * 10**6) / 10**6)808 assert total_seconds > 0.0809810 def test_response_is_iterable(self):811 r = requests.Response()812 io = StringIO.StringIO('abc')813 read_ = io.read814815 def read_mock(amt, decode_content=None):816 return read_(amt)817 setattr(io, 'read', read_mock)818 r.raw = io819 assert next(iter(r))820 io.close()821822 def test_response_decode_unicode(self):823 """824 When called with decode_unicode, Response.iter_content should always825 return unicode.826 """827 r = requests.Response()828 r._content_consumed = True829 r._content = b'the content'830 r.encoding = 'ascii'831832 chunks = r.iter_content(decode_unicode=True)833 assert all(isinstance(chunk, str) for chunk in chunks)834835 # also for streaming836 r = requests.Response()837 r.raw = io.BytesIO(b'the content')838 r.encoding = 'ascii'839 chunks = r.iter_content(decode_unicode=True)840 assert all(isinstance(chunk, str) for chunk in chunks)841842 def test_request_and_response_are_pickleable(self, httpbin):843 r = requests.get(httpbin('get'))844845 # verify we can pickle the original request846 assert pickle.loads(pickle.dumps(r.request))847848 # verify we can pickle the response and that we have access to849 # the original request.850 pr = pickle.loads(pickle.dumps(r))851 assert r.request.url == pr.request.url852 assert r.request.headers == pr.request.headers853854 def test_get_auth_from_url(self):855 url = 'http://user:pass@complex.url.com/path?query=yes'856 assert ('user', 'pass') == requests.utils.get_auth_from_url(url)857858 def test_get_auth_from_url_encoded_spaces(self):859 url = 'http://user:pass%20pass@complex.url.com/path?query=yes'860 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)861862 def test_get_auth_from_url_not_encoded_spaces(self):863 url = 'http://user:pass pass@complex.url.com/path?query=yes'864 assert ('user', 'pass pass') == requests.utils.get_auth_from_url(url)865866 def test_get_auth_from_url_percent_chars(self):867 url = 'http://user%25user:pass@complex.url.com/path?query=yes'868 assert ('user%user', 'pass') == requests.utils.get_auth_from_url(url)869870 def test_get_auth_from_url_encoded_hashes(self):871 url = 'http://user:pass%23pass@complex.url.com/path?query=yes'872 assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)873874 def test_cannot_send_unprepared_requests(self, httpbin):875 r = requests.Request(url=httpbin())876 with pytest.raises(ValueError):877 requests.Session().send(r)878879 def test_http_error(self):880 error = requests.exceptions.HTTPError()881 assert not error.response882 response = requests.Response()883 error = requests.exceptions.HTTPError(response=response)884 assert error.response == response885 error = requests.exceptions.HTTPError('message', response=response)886 assert str(error) == 'message'887 assert error.response == response888889 def test_session_pickling(self, httpbin):890 r = requests.Request('GET', httpbin('get'))891 s = requests.Session()892893 s = pickle.loads(pickle.dumps(s))894 s.proxies = getproxies()895896 r = s.send(r.prepare())897 assert r.status_code == 200898899 def test_fixes_1329(self, httpbin):900 """901 Ensure that header updates are done case-insensitively.902 """903 s = requests.Session()904 s.headers.update({'ACCEPT': 'BOGUS'})905 s.headers.update({'accept': 'application/json'})906 r = s.get(httpbin('get'))907 headers = r.request.headers908 assert headers['accept'] == 'application/json'909 assert headers['Accept'] == 'application/json'910 assert headers['ACCEPT'] == 'application/json'911912 def test_uppercase_scheme_redirect(self, httpbin):913 parts = urlparse(httpbin('html'))914 url = "HTTP://" + parts.netloc + parts.path915 r = requests.get(httpbin('redirect-to'), params={'url': url})916 assert r.status_code == 200917 assert r.url.lower() == url.lower()918919 def test_transport_adapter_ordering(self):920 s = requests.Session()921 order = ['https://', 'http://']922 assert order == list(s.adapters)923 s.mount('http://git', HTTPAdapter())924 s.mount('http://github', HTTPAdapter())925 s.mount('http://github.com', HTTPAdapter())926 s.mount('http://github.com/about/', HTTPAdapter())927 order = [928 'http://github.com/about/',929 'http://github.com',930 'http://github',931 'http://git',932 'https://',933 'http://',934 ]935 assert order == list(s.adapters)936 s.mount('http://gittip', HTTPAdapter())937 s.mount('http://gittip.com', HTTPAdapter())938 s.mount('http://gittip.com/about/', HTTPAdapter())939 order = [940 'http://github.com/about/',941 'http://gittip.com/about/',942 'http://github.com',943 'http://gittip.com',944 'http://github',945 'http://gittip',946 'http://git',947 'https://',948 'http://',949 ]950 assert order == list(s.adapters)951 s2 = requests.Session()952 s2.adapters = {'http://': HTTPAdapter()}953 s2.mount('https://', HTTPAdapter())954 assert 'http://' in s2.adapters955 assert 'https://' in s2.adapters956957 def test_header_remove_is_case_insensitive(self, httpbin):958 # From issue #1321959 s = requests.Session()960 s.headers['foo'] = 'bar'961 r = s.get(httpbin('get'), headers={'FOO': None})962 assert 'foo' not in r.request.headers963964 def test_params_are_merged_case_sensitive(self, httpbin):965 s = requests.Session()966 s.params['foo'] = 'bar'967 r = s.get(httpbin('get'), params={'FOO': 'bar'})968 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}969970 def test_long_authinfo_in_url(self):971 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(972 'E8A3BE87-9E3F-4620-8858-95478E385B5B',973 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',974 'exactly-------------sixty-----------three------------characters',975 )976 r = requests.Request('GET', url).prepare()977 assert r.url == url978979 def test_header_keys_are_native(self, httpbin):980 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}981 r = requests.Request('GET', httpbin('get'), headers=headers)982 p = r.prepare()983984 # This is testing that they are builtin strings. A bit weird, but there985 # we go.986 assert 'unicode' in p.headers.keys()987 assert 'byte' in p.headers.keys()988989 def test_can_send_nonstring_objects_with_files(self, httpbin):990 data = {'a': 0.0}991 files = {'b': 'foo'}992 r = requests.Request('POST', httpbin('post'), data=data, files=files)993 p = r.prepare()994995 assert 'multipart/form-data' in p.headers['Content-Type']996997 def test_can_send_bytes_bytearray_objects_with_files(self, httpbin):998 # Test bytes:999 data = {'a': 'this is a string'}1000 files = {'b': b'foo'}1001 r = requests.Request('POST', httpbin('post'), data=data, files=files)1002 p = r.prepare()1003 assert 'multipart/form-data' in p.headers['Content-Type']1004 # Test bytearrays:1005 files = {'b': bytearray(b'foo')}1006 r = requests.Request('POST', httpbin('post'), data=data, files=files)1007 p = r.prepare()1008 assert 'multipart/form-data' in p.headers['Content-Type']10091010 def test_can_send_file_object_with_non_string_filename(self, httpbin):1011 f = io.BytesIO()1012 f.name = 21013 r = requests.Request('POST', httpbin('post'), files={'f': f})1014 p = r.prepare()10151016 assert 'multipart/form-data' in p.headers['Content-Type']10171018 def test_autoset_header_values_are_native(self, httpbin):1019 data = 'this is a string'1020 length = '16'1021 req = requests.Request('POST', httpbin('post'), data=data)1022 p = req.prepare()10231024 assert p.headers['Content-Length'] == length10251026 def test_nonhttp_schemes_dont_check_URLs(self):1027 test_urls = (1028 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1029 'file:///etc/passwd',1030 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1031 )1032 for test_url in test_urls:1033 req = requests.Request('GET', test_url)1034 preq = req.prepare()1035 assert test_url == preq.url10361037 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1038 r = requests.get(1039 httpbin('redirect-to'),1040 params={'url': 'http://www.google.co.uk'},1041 auth=('user', 'pass'),1042 )1043 assert r.history[0].request.headers['Authorization']1044 assert not r.request.headers.get('Authorization', '')10451046 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1047 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1048 h1 = r.history[0].request.headers['Authorization']1049 h2 = r.request.headers['Authorization']10501051 assert h1 == h210521053 def test_manual_redirect_with_partial_body_read(self, httpbin):1054 s = requests.Session()1055 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1056 assert r1.is_redirect1057 rg = s.resolve_redirects(r1, r1.request, stream=True)10581059 # read only the first eight bytes of the response body,1060 # then follow the redirect1061 r1.iter_content(8)1062 r2 = next(rg)1063 assert r2.is_redirect10641065 # read all of the response via iter_content,1066 # then follow the redirect1067 for _ in r2.iter_content():1068 pass1069 r3 = next(rg)1070 assert not r3.is_redirect10711072 def _patch_adapter_gzipped_redirect(self, session, url):1073 adapter = session.get_adapter(url=url)1074 org_build_response = adapter.build_response1075 self._patched_response = False10761077 def build_response(*args, **kwargs):1078 resp = org_build_response(*args, **kwargs)1079 if not self._patched_response:1080 resp.raw.headers['content-encoding'] = 'gzip'1081 self._patched_response = True1082 return resp10831084 adapter.build_response = build_response10851086 def test_redirect_with_wrong_gzipped_header(self, httpbin):1087 s = requests.Session()1088 url = httpbin('redirect/1')1089 self._patch_adapter_gzipped_redirect(s, url)1090 s.get(url)10911092 def test_basic_auth_str_is_always_native(self):1093 s = _basic_auth_str("test", "test")1094 assert isinstance(s, builtin_str)1095 assert s == "Basic dGVzdDp0ZXN0"10961097 def test_requests_history_is_saved(self, httpbin):1098 r = requests.get(httpbin('redirect/5'))1099 total = r.history[-1].history1100 i = 01101 for item in r.history:1102 assert item.history == total[0:i]1103 i += 111041105 def test_json_param_post_content_type_works(self, httpbin):1106 r = requests.post(1107 httpbin('post'),1108 json={'life': 42}1109 )1110 assert r.status_code == 2001111 assert 'application/json' in r.request.headers['Content-Type']1112 assert {'life': 42} == r.json()['json']11131114 def test_json_param_post_should_not_override_data_param(self, httpbin):1115 r = requests.Request(method='POST', url=httpbin('post'),1116 data={'stuff': 'elixr'},1117 json={'music': 'flute'})1118 prep = r.prepare()1119 assert 'stuff=elixr' == prep.body11201121 def test_response_iter_lines(self, httpbin):1122 r = requests.get(httpbin('stream/4'), stream=True)1123 assert r.status_code == 20011241125 it = r.iter_lines()1126 next(it)1127 assert len(list(it)) == 311281129 def test_unconsumed_session_response_closes_connection(self, httpbin):1130 s = requests.session()11311132 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1133 pass11341135 assert response._content_consumed is False1136 assert response.raw.closed11371138 @pytest.mark.xfail1139 def test_response_iter_lines_reentrant(self, httpbin):1140 """Response.iter_lines() is not reentrant safe"""1141 r = requests.get(httpbin('stream/4'), stream=True)1142 assert r.status_code == 20011431144 next(r.iter_lines())1145 assert len(list(r.iter_lines())) == 3114611471148class TestContentEncodingDetection:11491150 def test_none(self):1151 encodings = requests.utils.get_encodings_from_content('')1152 assert not len(encodings)11531154 @pytest.mark.parametrize(1155 'content', (1156 # HTML5 meta charset attribute1157 '<meta charset="UTF-8">',1158 # HTML4 pragma directive1159 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',1160 # XHTML 1.x served with text/html MIME type1161 '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',1162 # XHTML 1.x served as XML1163 '<?xml version="1.0" encoding="UTF-8"?>',1164 )1165 )1166 def test_pragmas(self, content):1167 encodings = requests.utils.get_encodings_from_content(content)1168 assert len(encodings) == 11169 assert encodings[0] == 'UTF-8'11701171 def test_precedence(self):1172 content = '''1173 <?xml version="1.0" encoding="XML"?>1174 <meta charset="HTML5">1175 <meta http-equiv="Content-type" content="text/html;charset=HTML4" />1176 '''.strip()1177 encodings = requests.utils.get_encodings_from_content(content)1178 assert encodings == ['HTML5', 'HTML4', 'XML']117911801181class TestCaseInsensitiveDict:11821183 @pytest.mark.parametrize('cid',1184 (1185 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1186 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1187 CaseInsensitiveDict(FOO='foo', BAr='bar'),1188 )1189 )1190 def test_init(self, cid):1191 assert len(cid) == 21192 assert 'foo' in cid1193 assert 'bar' in cid11941195 def test_docstring_example(self):1196 cid = CaseInsensitiveDict()1197 cid['Accept'] = 'application/json'1198 assert cid['aCCEPT'] == 'application/json'1199 assert list(cid) == ['Accept']12001201 def test_len(self):1202 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1203 cid['A'] = 'a'1204 assert len(cid) == 212051206 def test_getitem(self):1207 cid = CaseInsensitiveDict({'Spam': 'blueval'})1208 assert cid['spam'] == 'blueval'1209 assert cid['SPAM'] == 'blueval'12101211 def test_fixes_649(self):1212 """__setitem__ should behave case-insensitively."""1213 cid = CaseInsensitiveDict()1214 cid['spam'] = 'oneval'1215 cid['Spam'] = 'twoval'1216 cid['sPAM'] = 'redval'1217 cid['SPAM'] = 'blueval'1218 assert cid['spam'] == 'blueval'1219 assert cid['SPAM'] == 'blueval'1220 assert list(cid.keys()) == ['SPAM']12211222 def test_delitem(self):1223 cid = CaseInsensitiveDict()1224 cid['Spam'] = 'someval'1225 del cid['sPam']1226 assert 'spam' not in cid1227 assert len(cid) == 012281229 def test_contains(self):1230 cid = CaseInsensitiveDict()1231 cid['Spam'] = 'someval'1232 assert 'Spam' in cid1233 assert 'spam' in cid1234 assert 'SPAM' in cid1235 assert 'sPam' in cid1236 assert 'notspam' not in cid12371238 def test_get(self):1239 cid = CaseInsensitiveDict()1240 cid['spam'] = 'oneval'1241 cid['SPAM'] = 'blueval'1242 assert cid.get('spam') == 'blueval'1243 assert cid.get('SPAM') == 'blueval'1244 assert cid.get('sPam') == 'blueval'1245 assert cid.get('notspam', 'default') == 'default'12461247 def test_update(self):1248 cid = CaseInsensitiveDict()1249 cid['spam'] = 'blueval'1250 cid.update({'sPam': 'notblueval'})1251 assert cid['spam'] == 'notblueval'1252 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1253 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1254 assert len(cid) == 21255 assert cid['foo'] == 'anotherfoo'1256 assert cid['bar'] == 'anotherbar'12571258 def test_update_retains_unchanged(self):1259 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1260 cid.update({'foo': 'newfoo'})1261 assert cid['bar'] == 'bar'12621263 def test_iter(self):1264 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1265 keys = frozenset(['Spam', 'Eggs'])1266 assert frozenset(iter(cid)) == keys12671268 def test_equality(self):1269 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1270 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1271 assert cid == othercid1272 del othercid['spam']1273 assert cid != othercid1274 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1275 assert cid != object()12761277 def test_setdefault(self):1278 cid = CaseInsensitiveDict({'Spam': 'blueval'})1279 assert cid.setdefault('spam', 'notblueval') == 'blueval'1280 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'12811282 def test_lower_items(self):1283 cid = CaseInsensitiveDict({1284 'Accept': 'application/json',1285 'user-Agent': 'requests',1286 })1287 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1288 lowerkeyset = frozenset(['accept', 'user-agent'])1289 assert keyset == lowerkeyset12901291 def test_preserve_key_case(self):1292 cid = CaseInsensitiveDict({1293 'Accept': 'application/json',1294 'user-Agent': 'requests',1295 })1296 keyset = frozenset(['Accept', 'user-Agent'])1297 assert frozenset(i[0] for i in cid.items()) == keyset1298 assert frozenset(cid.keys()) == keyset1299 assert frozenset(cid) == keyset13001301 def test_preserve_last_key_case(self):1302 cid = CaseInsensitiveDict({1303 'Accept': 'application/json',1304 'user-Agent': 'requests',1305 })1306 cid.update({'ACCEPT': 'application/json'})1307 cid['USER-AGENT'] = 'requests'1308 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1309 assert frozenset(i[0] for i in cid.items()) == keyset1310 assert frozenset(cid.keys()) == keyset1311 assert frozenset(cid) == keyset13121313 def test_copy(self):1314 cid = CaseInsensitiveDict({1315 'Accept': 'application/json',1316 'user-Agent': 'requests',1317 })1318 cid_copy = cid.copy()1319 assert cid == cid_copy1320 cid['changed'] = True1321 assert cid != cid_copy132213231324class TestUtils:13251326 def test_super_len_io_streams(self):1327 """ Ensures that we properly deal with different kinds of IO streams. """1328 # uses StringIO or io.StringIO (see import above)1329 from io import BytesIO1330 from requests.utils import super_len13311332 assert super_len(StringIO.StringIO()) == 01333 assert super_len(1334 StringIO.StringIO('with so much drama in the LBC')) == 2913351336 assert super_len(BytesIO()) == 01337 assert super_len(1338 BytesIO(b"it's kinda hard bein' snoop d-o-double-g")) == 4013391340 try:1341 import cStringIO1342 except ImportError:1343 pass1344 else:1345 assert super_len(1346 cStringIO.StringIO('but some how, some way...')) == 2513471348 def test_super_len_correctly_calculates_len_of_partially_read_file(self):1349 """Ensure that we handle partially consumed file like objects."""1350 from requests.utils import super_len1351 s = StringIO.StringIO()1352 s.write('foobarbogus')1353 assert super_len(s) == 013541355 def test_get_environ_proxies_ip_ranges(self):1356 """Ensures that IP addresses are correctly matches with ranges1357 in no_proxy variable."""1358 from requests.utils import get_environ_proxies1359 os.environ['no_proxy'] = "192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1"1360 assert get_environ_proxies('http://192.168.0.1:5000/') == {}1361 assert get_environ_proxies('http://192.168.0.1/') == {}1362 assert get_environ_proxies('http://172.16.1.1/') == {}1363 assert get_environ_proxies('http://172.16.1.1:5000/') == {}1364 assert get_environ_proxies('http://192.168.1.1:5000/') != {}1365 assert get_environ_proxies('http://192.168.1.1/') != {}13661367 def test_get_environ_proxies(self):1368 """Ensures that IP addresses are correctly matches with ranges1369 in no_proxy variable."""1370 from requests.utils import get_environ_proxies1371 os.environ['no_proxy'] = "127.0.0.1,localhost.localdomain,192.168.0.0/24,172.16.1.1"1372 assert get_environ_proxies(1373 'http://localhost.localdomain:5000/v1.0/') == {}1374 assert get_environ_proxies('http://www.requests.com/') != {}13751376 def test_select_proxies(self):1377 """Make sure we can select per-host proxies correctly."""1378 from requests.utils import select_proxy1379 proxies = {'http': 'http://http.proxy',1380 'http://some.host': 'http://some.host.proxy'}1381 assert select_proxy('hTTp://u:p@Some.Host/path', proxies) == 'http://some.host.proxy'1382 assert select_proxy('hTTp://u:p@Other.Host/path', proxies) == 'http://http.proxy'1383 assert select_proxy('hTTps://Other.Host', proxies) is None13841385 def test_guess_filename_when_int(self):1386 from requests.utils import guess_filename1387 assert None is guess_filename(1)13881389 def test_guess_filename_when_filename_is_an_int(self):1390 from requests.utils import guess_filename1391 fake = type('Fake', (object,), {'name': 1})()1392 assert None is guess_filename(fake)13931394 def test_guess_filename_with_file_like_obj(self):1395 from requests.utils import guess_filename1396 from requests import compat1397 fake = type('Fake', (object,), {'name': b'value'})()1398 guessed_name = guess_filename(fake)1399 assert b'value' == guessed_name1400 assert isinstance(guessed_name, compat.bytes)14011402 def test_guess_filename_with_unicode_name(self):1403 from requests.utils import guess_filename1404 from requests import compat1405 filename = b'value'.decode('utf-8')1406 fake = type('Fake', (object,), {'name': filename})()1407 guessed_name = guess_filename(fake)1408 assert filename == guessed_name1409 assert isinstance(guessed_name, compat.str)14101411 def test_is_ipv4_address(self):1412 from requests.utils import is_ipv4_address1413 assert is_ipv4_address('8.8.8.8')1414 assert not is_ipv4_address('8.8.8.8.8')1415 assert not is_ipv4_address('localhost.localdomain')14161417 def test_is_valid_cidr(self):1418 from requests.utils import is_valid_cidr1419 assert not is_valid_cidr('8.8.8.8')1420 assert is_valid_cidr('192.168.1.0/24')14211422 def test_dotted_netmask(self):1423 from requests.utils import dotted_netmask1424 assert dotted_netmask(8) == '255.0.0.0'1425 assert dotted_netmask(24) == '255.255.255.0'1426 assert dotted_netmask(25) == '255.255.255.128'14271428 def test_address_in_network(self):1429 from requests.utils import address_in_network1430 assert address_in_network('192.168.1.1', '192.168.1.0/24')1431 assert not address_in_network('172.16.0.1', '192.168.1.0/24')14321433 def test_get_auth_from_url(self):1434 """Ensures that username and password in well-encoded URI as per1435 RFC 3986 are correctly extracted."""1436 from requests.utils import get_auth_from_url1437 from requests.compat import quote1438 percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1439 url_address = "request.com/url.html#test"1440 url = "http://" + quote(1441 percent_encoding_test_chars, '') + ':' + quote(1442 percent_encoding_test_chars, '') + '@' + url_address1443 (username, password) = get_auth_from_url(url)1444 assert username == percent_encoding_test_chars1445 assert password == percent_encoding_test_chars14461447 def test_requote_uri_with_unquoted_percents(self):1448 """Ensure we handle unquoted percent signs in redirects.14491450 See: https://github.com/kennethreitz/requests/issues/23561451 """1452 from requests.utils import requote_uri1453 bad_uri = 'http://example.com/fiz?buz=%ppicture'1454 quoted = 'http://example.com/fiz?buz=%25ppicture'1455 assert quoted == requote_uri(bad_uri)14561457 def test_requote_uri_properly_requotes(self):1458 """Ensure requoting doesn't break expectations."""1459 from requests.utils import requote_uri1460 quoted = 'http://example.com/fiz?buz=%25ppicture'1461 assert quoted == requote_uri(quoted)146214631464class TestMorselToCookieExpires:1465 """Tests for morsel_to_cookie when morsel contains expires."""14661467 def test_expires_valid_str(self):1468 """Test case where we convert expires from string time."""14691470 morsel = Morsel()1471 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1472 cookie = morsel_to_cookie(morsel)1473 assert cookie.expires == 114741475 @pytest.mark.parametrize('value, exception',1476 (1477 (100, TypeError),1478 ('woops', ValueError),1479 )1480 )1481 def test_expires_invalid_int(self, value, exception):1482 """Test case where an invalid type is passed for expires."""1483 morsel = Morsel()1484 morsel['expires'] = value1485 with pytest.raises(exception):1486 morsel_to_cookie(morsel)14871488 def test_expires_none(self):1489 """Test case where expires is None."""14901491 morsel = Morsel()1492 morsel['expires'] = None1493 cookie = morsel_to_cookie(morsel)1494 assert cookie.expires is None149514961497class TestMorselToCookieMaxAge:14981499 """Tests for morsel_to_cookie when morsel contains max-age."""15001501 def test_max_age_valid_int(self):1502 """Test case where a valid max age in seconds is passed."""15031504 morsel = Morsel()1505 morsel['max-age'] = 601506 cookie = morsel_to_cookie(morsel)1507 assert isinstance(cookie.expires, int)15081509 def test_max_age_invalid_str(self):1510 """Test case where a invalid max age is passed."""15111512 morsel = Morsel()1513 morsel['max-age'] = 'woops'1514 with pytest.raises(TypeError):1515 morsel_to_cookie(morsel)151615171518class TestTimeout:1519 def test_stream_timeout(self, httpbin):1520 try:1521 requests.get(httpbin('delay/10'), timeout=2.0)1522 except requests.exceptions.Timeout as e:1523 assert 'Read timed out' in e.args[0].args[0]15241525 def test_invalid_timeout(self, httpbin):1526 with pytest.raises(ValueError) as e:1527 requests.get(httpbin('get'), timeout=(3, 4, 5))1528 assert '(connect, read)' in str(e)15291530 with pytest.raises(ValueError) as e:1531 requests.get(httpbin('get'), timeout="foo")1532 assert 'must be an int or float' in str(e)15331534 def test_none_timeout(self, httpbin):1535 """ Check that you can set None as a valid timeout value.15361537 To actually test this behavior, we'd want to check that setting the1538 timeout to None actually lets the request block past the system default1539 timeout. However, this would make the test suite unbearably slow.1540 Instead we verify that setting the timeout to None does not prevent the1541 request from succeeding.1542 """1543 r = requests.get(httpbin('get'), timeout=None)1544 assert r.status_code == 20015451546 def test_read_timeout(self, httpbin):1547 try:1548 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1549 pytest.fail('The recv() request should time out.')1550 except ReadTimeout:1551 pass15521553 def test_connect_timeout(self):1554 try:1555 requests.get(TARPIT, timeout=(0.1, None))1556 pytest.fail('The connect() request should time out.')1557 except ConnectTimeout as e:1558 assert isinstance(e, ConnectionError)1559 assert isinstance(e, Timeout)15601561 def test_total_timeout_connect(self):1562 try:1563 requests.get(TARPIT, timeout=(0.1, 0.1))1564 pytest.fail('The connect() request should time out.')1565 except ConnectTimeout:1566 pass15671568 def test_encoded_methods(self, httpbin):1569 """See: https://github.com/kennethreitz/requests/issues/2316"""1570 r = requests.request(b'GET', httpbin('get'))1571 assert r.ok157215731574SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))157515761577class RedirectSession(SessionRedirectMixin):1578 def __init__(self, order_of_redirects):1579 self.redirects = order_of_redirects1580 self.calls = []1581 self.max_redirects = 301582 self.cookies = {}1583 self.trust_env = False15841585 def send(self, *args, **kwargs):1586 self.calls.append(SendCall(args, kwargs))1587 return self.build_response()15881589 def build_response(self):1590 request = self.calls[-1].args[0]1591 r = requests.Response()15921593 try:1594 r.status_code = int(self.redirects.pop(0))1595 except IndexError:1596 r.status_code = 20015971598 r.headers = CaseInsensitiveDict({'Location': '/'})1599 r.raw = self._build_raw()1600 r.request = request1601 return r16021603 def _build_raw(self):1604 string = StringIO.StringIO('')1605 setattr(string, 'release_conn', lambda *args: args)1606 return string160716081609class TestRedirects:1610 default_keyword_args = {1611 'stream': False,1612 'verify': True,1613 'cert': None,1614 'timeout': None,1615 'allow_redirects': False,1616 'proxies': {},1617 }16181619 def test_requests_are_updated_each_time(self, httpbin):1620 session = RedirectSession([303, 307])1621 prep = requests.Request('POST', httpbin('post')).prepare()1622 r0 = session.send(prep)1623 assert r0.request.method == 'POST'1624 assert session.calls[-1] == SendCall((r0.request,), {})1625 redirect_generator = session.resolve_redirects(r0, prep)1626 for response in redirect_generator:1627 assert response.request.method == 'GET'1628 send_call = SendCall((response.request,),1629 TestRedirects.default_keyword_args)1630 assert session.calls[-1] == send_call163116321633@pytest.fixture1634def list_of_tuples():1635 return [1636 (('a', 'b'), ('c', 'd')),1637 (('c', 'd'), ('a', 'b')),1638 (('a', 'b'), ('c', 'd'), ('e', 'f')),1639 ]164016411642def test_data_argument_accepts_tuples(list_of_tuples):1643 """Ensure that the data argument will accept tuples of strings1644 and properly encode them.1645 """1646 for data in list_of_tuples:1647 p = PreparedRequest()1648 p.prepare(1649 method='GET',1650 url='http://www.example.com',1651 data=data,1652 hooks=default_hooks()1653 )1654 assert p.body == urlencode(data)165516561657def assert_copy(p, p_copy):1658 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1659 assert getattr(p, attr) == getattr(p_copy, attr)166016611662def test_prepared_request_empty_copy():1663 p = PreparedRequest()1664 assert_copy(p, p.copy())166516661667def test_prepared_request_no_cookies_copy():1668 p = PreparedRequest()1669 p.prepare(1670 method='GET',1671 url='http://www.example.com',1672 data='foo=bar',1673 hooks=default_hooks()1674 )1675 assert_copy(p, p.copy())167616771678def test_prepared_request_complete_copy():1679 p = PreparedRequest()1680 p.prepare(1681 method='GET',1682 url='http://www.example.com',1683 data='foo=bar',1684 hooks=default_hooks(),1685 cookies={'foo': 'bar'}1686 )1687 assert_copy(p, p.copy())168816891690def test_prepare_unicode_url():1691 p = PreparedRequest()1692 p.prepare(1693 method='GET',1694 url=u('http://www.example.com/üniçø∂é'),1695 )1696 assert_copy(p, p.copy())169716981699def test_urllib3_retries(httpbin):1700 from requests.packages.urllib3.util import Retry1701 s = requests.Session()1702 s.mount('http://', HTTPAdapter(max_retries=Retry(1703 total=2, status_forcelist=[500]1704 )))17051706 with pytest.raises(RetryError):1707 s.get(httpbin('status/500'))170817091710def test_urllib3_pool_connection_closed(httpbin):1711 s = requests.Session()1712 s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))17131714 try:1715 s.get(httpbin('status/200'))1716 except ConnectionError as e:1717 assert u"Pool is closed." in str(e)171817191720def test_vendor_aliases():1721 from requests.packages import urllib31722 from requests.packages import chardet17231724 with pytest.raises(ImportError):1725 from requests.packages import webbrowser