test_requests.py
This file
Path
test_requests.py
349 lines · 11.1 KiB · Python
Last changed by
Merge pull request #1119 from Lukasa/diagsKenneth Reitzbefore adoption90cd37f
History of this fileTake it
basic testKenneth Reitzbefore adoption82cce02
lines 1–5why, one step back1#!/usr/bin/env python2# -*- coding: utf-8 -*-34"""Tests for Requests."""5Merge pull request #1151 from sigmavirus24/fix1133Kenneth Reitzbefore adoption9fc7059
line 6why, one step back6from __future__ import divisionMerge pull request #1024 from etscrivner/masterKenneth Reitzbefore adoption5c4aa0b
line 7why, one step back7import jsonbasic testsKenneth Reitzbefore adoption73ed0d0
line 8why, one step back8import osbasic testKenneth Reitzbefore adoption82cce02
lines 9–11why, one step back9import unittest1011import requestsnew tests!Kenneth Reitzbefore adoption0569fe4
line 12why, one step back12from requests.auth import HTTPDigestAuthMerge pull request #1116 from Lukasa/masterKenneth Reitzbefore adoption30573b2
line 13why, one step back13from requests.compat import strbasic testKenneth Reitzbefore adoption82cce02
line 14why, one step back14Merge pull request #1116 from Lukasa/masterKenneth Reitzbefore adoption30573b2
lines 15–19why, one step back15try:16 import StringIO17except ImportError:18 import io as StringIO19new tests!Kenneth Reitzbefore adoption0569fe4
line 20why, one step back20HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')basic testKenneth Reitzbefore adoption82cce02
line 21why, one step back21Merge pull request #1146 from oczkers/masterKenneth Reitzbefore adoption25545b3
line 22why, one step back22new tests!Kenneth Reitzbefore adoption0569fe4
lines 23–26why, one step back23def httpbin(*suffix):24 """Returns url for HTTPBIN resource."""25 return HTTPBIN + '/'.join(suffix)26Merge pull request #1146 from oczkers/masterKenneth Reitzbefore adoption25545b3
line 27why, one step back27basic testKenneth Reitzbefore adoption82cce02
lines 28–29why, one step back28class RequestsTestCase(unittest.TestCase):29basic testsKenneth Reitzbefore adoption73ed0d0
lines 30–31why, one step back30 _multiprocess_can_split_ = True31basic testKenneth Reitzbefore adoption82cce02
lines 32–39why, one step back32 def setUp(self):33 """Create simple data set with headers."""34 pass3536 def tearDown(self):37 """Teardown."""38 pass39basic testsKenneth Reitzbefore adoption73ed0d0
line 40why, one step back40 def test_entry_points(self):basic testKenneth Reitzbefore adoption82cce02
line 41why, one step back41basic testsKenneth Reitzbefore adoption73ed0d0
lines 42–49why, one step back42 requests.session43 requests.session().get44 requests.session().head45 requests.get46 requests.head47 requests.put48 requests.patch49 requests.postbasic testKenneth Reitzbefore adoption82cce02
line 50why, one step back50basic testsKenneth Reitzbefore adoption73ed0d0
lines 51–62why, one step back51 def test_invalid_url(self):52 self.assertRaises(ValueError, requests.get, 'hiwpefhipowhefopw')5354 def test_basic_building(self):55 req = requests.Request()56 req.url = 'http://kennethreitz.org/'57 req.data = {'life': '42'}5859 pr = req.prepare()60 assert pr.url == req.url61 assert pr.body == 'life=42'62Merge pull request #1142 from theaeolianmachine/removeGETContentLengthKenneth Reitzbefore adoptionc50f8f7
lines 63–68why, one step back63 def test_no_content_length(self):64 get_req = requests.Request('GET', httpbin('get')).prepare()65 self.assertTrue('Content-Length' not in get_req.headers)66 head_req = requests.Request('HEAD', httpbin('head')).prepare()67 self.assertTrue('Content-Length' not in head_req.headers)68basic testsKenneth Reitzbefore adoption73ed0d0
lines 69–82why, one step back69 def test_path_is_not_double_encoded(self):70 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()7172 self.assertEqual(request.path_url, "/get/test%20case")7374 def test_params_are_added_before_fragment(self):75 request = requests.Request('GET',76 "http://example.com/path#fragment", params={"a": "b"}).prepare()77 self.assertEqual(request.url,78 "http://example.com/path?a=b#fragment")79 request = requests.Request('GET',80 "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()81 self.assertEqual(request.url,82 "http://example.com/path?key=value&a=b#fragment")new tests!Kenneth Reitzbefore adoption0569fe4
lines 83–95why, one step back8384 def test_HTTP_200_OK_GET_ALTERNATIVE(self):85 r = requests.Request('GET', httpbin('get'))86 s = requests.Session()8788 r = s.send(r.prepare())8990 self.assertEqual(r.status_code, 200)9192 def test_HTTP_302_ALLOW_REDIRECT_GET(self):93 r = requests.get(httpbin('redirect', '1'))94 self.assertEqual(r.status_code, 200)95test cleanupKenneth Reitzbefore adoption4a5b5bc
lines 96–98why, one step back96 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):97 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})98 # self.assertEqual(r.status_code, 200)Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoptionfcccc82
line 99why, one step back99new tests!Kenneth Reitzbefore adoption0569fe4
lines 100–116why, one step back100 def test_HTTP_200_OK_GET_WITH_PARAMS(self):101 heads = {'User-agent': 'Mozilla/5.0'}102103 r = requests.get(httpbin('user-agent'), headers=heads)104105 self.assertTrue(heads['User-agent'] in r.text)106 self.assertEqual(r.status_code, 200)107108 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):109 heads = {'User-agent': 'Mozilla/5.0'}110111 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)112 self.assertEqual(r.status_code, 200)113114 def test_user_agent_transfers(self):115116 heads = {Merge pull request #1146 from oczkers/masterKenneth Reitzbefore adoption25545b3
line 117why, one step back117 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'new tests!Kenneth Reitzbefore adoption0569fe4
lines 118–123why, one step back118 }119120 r = requests.get(httpbin('user-agent'), headers=heads)121 self.assertTrue(heads['User-agent'] in r.text)122123 heads = {Merge pull request #1146 from oczkers/masterKenneth Reitzbefore adoption25545b3
line 124why, one step back124 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'new tests!Kenneth Reitzbefore adoption0569fe4
lines 125–192why, one step back125 }126127 r = requests.get(httpbin('user-agent'), headers=heads)128 self.assertTrue(heads['user-agent'] in r.text)129130 def test_HTTP_200_OK_HEAD(self):131 r = requests.head(httpbin('get'))132 self.assertEqual(r.status_code, 200)133134 def test_HTTP_200_OK_PUT(self):135 r = requests.put(httpbin('put'))136 self.assertEqual(r.status_code, 200)137138 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):139 auth = ('user', 'pass')140 url = httpbin('basic-auth', 'user', 'pass')141142 r = requests.get(url, auth=auth)143 self.assertEqual(r.status_code, 200)144145 r = requests.get(url)146 self.assertEqual(r.status_code, 401)147148 s = requests.session()149 s.auth = auth150 r = s.get(url)151 self.assertEqual(r.status_code, 200)152153 def test_DIGEST_HTTP_200_OK_GET(self):154155 auth = HTTPDigestAuth('user', 'pass')156 url = httpbin('digest-auth', 'auth', 'user', 'pass')157158 r = requests.get(url, auth=auth)159 self.assertEqual(r.status_code, 200)160161 r = requests.get(url)162 self.assertEqual(r.status_code, 401)163164 s = requests.session()165 s.auth = auth166 r = s.get(url)167 self.assertEqual(r.status_code, 200)168169 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):170171 auth = HTTPDigestAuth('user', 'wrongpass')172 url = httpbin('digest-auth', 'auth', 'user', 'pass')173174 r = requests.get(url, auth=auth)175 self.assertEqual(r.status_code, 401)176177 r = requests.get(url)178 self.assertEqual(r.status_code, 401)179180 s = requests.session()181 s.auth = auth182 r = s.get(url)183 self.assertEqual(r.status_code, 401)184185 def test_POSTBIN_GET_POST_FILES(self):186187 url = httpbin('post')188 post1 = requests.post(url).raise_for_status()189190 post1 = requests.post(url, data={'some': 'data'})191 self.assertEqual(post1.status_code, 200)192remove chardetKenneth Reitzbefore adoption480a382
line 193why, one step back193 with open('requirements.txt') as f:new tests!Kenneth Reitzbefore adoption0569fe4
lines 194–212why, one step back194 post2 = requests.post(url, files={'some': f})195 self.assertEqual(post2.status_code, 200)196197 post4 = requests.post(url, data='[{"some": "json"}]')198 self.assertEqual(post4.status_code, 200)199200 try:201 requests.post(url, files=['bad file data'])202 except ValueError:203 pass204205 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):206207 url = httpbin('post')208 post1 = requests.post(url).raise_for_status()209210 post1 = requests.post(url, data={'some': 'data'})211 self.assertEqual(post1.status_code, 200)212remove chardetKenneth Reitzbefore adoption480a382
line 213why, one step back213 with open('requirements.txt') as f:new tests!Kenneth Reitzbefore adoption0569fe4
lines 214–223why, one step back214 post2 = requests.post(url, data={'some': 'data'}, files={'some': f})215 self.assertEqual(post2.status_code, 200)216217 post4 = requests.post(url, data='[{"some": "json"}]')218 self.assertEqual(post4.status_code, 200)219220 try:221 requests.post(url, files=['bad file data'])222 except ValueError:223 passremove chardetKenneth Reitzbefore adoption480a382
lines 224–252why, one step back224225 def test_request_ok_set(self):226 r = requests.get(httpbin('status', '404'))227 self.assertEqual(r.ok, False)228229 def test_status_raising(self):230 r = requests.get(httpbin('status', '404'))231 self.assertRaises(requests.exceptions.HTTPError, r.raise_for_status)232233 r = requests.get(httpbin('status', '500'))234 self.assertFalse(r.ok)235236 def test_decompress_gzip(self):237 r = requests.get(httpbin('gzip'))238 r.content.decode('ascii')239240 def test_unicode_get(self):241 url = httpbin('/get')242 requests.get(url, params={'foo': 'føø'})243 requests.get(url, params={'føø': 'føø'})244 requests.get(url, params={'føø': 'føø'})245 requests.get(url, params={'foo': 'foo'})246 requests.get(httpbin('ø'), params={'foo': 'foo'})247248 def test_urlencoded_get_query_multivalued_param(self):249250 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))251 self.assertEqual(r.status_code, 200)252 self.assertEqual(r.url, httpbin('get?test=foo&test=baz'))Merge pull request #1024 from etscrivner/masterKenneth Reitzbefore adoption5c4aa0b
lines 253–259why, one step back253254 def test_different_encodings_dont_break_post(self):255 r = requests.post(httpbin('post'),256 data={'stuff': json.dumps({'a': 123})},257 params={'blah': 'asdf1234'},258 files={'file': ('test_requests.py', open(__file__, 'rb'))})259 self.assertEqual(r.status_code, 200)new tests!Kenneth Reitzbefore adoption0569fe4
line 260why, one step back260Merge remote-tracking branch 'origin/master'Kenneth Reitzbefore adoption1a7c91f
lines 261–268why, one step back261 def test_custom_content_type(self):262 r = requests.post(httpbin('post'),263 data={'stuff': json.dumps({'a': 123})},264 files={'file1': ('test_requests.py', open(__file__, 'rb')),265 'file2': ('test_requests', open(__file__, 'rb'),266 'text/py-content-type')})267 self.assertEqual(r.status_code, 200)268 self.assertTrue(b"text/py-content-type" in r.request.body)new tests!Kenneth Reitzbefore adoption0569fe4
line 269why, one step back269Merge pull request #1099 from sprt/masterKenneth Reitzbefore adoption22623bd
lines 270–282why, one step back270 def test_prepared_request_hook(self):271 def hook(resp):272 resp.hook_working = True273 return resp274275 req = requests.Request('GET', HTTPBIN, hooks={'response': hook})276 prep = req.prepare()277278 s = requests.Session()279 resp = s.send(prep)280281 self.assertTrue(hasattr(resp, 'hook_working'))282Merge pull request #1136 from steveklabnik/test_link_headerKenneth Reitzbefore adoptionb242722
line 283why, one step back283 def test_links(self):Merge pull request #1145 from sigmavirus24/masterKenneth Reitzbefore adoptionac5e680
lines 284–304why, one step back284 r = requests.Response()285 r.headers = {286 'cache-control': 'public, max-age=60, s-maxage=60',287 'connection': 'keep-alive',288 'content-encoding': 'gzip',289 'content-type': 'application/json; charset=utf-8',290 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',291 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',292 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',293 'link': ('<https://api.github.com/users/kennethreitz/repos?'294 'page=2&per_page=10>; rel="next", <https://api.github.'295 'com/users/kennethreitz/repos?page=7&per_page=10>; '296 ' rel="last"'),297 'server': 'GitHub.com',298 'status': '200 OK',299 'vary': 'Accept',300 'x-content-type-options': 'nosniff',301 'x-github-media-type': 'github.beta',302 'x-ratelimit-limit': '60',303 'x-ratelimit-remaining': '57'304 }Merge pull request #1136 from steveklabnik/test_link_headerKenneth Reitzbefore adoptionb242722
lines 305–306why, one step back305 self.assertEqual(r.links['next']['rel'], 'next')306Merge pull request #1140 from ralphbean/cookie-testKenneth Reitzbefore adoptionb6af862
lines 307–323why, one step back307 def test_cookie_parameters(self):308 key = 'some_cookie'309 value = 'some_value'310 secure = True311 domain = 'test.com'312 rest = {'HttpOnly': True}313314 jar = requests.cookies.RequestsCookieJar()315 jar.set(key, value, secure=secure, domain=domain, rest=rest)316317 self.assertEqual(len(jar), 1)318 self.assertTrue('some_cookie' in jar)319320 cookie = list(jar)[0]321 self.assertEqual(cookie.secure, secure)322 self.assertEqual(cookie.domain, domain)323 self.assertEqual(cookie._rest['HttpOnly'], rest['HttpOnly'])basic testsKenneth Reitzbefore adoption73ed0d0
line 324why, one step back324Merge pull request #1138 from clee/masterKenneth Reitzbefore adoptiondfa89e2
lines 325–326why, one step back325 def test_time_elapsed_blank(self):326 r = requests.get(httpbin('get'))Merge pull request #1151 from sigmavirus24/fix1133Kenneth Reitzbefore adoption9fc7059
lines 327–330why, one step back327 td = r.elapsed328 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)329 * 10**6) / 10**6)330 self.assertTrue(total_seconds > 0.0)Merge pull request #1138 from clee/masterKenneth Reitzbefore adoptiondfa89e2
line 331why, one step back331Merge pull request #1143 from Lukasa/masterKenneth Reitzbefore adoption207a274
lines 332–337why, one step back332 def test_response_is_iterable(self):333 r = requests.Response()334 io = StringIO.StringIO('abc')335 r.raw = io336 self.assertTrue(next(iter(r)))337 io.close()Merge pull request #1138 from clee/masterKenneth Reitzbefore adoptiondfa89e2
line 338why, one step back338Merge pull request #1162 from Lukasa/proxy_authKenneth Reitzbefore adoption03f6908
lines 339–343why, one step back339 def test_get_auth_from_url(self):340 url = 'http://user:pass@complex.url.com/path?query=yes'341 self.assertEqual(('user', 'pass'),342 requests.utils.get_auth_from_url(url))343Merge pull request #1119 from Lukasa/diagsKenneth Reitzbefore adoption90cd37f
lines 344–347why, one step back344 def test_cannot_send_unprepared_requests(self):345 r = requests.Request(url=HTTPBIN)346 self.assertRaises(ValueError, requests.Session().send, r)347basic testsKenneth Reitzbefore adoption73ed0d0
lines 348–349why, one step back348if __name__ == '__main__':349 unittest.main()