Skip to content
Myr

test_requests.py

This file

Path

tests/test_requests.py

1,782 lines · 60.5 KiB · Python

Last changed by

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

History of this file

Take it

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1–11why, one step back
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-34"""Tests for Requests."""56from __future__ import division7import json8import os9import pickle10import collections11import contextlib

Test security warnings (#3289)John Vandenbergbefore adoption400d27f

line 12why, one step back
12import warnings

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 13–24why, one step back
13
14import io15import requests16import pytest17from requests.adapters import HTTPAdapter18from requests.auth import HTTPDigestAuth, _basic_auth_str19from requests.compat import (20 Morsel, cookielib, getproxies, str, urlparse,21 builtin_str, OrderedDict)22from requests.cookies import cookiejar_from_dict, morsel_to_cookie23from requests.exceptions import (24 ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,

Merge pull request #3059 from alexanderad/proxy-connection-errorsKenneth Reitzbefore adoption03ed671

line 25why, one step back
25 MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,

Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2

line 26why, one step back
26 ProxyError, InvalidHeader)

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 27–33why, one step back
27from requests.models import PreparedRequest
28from requests.structures import CaseInsensitiveDict29from requests.sessions import SessionRedirectMixin30from requests.models import urlencode31from requests.hooks import default_hooks3233from .compat import StringIO, u

Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9

line 34why, one step back
34from .utils import override_environ

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 35–37why, one step back
35
36# Requests to this URL should always fail with a connection timeout (nothing37# listening on that port)

syntax changesKenneth Reitzbefore adoptionbbadf47

line 38why, one step back
38TARPIT = 'http://10.255.255.1'

Added tests module.Dmitry Dygalobefore adoption18b26d2

line 39why, one step back
39

Test security warnings (#3289)John Vandenbergbefore adoption400d27f

lines 40–45why, one step back
40try:
41 from ssl import SSLContext42 del SSLContext43 HAS_MODERN_SSL = True44except ImportError:45 HAS_MODERN_SSL = False

Added tests module.Dmitry Dygalobefore adoption18b26d2

line 46why, one step back
46

Test security warnings (#3289)John Vandenbergbefore adoption400d27f

lines 47–53why, one step back
47try:
48 requests.pyopenssl49 HAS_PYOPENSSL = True50except AttributeError:51 HAS_PYOPENSSL = False5253

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 54–66why, one step back
54class TestRequests:
5556 def test_entry_points(self):5758 requests.session59 requests.session().get60 requests.session().head61 requests.get62 requests.head63 requests.put64 requests.patch65 requests.post66

syntax changesKenneth Reitzbefore adoptionbbadf47

lines 67–68why, one step back
67 @pytest.mark.parametrize(
68 'exception, url', (

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 69–73why, one step back
69 (MissingSchema, 'hiwpefhipowhefopw'),
70 (InvalidSchema, 'localhost:3128'),71 (InvalidSchema, 'localhost.localdomain:3128/'),72 (InvalidSchema, '10.122.1.1:3128/'),73 (InvalidURL, 'http://'),

syntax changesKenneth Reitzbefore adoptionbbadf47

line 74why, one step back
74 ))

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 75–105why, one step back
75 def test_invalid_url(self, exception, url):
76 with pytest.raises(exception):77 requests.get(url)7879 def test_basic_building(self):80 req = requests.Request()81 req.url = 'http://kennethreitz.org/'82 req.data = {'life': '42'}8384 pr = req.prepare()85 assert pr.url == req.url86 assert pr.body == 'life=42'8788 @pytest.mark.parametrize('method', ('GET', 'HEAD'))89 def test_no_content_length(self, httpbin, method):90 req = requests.Request(method, httpbin(method.lower())).prepare()91 assert 'Content-Length' not in req.headers9293 def test_override_content_length(self, httpbin):94 headers = {95 'Content-Length': 'not zero'96 }97 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()98 assert 'Content-Length' in r.headers99 assert r.headers['Content-Length'] == 'not zero'100101 def test_path_is_not_double_encoded(self):102 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()103104 assert request.path_url == '/get/test%20case'105

syntax changesKenneth Reitzbefore adoptionbbadf47

lines 106–107why, one step back
106 @pytest.mark.parametrize(
107 'url, expected', (

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 108–109why, one step back
108 ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),
109 ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')

syntax changesKenneth Reitzbefore adoptionbbadf47

line 110why, one step back
110 ))

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 111–180why, one step back
111 def test_params_are_added_before_fragment(self, url, expected):
112 request = requests.Request('GET', url, params={"a": "b"}).prepare()113 assert request.url == expected114115 def test_params_original_order_is_preserved_by_default(self):116 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))117 session = requests.Session()118 request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)119 prep = session.prepare_request(request)120 assert prep.url == 'http://example.com/?z=1&a=1&k=1&d=1'121122 def test_params_bytes_are_encoded(self):123 request = requests.Request('GET', 'http://example.com',124 params=b'test=foo').prepare()125 assert request.url == 'http://example.com/?test=foo'126127 def test_binary_put(self):128 request = requests.Request('PUT', 'http://example.com',129 data=u"ööö".encode("utf-8")).prepare()130 assert isinstance(request.body, bytes)131132 @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))133 def test_mixed_case_scheme_acceptable(self, httpbin, scheme):134 s = requests.Session()135 s.proxies = getproxies()136 parts = urlparse(httpbin('get'))137 url = scheme + parts.netloc + parts.path138 r = requests.Request('GET', url)139 r = s.send(r.prepare())140 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)141142 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):143 r = requests.Request('GET', httpbin('get'))144 s = requests.Session()145 s.proxies = getproxies()146147 r = s.send(r.prepare())148149 assert r.status_code == 200150151 def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):152 r = requests.get(httpbin('redirect', '1'))153 assert r.status_code == 200154 assert r.history[0].status_code == 302155 assert r.history[0].is_redirect156157 def test_HTTP_302_TOO_MANY_REDIRECTS(self, httpbin):158 try:159 requests.get(httpbin('relative-redirect', '50'))160 except TooManyRedirects as e:161 url = httpbin('relative-redirect', '20')162 assert e.request.url == url163 assert e.response.url == url164 assert len(e.response.history) == 30165 else:166 pytest.fail('Expected redirect to raise TooManyRedirects but it did not')167168 def test_HTTP_302_TOO_MANY_REDIRECTS_WITH_PARAMS(self, httpbin):169 s = requests.session()170 s.max_redirects = 5171 try:172 s.get(httpbin('relative-redirect', '50'))173 except TooManyRedirects as e:174 url = httpbin('relative-redirect', '45')175 assert e.request.url == url176 assert e.response.url == url177 assert len(e.response.history) == 5178 else:179 pytest.fail('Expected custom max number of redirects to be respected but was not')180

Merge pull request #3060 from benweatherman/masterIan Cordascobefore adoption3acf3a7

lines 181–223why, one step back
181 def test_http_301_changes_post_to_get(self, httpbin):
182 r = requests.post(httpbin('status', '301'))183 assert r.status_code == 200184 assert r.request.method == 'GET'185 assert r.history[0].status_code == 301186 assert r.history[0].is_redirect187188 def test_http_301_doesnt_change_head_to_get(self, httpbin):189 r = requests.head(httpbin('status', '301'), allow_redirects=True)190 print(r.content)191 assert r.status_code == 200192 assert r.request.method == 'HEAD'193 assert r.history[0].status_code == 301194 assert r.history[0].is_redirect195196 def test_http_302_changes_post_to_get(self, httpbin):197 r = requests.post(httpbin('status', '302'))198 assert r.status_code == 200199 assert r.request.method == 'GET'200 assert r.history[0].status_code == 302201 assert r.history[0].is_redirect202203 def test_http_302_doesnt_change_head_to_get(self, httpbin):204 r = requests.head(httpbin('status', '302'), allow_redirects=True)205 assert r.status_code == 200206 assert r.request.method == 'HEAD'207 assert r.history[0].status_code == 302208 assert r.history[0].is_redirect209210 def test_http_303_changes_post_to_get(self, httpbin):211 r = requests.post(httpbin('status', '303'))212 assert r.status_code == 200213 assert r.request.method == 'GET'214 assert r.history[0].status_code == 303215 assert r.history[0].is_redirect216217 def test_http_303_doesnt_change_head_to_get(self, httpbin):218 r = requests.head(httpbin('status', '303'), allow_redirects=True)219 assert r.status_code == 200220 assert r.request.method == 'HEAD'221 assert r.history[0].status_code == 303222 assert r.history[0].is_redirect223

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 224–328why, one step back
224 def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):
225 heads = {'User-agent': 'Mozilla/5.0'}226227 r = requests.get(httpbin('user-agent'), headers=heads)228229 assert heads['User-agent'] in r.text230 assert r.status_code == 200231232 def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):233 heads = {'User-agent': 'Mozilla/5.0'}234235 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)236 assert r.status_code == 200237238 def test_set_cookie_on_301(self, httpbin):239 s = requests.session()240 url = httpbin('cookies/set?foo=bar')241 s.get(url)242 assert s.cookies['foo'] == 'bar'243244 def test_cookie_sent_on_redirect(self, httpbin):245 s = requests.session()246 s.get(httpbin('cookies/set?foo=bar'))247 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')248 assert 'Cookie' in r.json()['headers']249250 def test_cookie_removed_on_expire(self, httpbin):251 s = requests.session()252 s.get(httpbin('cookies/set?foo=bar'))253 assert s.cookies['foo'] == 'bar'254 s.get(255 httpbin('response-headers'),256 params={257 'Set-Cookie':258 'foo=deleted; expires=Thu, 01-Jan-1970 00:00:01 GMT'259 }260 )261 assert 'foo' not in s.cookies262263 def test_cookie_quote_wrapped(self, httpbin):264 s = requests.session()265 s.get(httpbin('cookies/set?foo="bar:baz"'))266 assert s.cookies['foo'] == '"bar:baz"'267268 def test_cookie_persists_via_api(self, httpbin):269 s = requests.session()270 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})271 assert 'foo' in r.request.headers['Cookie']272 assert 'foo' in r.history[0].request.headers['Cookie']273274 def test_request_cookie_overrides_session_cookie(self, httpbin):275 s = requests.session()276 s.cookies['foo'] = 'bar'277 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})278 assert r.json()['cookies']['foo'] == 'baz'279 # Session cookie should not be modified280 assert s.cookies['foo'] == 'bar'281282 def test_request_cookies_not_persisted(self, httpbin):283 s = requests.session()284 s.get(httpbin('cookies'), cookies={'foo': 'baz'})285 # Sending a request with cookies should not add cookies to the session286 assert not s.cookies287288 def test_generic_cookiejar_works(self, httpbin):289 cj = cookielib.CookieJar()290 cookiejar_from_dict({'foo': 'bar'}, cj)291 s = requests.session()292 s.cookies = cj293 r = s.get(httpbin('cookies'))294 # Make sure the cookie was sent295 assert r.json()['cookies']['foo'] == 'bar'296 # Make sure the session cj is still the custom one297 assert s.cookies is cj298299 def test_param_cookiejar_works(self, httpbin):300 cj = cookielib.CookieJar()301 cookiejar_from_dict({'foo': 'bar'}, cj)302 s = requests.session()303 r = s.get(httpbin('cookies'), cookies=cj)304 # Make sure the cookie was sent305 assert r.json()['cookies']['foo'] == 'bar'306307 def test_requests_in_history_are_not_overridden(self, httpbin):308 resp = requests.get(httpbin('redirect/3'))309 urls = [r.url for r in resp.history]310 req_urls = [r.request.url for r in resp.history]311 assert urls == req_urls312313 def test_history_is_always_a_list(self, httpbin):314 """Show that even with redirects, Response.history is always a list."""315 resp = requests.get(httpbin('get'))316 assert isinstance(resp.history, list)317 resp = requests.get(httpbin('redirect/1'))318 assert isinstance(resp.history, list)319 assert not isinstance(resp.history, tuple)320321 def test_headers_on_session_with_None_are_not_sent(self, httpbin):322 """Do not send headers in Session.headers with None values."""323 ses = requests.Session()324 ses.headers['Accept-Encoding'] = None325 req = requests.Request('GET', httpbin('get'))326 prep = ses.prepare_request(req)327 assert 'Accept-Encoding' not in prep.headers328

Merge pull request #3096 from piotrjurkiewicz/masterKenneth Reitzbefore adoptionce5e312

lines 329–348why, one step back
329 def test_headers_preserve_order(self, httpbin):
330 """Preserve order when headers provided as OrderedDict."""331 ses = requests.Session()332 ses.headers = OrderedDict()333 ses.headers['Accept-Encoding'] = 'identity'334 ses.headers['First'] = '1'335 ses.headers['Second'] = '2'336 headers = OrderedDict([('Third', '3'), ('Fourth', '4')])337 headers['Fifth'] = '5'338 headers['Second'] = '222'339 req = requests.Request('GET', httpbin('get'), headers=headers)340 prep = ses.prepare_request(req)341 items = list(prep.headers.items())342 assert items[0] == ('Accept-Encoding', 'identity')343 assert items[1] == ('First', '1')344 assert items[2] == ('Second', '222')345 assert items[3] == ('Third', '3')346 assert items[4] == ('Fourth', '4')347 assert items[5] == ('Fifth', '5')348

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 349–351why, one step back
349 @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))
350 def test_user_agent_transfers(self, httpbin, key):351

syntax changesKenneth Reitzbefore adoptionbbadf47

line 352why, one step back
352 heads = {key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'}

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 353–387why, one step back
353
354 r = requests.get(httpbin('user-agent'), headers=heads)355 assert heads[key] in r.text356357 def test_HTTP_200_OK_HEAD(self, httpbin):358 r = requests.head(httpbin('get'))359 assert r.status_code == 200360361 def test_HTTP_200_OK_PUT(self, httpbin):362 r = requests.put(httpbin('put'))363 assert r.status_code == 200364365 def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):366 auth = ('user', 'pass')367 url = httpbin('basic-auth', 'user', 'pass')368369 r = requests.get(url, auth=auth)370 assert r.status_code == 200371372 r = requests.get(url)373 assert r.status_code == 401374375 s = requests.session()376 s.auth = auth377 r = s.get(url)378 assert r.status_code == 200379380 @pytest.mark.parametrize(381 'url, exception', (382 # Connecting to an unknown domain should raise a ConnectionError383 ('http://doesnotexist.google.com', ConnectionError),384 # Connecting to an invalid port should raise a ConnectionError385 ('http://localhost:1', ConnectionError),386 # Inputing a URL that cannot be parsed should raise an InvalidURL error387 ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)

syntax changesKenneth Reitzbefore adoptionbbadf47

line 388why, one step back
388 ))

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 389–391why, one step back
389 def test_errors(self, url, exception):
390 with pytest.raises(exception):391 requests.get(url, timeout=1)

Merge pull request #3059 from alexanderad/proxy-connection-errorsKenneth Reitzbefore adoption03ed671

lines 392–396why, one step back
392
393 def test_proxy_error(self):394 # any proxy related error (address resolution, no route to host, etc) should result in a ProxyError395 with pytest.raises(ProxyError):396 requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 397–515why, one step back
397
398 def test_basicauth_with_netrc(self, httpbin):399 auth = ('user', 'pass')400 wrong_auth = ('wronguser', 'wrongpass')401 url = httpbin('basic-auth', 'user', 'pass')402403 old_auth = requests.sessions.get_netrc_auth404405 try:406 def get_netrc_auth_mock(url):407 return auth408 requests.sessions.get_netrc_auth = get_netrc_auth_mock409410 # Should use netrc and work.411 r = requests.get(url)412 assert r.status_code == 200413414 # Given auth should override and fail.415 r = requests.get(url, auth=wrong_auth)416 assert r.status_code == 401417418 s = requests.session()419420 # Should use netrc and work.421 r = s.get(url)422 assert r.status_code == 200423424 # Given auth should override and fail.425 s.auth = wrong_auth426 r = s.get(url)427 assert r.status_code == 401428 finally:429 requests.sessions.get_netrc_auth = old_auth430431 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):432433 auth = HTTPDigestAuth('user', 'pass')434 url = httpbin('digest-auth', 'auth', 'user', 'pass')435436 r = requests.get(url, auth=auth)437 assert r.status_code == 200438439 r = requests.get(url)440 assert r.status_code == 401441442 s = requests.session()443 s.auth = HTTPDigestAuth('user', 'pass')444 r = s.get(url)445 assert r.status_code == 200446447 def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):448 url = httpbin('digest-auth', 'auth', 'user', 'pass')449 auth = HTTPDigestAuth('user', 'pass')450 r = requests.get(url)451 assert r.cookies['fake'] == 'fake_value'452453 r = requests.get(url, auth=auth)454 assert r.status_code == 200455456 def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):457 url = httpbin('digest-auth', 'auth', 'user', 'pass')458 auth = HTTPDigestAuth('user', 'pass')459 s = requests.Session()460 s.get(url, auth=auth)461 assert s.cookies['fake'] == 'fake_value'462463 def test_DIGEST_STREAM(self, httpbin):464465 auth = HTTPDigestAuth('user', 'pass')466 url = httpbin('digest-auth', 'auth', 'user', 'pass')467468 r = requests.get(url, auth=auth, stream=True)469 assert r.raw.read() != b''470471 r = requests.get(url, auth=auth, stream=False)472 assert r.raw.read() == b''473474 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):475476 auth = HTTPDigestAuth('user', 'wrongpass')477 url = httpbin('digest-auth', 'auth', 'user', 'pass')478479 r = requests.get(url, auth=auth)480 assert r.status_code == 401481482 r = requests.get(url)483 assert r.status_code == 401484485 s = requests.session()486 s.auth = auth487 r = s.get(url)488 assert r.status_code == 401489490 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):491492 auth = HTTPDigestAuth('user', 'pass')493 url = httpbin('digest-auth', 'auth', 'user', 'pass')494495 r = requests.get(url, auth=auth)496 assert '"auth"' in r.request.headers['Authorization']497498 def test_POSTBIN_GET_POST_FILES(self, httpbin):499500 url = httpbin('post')501 requests.post(url).raise_for_status()502503 post1 = requests.post(url, data={'some': 'data'})504 assert post1.status_code == 200505506 with open('requirements.txt') as f:507 post2 = requests.post(url, files={'some': f})508 assert post2.status_code == 200509510 post4 = requests.post(url, data='[{"some": "json"}]')511 assert post4.status_code == 200512513 with pytest.raises(ValueError):514 requests.post(url, files=['bad file data'])515

Merge pull request #3082 from tzickel/masterIan Cordascobefore adoptione65d6fc

lines 516–557why, one step back
516 def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):
517518 class TestStream(object):519 def __init__(self, data):520 self.data = data.encode()521 self.length = len(self.data)522 self.index = 0523524 def __len__(self):525 return self.length526527 def read(self, size=None):528 if size:529 ret = self.data[self.index:self.index + size]530 self.index += size531 else:532 ret = self.data[self.index:]533 self.index = self.length534 return ret535536 def tell(self):537 return self.index538539 def seek(self, offset, where=0):540 if where == 0:541 self.index = offset542 elif where == 1:543 self.index += offset544 elif where == 2:545 self.index = self.length + offset546547 test = TestStream('test')548 post1 = requests.post(httpbin('post'), data=test)549 assert post1.status_code == 200550 assert post1.json()['data'] == 'test'551552 test = TestStream('test')553 test.seek(2)554 post2 = requests.post(httpbin('post'), data=test)555 assert post2.status_code == 200556 assert post2.json()['data'] == 'st'557

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 558–566why, one step back
558 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):
559560 url = httpbin('post')561 requests.post(url).raise_for_status()562563 post1 = requests.post(url, data={'some': 'data'})564 assert post1.status_code == 200565566 with open('requirements.txt') as f:

Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac

line 567why, one step back
567 post2 = requests.post(url, data={'some': 'data'}, files={'some': f})

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 568–598why, one step back
568 assert post2.status_code == 200
569570 post4 = requests.post(url, data='[{"some": "json"}]')571 assert post4.status_code == 200572573 with pytest.raises(ValueError):574 requests.post(url, files=['bad file data'])575576 def test_conflicting_post_params(self, httpbin):577 url = httpbin('post')578 with open('requirements.txt') as f:579 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")580 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")581582 def test_request_ok_set(self, httpbin):583 r = requests.get(httpbin('status', '404'))584 assert not r.ok585586 def test_status_raising(self, httpbin):587 r = requests.get(httpbin('status', '404'))588 with pytest.raises(requests.exceptions.HTTPError):589 r.raise_for_status()590591 r = requests.get(httpbin('status', '500'))592 assert not r.ok593594 def test_decompress_gzip(self, httpbin):595 r = requests.get(httpbin('gzip'))596 r.content.decode('ascii')597598 @pytest.mark.parametrize(

syntax changesKenneth Reitzbefore adoptionbbadf47

line 599why, one step back
599 'url, params', (

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 600–604why, one step back
600 ('/get', {'foo': 'føø'}),
601 ('/get', {'føø': 'føø'}),602 ('/get', {'føø': 'føø'}),603 ('/get', {'foo': 'foo'}),604 ('ø', {'foo': 'foo'}),

syntax changesKenneth Reitzbefore adoptionbbadf47

line 605why, one step back
605 ))

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 606–616why, one step back
606 def test_unicode_get(self, httpbin, url, params):
607 requests.get(httpbin(url), params=params)608609 def test_unicode_header_name(self, httpbin):610 requests.put(611 httpbin('put'),612 headers={str('Content-Type'): 'application/octet-stream'},613 data='\xff') # compat.str is unicode.614615 def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):616 requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)

Test security warnings (#3289)John Vandenbergbefore adoption400d27f

lines 617–637why, one step back
617
618 def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):619 """warnings are emitted with requests.get"""620 if HAS_MODERN_SSL or HAS_PYOPENSSL:621 warnings_expected = ('SubjectAltNameWarning', )622 else:623 warnings_expected = ('SNIMissingWarning',624 'InsecurePlatformWarning',625 'SubjectAltNameWarning', )626627 with pytest.warns(None) as warning_records:628 warnings.simplefilter('always')629 requests.get(httpbin_secure('status', '200'),630 verify=httpbin_ca_bundle)631632 warning_records = [item for item in warning_records633 if item.category.__name__ != 'ResourceWarning']634635 warnings_category = tuple(636 item.category.__name__ for item in warning_records)637 assert warnings_category == warnings_expected

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 638–657why, one step back
638
639 def test_urlencoded_get_query_multivalued_param(self, httpbin):640641 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))642 assert r.status_code == 200643 assert r.url == httpbin('get?test=foo&test=baz')644645 def test_different_encodings_dont_break_post(self, httpbin):646 r = requests.post(httpbin('post'),647 data={'stuff': json.dumps({'a': 123})},648 params={'blah': 'asdf1234'},649 files={'file': ('test_requests.py', open(__file__, 'rb'))})650 assert r.status_code == 200651652 @pytest.mark.parametrize(653 'data', (654 {'stuff': u('ëlïxr')},655 {'stuff': u('ëlïxr').encode('utf-8')},656 {'stuff': 'elixr'},657 {'stuff': 'elixr'.encode('utf-8')},

syntax changesKenneth Reitzbefore adoptionbbadf47

line 658why, one step back
658 ))

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 659–666why, one step back
659 def test_unicode_multipart_post(self, httpbin, data):
660 r = requests.post(httpbin('post'),661 data=data,662 files={'file': ('test_requests.py', open(__file__, 'rb'))})663 assert r.status_code == 200664665 def test_unicode_multipart_post_fieldnames(self, httpbin):666 filename = os.path.splitext(__file__)[0] + '.py'

syntax changesKenneth Reitzbefore adoptionbbadf47

lines 667–670why, one step back
667 r = requests.Request(
668 method='POST', url=httpbin('post'),669 data={'stuff'.encode('utf-8'): 'elixr'},670 files={'file': ('test_requests.py', open(filename, 'rb'))})

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 671–683why, one step back
671 prep = r.prepare()
672 assert b'name="stuff"' in prep.body673 assert b'name="b\'stuff\'"' not in prep.body674675 def test_unicode_method_name(self, httpbin):676 files = {'file': open(__file__, 'rb')}677 r = requests.request(678 method=u('POST'), url=httpbin('post'), files=files)679 assert r.status_code == 200680681 def test_unicode_method_name_with_request_object(self, httpbin):682 files = {'file': open(__file__, 'rb')}683 s = requests.Session()

syntax changesKenneth Reitzbefore adoptionbbadf47

line 684why, one step back
684 req = requests.Request(u('POST'), httpbin('post'), files=files)

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 685–686why, one step back
685 prep = s.prepare_request(req)
686 assert isinstance(prep.method, builtin_str)

syntax changesKenneth Reitzbefore adoptionbbadf47

line 687why, one step back
687 assert prep.method == 'POST'

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 688–691why, one step back
688
689 resp = s.send(prep)690 assert resp.status_code == 200691

Merge pull request #3108 from kevinburke/flip-conditionalIan Cordascobefore adoptionbbeb000

lines 692–699why, one step back
692 def test_non_prepared_request_error(self):
693 s = requests.Session()694 req = requests.Request(u('POST'), '/')695696 with pytest.raises(ValueError) as e:697 s.send(req)698 assert str(e.value) == 'You can only send PreparedRequests.'699

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 700–703why, one step back
700 def test_custom_content_type(self, httpbin):
701 r = requests.post(702 httpbin('post'),703 data={'stuff': json.dumps({'a': 123})},

syntax changesKenneth Reitzbefore adoptionbbadf47

lines 704–707why, one step back
704 files={
705 'file1': ('test_requests.py', open(__file__, 'rb')),706 'file2': ('test_requests', open(__file__, 'rb'),707 'text/py-content-type')})

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 708–906why, one step back
708 assert r.status_code == 200
709 assert b"text/py-content-type" in r.request.body710711 def test_hook_receives_request_arguments(self, httpbin):712 def hook(resp, **kwargs):713 assert resp is not None714 assert kwargs != {}715716 s = requests.Session()717 r = requests.Request('GET', httpbin(), hooks={'response': hook})718 prep = s.prepare_request(r)719 s.send(prep)720721 def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):722 hook = lambda x, *args, **kwargs: x723 s = requests.Session()724 s.hooks['response'].append(hook)725 r = requests.Request('GET', httpbin())726 prep = s.prepare_request(r)727 assert prep.hooks['response'] != []728 assert prep.hooks['response'] == [hook]729730 def test_session_hooks_are_overridden_by_request_hooks(self, httpbin):731 hook1 = lambda x, *args, **kwargs: x732 hook2 = lambda x, *args, **kwargs: x733 assert hook1 is not hook2734 s = requests.Session()735 s.hooks['response'].append(hook2)736 r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})737 prep = s.prepare_request(r)738 assert prep.hooks['response'] == [hook1]739740 def test_prepared_request_hook(self, httpbin):741 def hook(resp, **kwargs):742 resp.hook_working = True743 return resp744745 req = requests.Request('GET', httpbin(), hooks={'response': hook})746 prep = req.prepare()747748 s = requests.Session()749 s.proxies = getproxies()750 resp = s.send(prep)751752 assert hasattr(resp, 'hook_working')753754 def test_prepared_from_session(self, httpbin):755 class DummyAuth(requests.auth.AuthBase):756 def __call__(self, r):757 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'758 return r759760 req = requests.Request('GET', httpbin('headers'))761 assert not req.auth762763 s = requests.Session()764 s.auth = DummyAuth()765766 prep = s.prepare_request(req)767 resp = s.send(prep)768769 assert resp.json()['headers'][770 'Dummy-Auth-Test'] == 'dummy-auth-test-ok'771772 def test_prepare_request_with_bytestring_url(self):773 req = requests.Request('GET', b'https://httpbin.org/')774 s = requests.Session()775 prep = s.prepare_request(req)776 assert prep.url == "https://httpbin.org/"777778 def test_links(self):779 r = requests.Response()780 r.headers = {781 'cache-control': 'public, max-age=60, s-maxage=60',782 'connection': 'keep-alive',783 'content-encoding': 'gzip',784 'content-type': 'application/json; charset=utf-8',785 'date': 'Sat, 26 Jan 2013 16:47:56 GMT',786 'etag': '"6ff6a73c0e446c1f61614769e3ceb778"',787 'last-modified': 'Sat, 26 Jan 2013 16:22:39 GMT',788 'link': ('<https://api.github.com/users/kennethreitz/repos?'789 'page=2&per_page=10>; rel="next", <https://api.github.'790 'com/users/kennethreitz/repos?page=7&per_page=10>; '791 ' rel="last"'),792 'server': 'GitHub.com',793 'status': '200 OK',794 'vary': 'Accept',795 'x-content-type-options': 'nosniff',796 'x-github-media-type': 'github.beta',797 'x-ratelimit-limit': '60',798 'x-ratelimit-remaining': '57'799 }800 assert r.links['next']['rel'] == 'next'801802 def test_cookie_parameters(self):803 key = 'some_cookie'804 value = 'some_value'805 secure = True806 domain = 'test.com'807 rest = {'HttpOnly': True}808809 jar = requests.cookies.RequestsCookieJar()810 jar.set(key, value, secure=secure, domain=domain, rest=rest)811812 assert len(jar) == 1813 assert 'some_cookie' in jar814815 cookie = list(jar)[0]816 assert cookie.secure == secure817 assert cookie.domain == domain818 assert cookie._rest['HttpOnly'] == rest['HttpOnly']819820 def test_cookie_as_dict_keeps_len(self):821 key = 'some_cookie'822 value = 'some_value'823824 key1 = 'some_cookie1'825 value1 = 'some_value1'826827 jar = requests.cookies.RequestsCookieJar()828 jar.set(key, value)829 jar.set(key1, value1)830831 d1 = dict(jar)832 d2 = dict(jar.iteritems())833 d3 = dict(jar.items())834835 assert len(jar) == 2836 assert len(d1) == 2837 assert len(d2) == 2838 assert len(d3) == 2839840 def test_cookie_as_dict_keeps_items(self):841 key = 'some_cookie'842 value = 'some_value'843844 key1 = 'some_cookie1'845 value1 = 'some_value1'846847 jar = requests.cookies.RequestsCookieJar()848 jar.set(key, value)849 jar.set(key1, value1)850851 d1 = dict(jar)852 d2 = dict(jar.iteritems())853 d3 = dict(jar.items())854855 assert d1['some_cookie'] == 'some_value'856 assert d2['some_cookie'] == 'some_value'857 assert d3['some_cookie1'] == 'some_value1'858859 def test_cookie_as_dict_keys(self):860 key = 'some_cookie'861 value = 'some_value'862863 key1 = 'some_cookie1'864 value1 = 'some_value1'865866 jar = requests.cookies.RequestsCookieJar()867 jar.set(key, value)868 jar.set(key1, value1)869870 keys = jar.keys()871 assert keys == list(keys)872 # make sure one can use keys multiple times873 assert list(keys) == list(keys)874875 def test_cookie_as_dict_values(self):876 key = 'some_cookie'877 value = 'some_value'878879 key1 = 'some_cookie1'880 value1 = 'some_value1'881882 jar = requests.cookies.RequestsCookieJar()883 jar.set(key, value)884 jar.set(key1, value1)885886 values = jar.values()887 assert values == list(values)888 # make sure one can use values multiple times889 assert list(values) == list(values)890891 def test_cookie_as_dict_items(self):892 key = 'some_cookie'893 value = 'some_value'894895 key1 = 'some_cookie1'896 value1 = 'some_value1'897898 jar = requests.cookies.RequestsCookieJar()899 jar.set(key, value)900 jar.set(key1, value1)901902 items = jar.items()903 assert items == list(items)904 # make sure one can use items multiple times905 assert list(items) == list(items)906

Merge pull request #3032 from davidsoncasey/masterCory Benfieldbefore adoption4f378b0

lines 907–938why, one step back
907 def test_cookie_duplicate_names_different_domains(self):
908 key = 'some_cookie'909 value = 'some_value'910 domain1 = 'test1.com'911 domain2 = 'test2.com'912913 jar = requests.cookies.RequestsCookieJar()914 jar.set(key, value, domain=domain1)915 jar.set(key, value, domain=domain2)916 assert key in jar917 items = jar.items()918 assert len(items) == 2919920 # Verify that CookieConflictError is raised if domain is not specified921 with pytest.raises(requests.cookies.CookieConflictError):922 jar.get(key)923924 # Verify that CookieConflictError is not raised if domain is specified925 cookie = jar.get(key, domain=domain1)926 assert cookie == value927928 def test_cookie_duplicate_names_raises_cookie_conflict_error(self):929 key = 'some_cookie'930 value = 'some_value'931 path = 'some_path'932933 jar = requests.cookies.RequestsCookieJar()934 jar.set(key, value, path=path)935 jar.set(key, value)936 with pytest.raises(requests.cookies.CookieConflictError):937 jar.get(key)938

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 939–941why, one step back
939 def test_time_elapsed_blank(self, httpbin):
940 r = requests.get(httpbin('get'))941 td = r.elapsed

Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac

line 942why, one step back
942 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6)

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 943–957why, one step back
943 assert total_seconds > 0.0
944945 def test_response_is_iterable(self):946 r = requests.Response()947 io = StringIO.StringIO('abc')948 read_ = io.read949950 def read_mock(amt, decode_content=None):951 return read_(amt)952 setattr(io, 'read', read_mock)953 r.raw = io954 assert next(iter(r))955 io.close()956957 def test_response_decode_unicode(self):

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

line 958why, one step back
958 """When called with decode_unicode, Response.iter_content should always

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 959–975why, one step back
959 return unicode.
960 """961 r = requests.Response()962 r._content_consumed = True963 r._content = b'the content'964 r.encoding = 'ascii'965966 chunks = r.iter_content(decode_unicode=True)967 assert all(isinstance(chunk, str) for chunk in chunks)968969 # also for streaming970 r = requests.Response()971 r.raw = io.BytesIO(b'the content')972 r.encoding = 'ascii'973 chunks = r.iter_content(decode_unicode=True)974 assert all(isinstance(chunk, str) for chunk in chunks)975

adding asserted_encoding check on None type encoding to match text() behavior (#3362)Nate Prewittbefore adoption92fe51c

lines 976–982why, one step back
976 # check for encoding value of None
977 r = requests.Response()978 r.raw = io.BytesIO(b'the content')979 r.encoding = None980 chunks = r.iter_content(decode_unicode=True)981 assert all(isinstance(chunk, str) for chunk in chunks)982

Support responses like `HTTP/1.1 404 Unicode chars` (#3385)Andrii Kostenkobefore adoption7700eca

lines 983–989why, one step back
983 def test_response_reason_unicode(self):
984 # check for unicode HTTP status985 r = requests.Response()986 r.url = u'unicode URL'987 r.reason = u'Komponenttia ei löydy'.encode('utf-8')988 r.status_code = 404989 r.encoding = None

Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac

line 990why, one step back
990 assert not r.ok # old behaviour - crashes here

Support responses like `HTTP/1.1 404 Unicode chars` (#3385)Andrii Kostenkobefore adoption7700eca

line 991why, one step back
991

Allow None value for chunk_size again (#3368)Joy Zhengbefore adoption0bcf634

lines 992–993why, one step back
992 def test_response_chunk_size_type(self):
993 """Ensure that chunk_size is passed as None or an integer, otherwise

Merge pull request #3365 from nateprewitt/3364_chunking_is_intCory Benfieldbefore adoption36453b9

lines 994–999why, one step back
994 raise a TypeError.
995 """996 r = requests.Response()997 r.raw = io.BytesIO(b'the content')998 chunks = r.iter_content(1)999 assert all(len(chunk) == 1 for chunk in chunks)

Allow None value for chunk_size again (#3368)Joy Zhengbefore adoption0bcf634

lines 1000–1004why, one step back
1000
1001 r = requests.Response()1002 r.raw = io.BytesIO(b'the content')1003 chunks = r.iter_content(None)1004 assert list(chunks) == [b'the content']

Merge pull request #3365 from nateprewitt/3364_chunking_is_intCory Benfieldbefore adoption36453b9

lines 1005–1010why, one step back
1005
1006 r = requests.Response()1007 r.raw = io.BytesIO(b'the content')1008 with pytest.raises(TypeError):1009 chunks = r.iter_content("1024")1010

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1011–1048why, one step back
1011 def test_request_and_response_are_pickleable(self, httpbin):
1012 r = requests.get(httpbin('get'))10131014 # verify we can pickle the original request1015 assert pickle.loads(pickle.dumps(r.request))10161017 # verify we can pickle the response and that we have access to1018 # the original request.1019 pr = pickle.loads(pickle.dumps(r))1020 assert r.request.url == pr.request.url1021 assert r.request.headers == pr.request.headers10221023 def test_cannot_send_unprepared_requests(self, httpbin):1024 r = requests.Request(url=httpbin())1025 with pytest.raises(ValueError):1026 requests.Session().send(r)10271028 def test_http_error(self):1029 error = requests.exceptions.HTTPError()1030 assert not error.response1031 response = requests.Response()1032 error = requests.exceptions.HTTPError(response=response)1033 assert error.response == response1034 error = requests.exceptions.HTTPError('message', response=response)1035 assert str(error) == 'message'1036 assert error.response == response10371038 def test_session_pickling(self, httpbin):1039 r = requests.Request('GET', httpbin('get'))1040 s = requests.Session()10411042 s = pickle.loads(pickle.dumps(s))1043 s.proxies = getproxies()10441045 r = s.send(r.prepare())1046 assert r.status_code == 20010471048 def test_fixes_1329(self, httpbin):

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

line 1049why, one step back
1049 """Ensure that header updates are done case-insensitively."""

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1050–1134why, one step back
1050 s = requests.Session()
1051 s.headers.update({'ACCEPT': 'BOGUS'})1052 s.headers.update({'accept': 'application/json'})1053 r = s.get(httpbin('get'))1054 headers = r.request.headers1055 assert headers['accept'] == 'application/json'1056 assert headers['Accept'] == 'application/json'1057 assert headers['ACCEPT'] == 'application/json'10581059 def test_uppercase_scheme_redirect(self, httpbin):1060 parts = urlparse(httpbin('html'))1061 url = "HTTP://" + parts.netloc + parts.path1062 r = requests.get(httpbin('redirect-to'), params={'url': url})1063 assert r.status_code == 2001064 assert r.url.lower() == url.lower()10651066 def test_transport_adapter_ordering(self):1067 s = requests.Session()1068 order = ['https://', 'http://']1069 assert order == list(s.adapters)1070 s.mount('http://git', HTTPAdapter())1071 s.mount('http://github', HTTPAdapter())1072 s.mount('http://github.com', HTTPAdapter())1073 s.mount('http://github.com/about/', HTTPAdapter())1074 order = [1075 'http://github.com/about/',1076 'http://github.com',1077 'http://github',1078 'http://git',1079 'https://',1080 'http://',1081 ]1082 assert order == list(s.adapters)1083 s.mount('http://gittip', HTTPAdapter())1084 s.mount('http://gittip.com', HTTPAdapter())1085 s.mount('http://gittip.com/about/', HTTPAdapter())1086 order = [1087 'http://github.com/about/',1088 'http://gittip.com/about/',1089 'http://github.com',1090 'http://gittip.com',1091 'http://github',1092 'http://gittip',1093 'http://git',1094 'https://',1095 'http://',1096 ]1097 assert order == list(s.adapters)1098 s2 = requests.Session()1099 s2.adapters = {'http://': HTTPAdapter()}1100 s2.mount('https://', HTTPAdapter())1101 assert 'http://' in s2.adapters1102 assert 'https://' in s2.adapters11031104 def test_header_remove_is_case_insensitive(self, httpbin):1105 # From issue #13211106 s = requests.Session()1107 s.headers['foo'] = 'bar'1108 r = s.get(httpbin('get'), headers={'FOO': None})1109 assert 'foo' not in r.request.headers11101111 def test_params_are_merged_case_sensitive(self, httpbin):1112 s = requests.Session()1113 s.params['foo'] = 'bar'1114 r = s.get(httpbin('get'), params={'FOO': 'bar'})1115 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}11161117 def test_long_authinfo_in_url(self):1118 url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(1119 'E8A3BE87-9E3F-4620-8858-95478E385B5B',1120 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',1121 'exactly-------------sixty-----------three------------characters',1122 )1123 r = requests.Request('GET', url).prepare()1124 assert r.url == url11251126 def test_header_keys_are_native(self, httpbin):1127 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}1128 r = requests.Request('GET', httpbin('get'), headers=headers)1129 p = r.prepare()11301131 # This is testing that they are builtin strings. A bit weird, but there1132 # we go.1133 assert 'unicode' in p.headers.keys()1134 assert 'byte' in p.headers.keys()

Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2

line 1135why, one step back
1135

Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c

line 1136why, one step back
1136 def test_header_validation(self, httpbin):

Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2

lines 1137–1138why, one step back
1137 """Ensure prepare_headers regex isn't flagging valid header contents."""
1138 headers_ok = {'foo': 'bar baz qux',

Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c

line 1139why, one step back
1139 'bar': u'fbbq'.encode('utf8'),

Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2

line 1140why, one step back
1140 'baz': '',

Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c

line 1141why, one step back
1141 'qux': '1'}

Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2

lines 1142–1143why, one step back
1142 r = requests.get(httpbin('get'), headers=headers_ok)
1143 assert r.request.headers['foo'] == headers_ok['foo']

Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c

lines 1144–1149why, one step back
1144
1145 def test_header_value_not_str(self, httpbin):1146 """Ensure the header value is of type string or bytes as1147 per discussion in GH issue #33861148 """1149 headers_int = {'foo': 3}

Merge pull request #3428 from nateprewitt/pep8_fixesKenneth Reitzbefore adoption4285bac

line 1150why, one step back
1150 headers_dict = {'bar': {'foo': 'bar'}}

Merge pull request #3390 from nateprewitt/3386_header_value_typeCory Benfieldbefore adoption425962c

lines 1151–1161why, one step back
1151 headers_list = {'baz': ['foo', 'bar']}
11521153 # Test for int1154 with pytest.raises(InvalidHeader):1155 r = requests.get(httpbin('get'), headers=headers_int)1156 # Test for dict1157 with pytest.raises(InvalidHeader):1158 r = requests.get(httpbin('get'), headers=headers_dict)1159 # Test for list1160 with pytest.raises(InvalidHeader):1161 r = requests.get(httpbin('get'), headers=headers_list)

Merge pull request #3366 from nateprewitt/2947-no-returns-in-headerCory Benfieldbefore adoptionbd9e8f2

lines 1162–1193why, one step back
1162
1163 def test_header_no_return_chars(self, httpbin):1164 """Ensure that a header containing return character sequences raise an1165 exception. Otherwise, multiple headers are created from single string.1166 """1167 headers_ret = {'foo': 'bar\r\nbaz: qux'}1168 headers_lf = {'foo': 'bar\nbaz: qux'}1169 headers_cr = {'foo': 'bar\rbaz: qux'}11701171 # Test for newline1172 with pytest.raises(InvalidHeader):1173 r = requests.get(httpbin('get'), headers=headers_ret)1174 # Test for line feed1175 with pytest.raises(InvalidHeader):1176 r = requests.get(httpbin('get'), headers=headers_lf)1177 # Test for carriage return1178 with pytest.raises(InvalidHeader):1179 r = requests.get(httpbin('get'), headers=headers_cr)11801181 def test_header_no_leading_space(self, httpbin):1182 """Ensure headers containing leading whitespace raise1183 InvalidHeader Error before sending.1184 """1185 headers_space = {'foo': ' bar'}1186 headers_tab = {'foo': ' bar'}11871188 # Test for whitespace1189 with pytest.raises(InvalidHeader):1190 r = requests.get(httpbin('get'), headers=headers_space)1191 # Test for tab1192 with pytest.raises(InvalidHeader):1193 r = requests.get(httpbin('get'), headers=headers_tab)

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1194–1229why, one step back
1194
1195 @pytest.mark.parametrize('files', ('foo', b'foo', bytearray(b'foo')))1196 def test_can_send_objects_with_files(self, httpbin, files):1197 data = {'a': 'this is a string'}1198 files = {'b': files}1199 r = requests.Request('POST', httpbin('post'), data=data, files=files)1200 p = r.prepare()1201 assert 'multipart/form-data' in p.headers['Content-Type']12021203 def test_can_send_file_object_with_non_string_filename(self, httpbin):1204 f = io.BytesIO()1205 f.name = 21206 r = requests.Request('POST', httpbin('post'), files={'f': f})1207 p = r.prepare()12081209 assert 'multipart/form-data' in p.headers['Content-Type']12101211 def test_autoset_header_values_are_native(self, httpbin):1212 data = 'this is a string'1213 length = '16'1214 req = requests.Request('POST', httpbin('post'), data=data)1215 p = req.prepare()12161217 assert p.headers['Content-Length'] == length12181219 def test_nonhttp_schemes_dont_check_URLs(self):1220 test_urls = (1221 'data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==',1222 'file:///etc/passwd',1223 'magnet:?xt=urn:btih:be08f00302bc2d1d3cfa3af02024fa647a271431',1224 )1225 for test_url in test_urls:1226 req = requests.Request('GET', test_url)1227 preq = req.prepare()1228 assert test_url == preq.url1229

Merge pull request #3236 from eriol/xfail-testKenneth Reitzbefore adoption771ecd7

line 1230why, one step back
1230 @pytest.mark.xfail(raises=ConnectionError)

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1231–1340why, one step back
1231 def test_auth_is_stripped_on_redirect_off_host(self, httpbin):
1232 r = requests.get(1233 httpbin('redirect-to'),1234 params={'url': 'http://www.google.co.uk'},1235 auth=('user', 'pass'),1236 )1237 assert r.history[0].request.headers['Authorization']1238 assert not r.request.headers.get('Authorization', '')12391240 def test_auth_is_retained_for_redirect_on_host(self, httpbin):1241 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1242 h1 = r.history[0].request.headers['Authorization']1243 h2 = r.request.headers['Authorization']12441245 assert h1 == h212461247 def test_manual_redirect_with_partial_body_read(self, httpbin):1248 s = requests.Session()1249 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1250 assert r1.is_redirect1251 rg = s.resolve_redirects(r1, r1.request, stream=True)12521253 # read only the first eight bytes of the response body,1254 # then follow the redirect1255 r1.iter_content(8)1256 r2 = next(rg)1257 assert r2.is_redirect12581259 # read all of the response via iter_content,1260 # then follow the redirect1261 for _ in r2.iter_content():1262 pass1263 r3 = next(rg)1264 assert not r3.is_redirect12651266 def _patch_adapter_gzipped_redirect(self, session, url):1267 adapter = session.get_adapter(url=url)1268 org_build_response = adapter.build_response1269 self._patched_response = False12701271 def build_response(*args, **kwargs):1272 resp = org_build_response(*args, **kwargs)1273 if not self._patched_response:1274 resp.raw.headers['content-encoding'] = 'gzip'1275 self._patched_response = True1276 return resp12771278 adapter.build_response = build_response12791280 def test_redirect_with_wrong_gzipped_header(self, httpbin):1281 s = requests.Session()1282 url = httpbin('redirect/1')1283 self._patch_adapter_gzipped_redirect(s, url)1284 s.get(url)12851286 def test_basic_auth_str_is_always_native(self):1287 s = _basic_auth_str("test", "test")1288 assert isinstance(s, builtin_str)1289 assert s == "Basic dGVzdDp0ZXN0"12901291 def test_requests_history_is_saved(self, httpbin):1292 r = requests.get(httpbin('redirect/5'))1293 total = r.history[-1].history1294 i = 01295 for item in r.history:1296 assert item.history == total[0:i]1297 i += 112981299 def test_json_param_post_content_type_works(self, httpbin):1300 r = requests.post(1301 httpbin('post'),1302 json={'life': 42}1303 )1304 assert r.status_code == 2001305 assert 'application/json' in r.request.headers['Content-Type']1306 assert {'life': 42} == r.json()['json']13071308 def test_json_param_post_should_not_override_data_param(self, httpbin):1309 r = requests.Request(method='POST', url=httpbin('post'),1310 data={'stuff': 'elixr'},1311 json={'music': 'flute'})1312 prep = r.prepare()1313 assert 'stuff=elixr' == prep.body13141315 def test_response_iter_lines(self, httpbin):1316 r = requests.get(httpbin('stream/4'), stream=True)1317 assert r.status_code == 20013181319 it = r.iter_lines()1320 next(it)1321 assert len(list(it)) == 313221323 def test_unconsumed_session_response_closes_connection(self, httpbin):1324 s = requests.session()13251326 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1327 pass13281329 assert response._content_consumed is False1330 assert response.raw.closed13311332 @pytest.mark.xfail1333 def test_response_iter_lines_reentrant(self, httpbin):1334 """Response.iter_lines() is not reentrant safe"""1335 r = requests.get(httpbin('stream/4'), stream=True)1336 assert r.status_code == 20013371338 next(r.iter_lines())1339 assert len(list(r.iter_lines())) == 31340

Merge pull request #3091 from bodgit/proxyIan Cordascobefore adoption60aee14

lines 1341–1351why, one step back
1341 def test_session_close_proxy_clear(self, mocker):
1342 proxies = {1343 'one': mocker.Mock(),1344 'two': mocker.Mock(),1345 }1346 session = requests.Session()1347 mocker.patch.dict(session.adapters['http://'].proxy_manager, proxies)1348 session.close()1349 proxies['one'].clear.assert_called_once_with()1350 proxies['two'].clear.assert_called_once_with()1351

Merge pull request #3179 from messense/messense-patch-1Cory Benfieldbefore adoption8770410

lines 1352–1362why, one step back
1352 def test_response_json_when_content_is_None(self, httpbin):
1353 r = requests.get(httpbin('/status/204'))1354 # Make sure r.content is None1355 r.status_code = 01356 r._content = False1357 r._content_consumed = False13581359 assert r.content is None1360 with pytest.raises(ValueError):1361 r.json()1362

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1363–1370why, one step back
1363
1364class TestCaseInsensitiveDict:13651366 @pytest.mark.parametrize(1367 'cid', (1368 CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1369 CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1370 CaseInsensitiveDict(FOO='foo', BAr='bar'),

syntax changesKenneth Reitzbefore adoptionbbadf47

line 1371why, one step back
1371 ))

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1372–1520why, one step back
1372 def test_init(self, cid):
1373 assert len(cid) == 21374 assert 'foo' in cid1375 assert 'bar' in cid13761377 def test_docstring_example(self):1378 cid = CaseInsensitiveDict()1379 cid['Accept'] = 'application/json'1380 assert cid['aCCEPT'] == 'application/json'1381 assert list(cid) == ['Accept']13821383 def test_len(self):1384 cid = CaseInsensitiveDict({'a': 'a', 'b': 'b'})1385 cid['A'] = 'a'1386 assert len(cid) == 213871388 def test_getitem(self):1389 cid = CaseInsensitiveDict({'Spam': 'blueval'})1390 assert cid['spam'] == 'blueval'1391 assert cid['SPAM'] == 'blueval'13921393 def test_fixes_649(self):1394 """__setitem__ should behave case-insensitively."""1395 cid = CaseInsensitiveDict()1396 cid['spam'] = 'oneval'1397 cid['Spam'] = 'twoval'1398 cid['sPAM'] = 'redval'1399 cid['SPAM'] = 'blueval'1400 assert cid['spam'] == 'blueval'1401 assert cid['SPAM'] == 'blueval'1402 assert list(cid.keys()) == ['SPAM']14031404 def test_delitem(self):1405 cid = CaseInsensitiveDict()1406 cid['Spam'] = 'someval'1407 del cid['sPam']1408 assert 'spam' not in cid1409 assert len(cid) == 014101411 def test_contains(self):1412 cid = CaseInsensitiveDict()1413 cid['Spam'] = 'someval'1414 assert 'Spam' in cid1415 assert 'spam' in cid1416 assert 'SPAM' in cid1417 assert 'sPam' in cid1418 assert 'notspam' not in cid14191420 def test_get(self):1421 cid = CaseInsensitiveDict()1422 cid['spam'] = 'oneval'1423 cid['SPAM'] = 'blueval'1424 assert cid.get('spam') == 'blueval'1425 assert cid.get('SPAM') == 'blueval'1426 assert cid.get('sPam') == 'blueval'1427 assert cid.get('notspam', 'default') == 'default'14281429 def test_update(self):1430 cid = CaseInsensitiveDict()1431 cid['spam'] = 'blueval'1432 cid.update({'sPam': 'notblueval'})1433 assert cid['spam'] == 'notblueval'1434 cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1435 cid.update({'fOO': 'anotherfoo', 'bAR': 'anotherbar'})1436 assert len(cid) == 21437 assert cid['foo'] == 'anotherfoo'1438 assert cid['bar'] == 'anotherbar'14391440 def test_update_retains_unchanged(self):1441 cid = CaseInsensitiveDict({'foo': 'foo', 'bar': 'bar'})1442 cid.update({'foo': 'newfoo'})1443 assert cid['bar'] == 'bar'14441445 def test_iter(self):1446 cid = CaseInsensitiveDict({'Spam': 'spam', 'Eggs': 'eggs'})1447 keys = frozenset(['Spam', 'Eggs'])1448 assert frozenset(iter(cid)) == keys14491450 def test_equality(self):1451 cid = CaseInsensitiveDict({'SPAM': 'blueval', 'Eggs': 'redval'})1452 othercid = CaseInsensitiveDict({'spam': 'blueval', 'eggs': 'redval'})1453 assert cid == othercid1454 del othercid['spam']1455 assert cid != othercid1456 assert cid == {'spam': 'blueval', 'eggs': 'redval'}1457 assert cid != object()14581459 def test_setdefault(self):1460 cid = CaseInsensitiveDict({'Spam': 'blueval'})1461 assert cid.setdefault('spam', 'notblueval') == 'blueval'1462 assert cid.setdefault('notspam', 'notblueval') == 'notblueval'14631464 def test_lower_items(self):1465 cid = CaseInsensitiveDict({1466 'Accept': 'application/json',1467 'user-Agent': 'requests',1468 })1469 keyset = frozenset(lowerkey for lowerkey, v in cid.lower_items())1470 lowerkeyset = frozenset(['accept', 'user-agent'])1471 assert keyset == lowerkeyset14721473 def test_preserve_key_case(self):1474 cid = CaseInsensitiveDict({1475 'Accept': 'application/json',1476 'user-Agent': 'requests',1477 })1478 keyset = frozenset(['Accept', 'user-Agent'])1479 assert frozenset(i[0] for i in cid.items()) == keyset1480 assert frozenset(cid.keys()) == keyset1481 assert frozenset(cid) == keyset14821483 def test_preserve_last_key_case(self):1484 cid = CaseInsensitiveDict({1485 'Accept': 'application/json',1486 'user-Agent': 'requests',1487 })1488 cid.update({'ACCEPT': 'application/json'})1489 cid['USER-AGENT'] = 'requests'1490 keyset = frozenset(['ACCEPT', 'USER-AGENT'])1491 assert frozenset(i[0] for i in cid.items()) == keyset1492 assert frozenset(cid.keys()) == keyset1493 assert frozenset(cid) == keyset14941495 def test_copy(self):1496 cid = CaseInsensitiveDict({1497 'Accept': 'application/json',1498 'user-Agent': 'requests',1499 })1500 cid_copy = cid.copy()1501 assert cid == cid_copy1502 cid['changed'] = True1503 assert cid != cid_copy150415051506class TestMorselToCookieExpires:1507 """Tests for morsel_to_cookie when morsel contains expires."""15081509 def test_expires_valid_str(self):1510 """Test case where we convert expires from string time."""15111512 morsel = Morsel()1513 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1514 cookie = morsel_to_cookie(morsel)1515 assert cookie.expires == 115161517 @pytest.mark.parametrize(1518 'value, exception', (1519 (100, TypeError),1520 ('woops', ValueError),

syntax changesKenneth Reitzbefore adoptionbbadf47

line 1521why, one step back
1521 ))

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1522–1570why, one step back
1522 def test_expires_invalid_int(self, value, exception):
1523 """Test case where an invalid type is passed for expires."""1524 morsel = Morsel()1525 morsel['expires'] = value1526 with pytest.raises(exception):1527 morsel_to_cookie(morsel)15281529 def test_expires_none(self):1530 """Test case where expires is None."""15311532 morsel = Morsel()1533 morsel['expires'] = None1534 cookie = morsel_to_cookie(morsel)1535 assert cookie.expires is None153615371538class TestMorselToCookieMaxAge:15391540 """Tests for morsel_to_cookie when morsel contains max-age."""15411542 def test_max_age_valid_int(self):1543 """Test case where a valid max age in seconds is passed."""15441545 morsel = Morsel()1546 morsel['max-age'] = 601547 cookie = morsel_to_cookie(morsel)1548 assert isinstance(cookie.expires, int)15491550 def test_max_age_invalid_str(self):1551 """Test case where a invalid max age is passed."""15521553 morsel = Morsel()1554 morsel['max-age'] = 'woops'1555 with pytest.raises(TypeError):1556 morsel_to_cookie(morsel)155715581559class TestTimeout:15601561 def test_stream_timeout(self, httpbin):1562 try:1563 requests.get(httpbin('delay/10'), timeout=2.0)1564 except requests.exceptions.Timeout as e:1565 assert 'Read timed out' in e.args[0].args[0]15661567 @pytest.mark.parametrize(1568 'timeout, error_text', (1569 ((3, 4, 5), '(connect, read)'),1570 ('foo', 'must be an int or float'),

syntax changesKenneth Reitzbefore adoptionbbadf47

line 1571why, one step back
1571 ))

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1572–1577why, one step back
1572 def test_invalid_timeout(self, httpbin, timeout, error_text):
1573 with pytest.raises(ValueError) as e:1574 requests.get(httpbin('get'), timeout=timeout)1575 assert error_text in str(e)15761577 def test_none_timeout(self, httpbin):

Merge pull request #3429 from nateprewitt/docstring_cleanupKenneth Reitzbefore adoptionfb01456

line 1578why, one step back
1578 """Check that you can set None as a valid timeout value.

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1579–1651why, one step back
1579
1580 To actually test this behavior, we'd want to check that setting the1581 timeout to None actually lets the request block past the system default1582 timeout. However, this would make the test suite unbearably slow.1583 Instead we verify that setting the timeout to None does not prevent the1584 request from succeeding.1585 """1586 r = requests.get(httpbin('get'), timeout=None)1587 assert r.status_code == 20015881589 def test_read_timeout(self, httpbin):1590 try:1591 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1592 pytest.fail('The recv() request should time out.')1593 except ReadTimeout:1594 pass15951596 def test_connect_timeout(self):1597 try:1598 requests.get(TARPIT, timeout=(0.1, None))1599 pytest.fail('The connect() request should time out.')1600 except ConnectTimeout as e:1601 assert isinstance(e, ConnectionError)1602 assert isinstance(e, Timeout)16031604 def test_total_timeout_connect(self):1605 try:1606 requests.get(TARPIT, timeout=(0.1, 0.1))1607 pytest.fail('The connect() request should time out.')1608 except ConnectTimeout:1609 pass16101611 def test_encoded_methods(self, httpbin):1612 """See: https://github.com/kennethreitz/requests/issues/2316"""1613 r = requests.request(b'GET', httpbin('get'))1614 assert r.ok161516161617SendCall = collections.namedtuple('SendCall', ('args', 'kwargs'))161816191620class RedirectSession(SessionRedirectMixin):1621 def __init__(self, order_of_redirects):1622 self.redirects = order_of_redirects1623 self.calls = []1624 self.max_redirects = 301625 self.cookies = {}1626 self.trust_env = False16271628 def send(self, *args, **kwargs):1629 self.calls.append(SendCall(args, kwargs))1630 return self.build_response()16311632 def build_response(self):1633 request = self.calls[-1].args[0]1634 r = requests.Response()16351636 try:1637 r.status_code = int(self.redirects.pop(0))1638 except IndexError:1639 r.status_code = 20016401641 r.headers = CaseInsensitiveDict({'Location': '/'})1642 r.raw = self._build_raw()1643 r.request = request1644 return r16451646 def _build_raw(self):1647 string = StringIO.StringIO('')1648 setattr(string, 'release_conn', lambda *args: args)1649 return string16501651

Merge pull request #3178 from haikuginger/masterCory Benfieldbefore adoption49b69c4

lines 1652–1663why, one step back
1652def test_json_encodes_as_bytes():
1653 # urllib3 expects bodies as bytes-like objects1654 body = {"key": "value"}1655 p = PreparedRequest()1656 p.prepare(1657 method='GET',1658 url='https://www.example.com/',1659 json=body1660 )1661 assert isinstance(p.body, bytes)16621663

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1664–1682why, one step back
1664def test_requests_are_updated_each_time(httpbin):
1665 session = RedirectSession([303, 307])1666 prep = requests.Request('POST', httpbin('post')).prepare()1667 r0 = session.send(prep)1668 assert r0.request.method == 'POST'1669 assert session.calls[-1] == SendCall((r0.request,), {})1670 redirect_generator = session.resolve_redirects(r0, prep)1671 default_keyword_args = {1672 'stream': False,1673 'verify': True,1674 'cert': None,1675 'timeout': None,1676 'allow_redirects': False,1677 'proxies': {},1678 }1679 for response in redirect_generator:1680 assert response.request.method == 'GET'1681 send_call = SendCall((response.request,), default_keyword_args)1682 assert session.calls[-1] == send_call

Merge pull request #3185 from brettdh/3183-support-all-proxy-env-varIan Cordascobefore adoptioncd4e6b9

lines 1683–1703why, one step back
1683
16841685@pytest.mark.parametrize("var,url,proxy", [1686 ('http_proxy', 'http://example.com', 'socks5://proxy.com:9876'),1687 ('https_proxy', 'https://example.com', 'socks5://proxy.com:9876'),1688 ('all_proxy', 'http://example.com', 'socks5://proxy.com:9876'),1689 ('all_proxy', 'https://example.com', 'socks5://proxy.com:9876'),1690])1691def test_proxy_env_vars_override_default(var, url, proxy):1692 session = requests.Session()1693 prep = PreparedRequest()1694 prep.prepare(method='GET', url=url)16951696 kwargs = {1697 var: proxy1698 }1699 scheme = urlparse(url).scheme1700 with override_environ(**kwargs):1701 proxies = session.rebuild_proxies(prep, {})1702 assert scheme in proxies1703 assert proxies[scheme] == proxy

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1704–1710why, one step back
1704
17051706@pytest.mark.parametrize(1707 'data', (1708 (('a', 'b'), ('c', 'd')),1709 (('c', 'd'), ('a', 'b')),1710 (('a', 'b'), ('c', 'd'), ('e', 'f')),

syntax changesKenneth Reitzbefore adoptionbbadf47

line 1711why, one step back
1711 ))

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1712–1745why, one step back
1712def test_data_argument_accepts_tuples(data):
1713 """Ensure that the data argument will accept tuples of strings1714 and properly encode them.1715 """1716 p = PreparedRequest()1717 p.prepare(1718 method='GET',1719 url='http://www.example.com',1720 data=data,1721 hooks=default_hooks()1722 )1723 assert p.body == urlencode(data)172417251726@pytest.mark.parametrize(1727 'kwargs', (1728 None,1729 {1730 'method': 'GET',1731 'url': 'http://www.example.com',1732 'data': 'foo=bar',1733 'hooks': default_hooks()1734 },1735 {1736 'method': 'GET',1737 'url': 'http://www.example.com',1738 'data': 'foo=bar',1739 'hooks': default_hooks(),1740 'cookies': {'foo': 'bar'}1741 },1742 {1743 'method': 'GET',1744 'url': u('http://www.example.com/üniçø∂é')1745 },

syntax changesKenneth Reitzbefore adoptionbbadf47

line 1746why, one step back
1746 ))

Added tests module.Dmitry Dygalobefore adoption18b26d2

lines 1747–1782why, one step back
1747def test_prepared_copy(kwargs):
1748 p = PreparedRequest()1749 if kwargs:1750 p.prepare(**kwargs)1751 copy = p.copy()1752 for attr in ('method', 'url', 'headers', '_cookies', 'body', 'hooks'):1753 assert getattr(p, attr) == getattr(copy, attr)175417551756def test_urllib3_retries(httpbin):1757 from requests.packages.urllib3.util import Retry1758 s = requests.Session()1759 s.mount('http://', HTTPAdapter(max_retries=Retry(1760 total=2, status_forcelist=[500]1761 )))17621763 with pytest.raises(RetryError):1764 s.get(httpbin('status/500'))176517661767def test_urllib3_pool_connection_closed(httpbin):1768 s = requests.Session()1769 s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))17701771 try:1772 s.get(httpbin('status/200'))1773 except ConnectionError as e:1774 assert u"Pool is closed." in str(e)177517761777def test_vendor_aliases():1778 from requests.packages import urllib31779 from requests.packages import chardet17801781 with pytest.raises(ImportError):1782 from requests.packages import webbrowser