Initial work
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 ed8cfd3 · Browse files · 7 files·+172 added−161 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+172 added−161 removed
- other:+172 added−161 removed
Provenance
- Commit
6c2942b- Tree
7c53d4a- Author
Dmitry Dygalo <dadygalo@gmail.com>- Committer
Dmitry Dygalo <dadygalo@gmail.com>- Parent
ed8cfd3
7 files changed+172 added−161 removed
added:.coveragerc+7 added
1+[run]2+omit = */packages/*3+4+[report]5+show_missing = true6+precision = 27+exclude_lines = pytest.failmodified:.gitignore-1 removed
3 unmodified lines4 nosetests.xml5 junit-report.xml6 pylint.txt7 toy.py8-tox.ini8 violations.pyflakes.txt9 cover/10 build/11 docs/_build12 unmodified linesmodified:AUTHORS.rst+2 added-1 removed
160 unmodified lines161 - Colin Dickson (`@colindickson <https://github.com/colindickson>`_)162 - Smiley Barry (`@smiley <https://github.com/smiley>`_)163 - Shagun Sodhani (`@shagunsodhani <https://github.com/shagunsodhani>`_)164 - Robin Linderborg (`@vienno <https://github.com/vienno>`_)165-- Brian Samek(`@bsamek <https://github.com/bsamek`_)165+- Brian Samek (`@bsamek <https://github.com/bsamek>`_)166+- Dmitry Dygalo (`@Stranger6667 <https://github.com/Stranger6667>`_)modified:Makefile+2 added-2 removed
4 unmodified lines5 6 test: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+ python setup.py test -a "test_requests.py"10 11 coverage:12- py.test --verbose --cov-report term --cov=requests test_requests.py12+ python setup.py test -a "--verbose --cov-report term --cov=requests test_requests.py"13 14 ci: init15 py.test --junitxml=junit.xml16 23 unmodified linesmodified:setup.py+34 added-1 removed
1 #!/usr/bin/env python2 3 import os4+import platform5 import re6 import sys7 8 from codecs import open9 10 from setuptools import setup11+from setuptools.command.test import test as TestCommand12 13 14+JYTHON = platform.system() == 'Java'15+16+17+class PyTest(TestCommand):18+ user_options = [('pytest-args=', 'a', "Arguments to pass into py.test")]19+20+ def initialize_options(self):21+ TestCommand.initialize_options(self)22+ self.pytest_args = []23+24+ def finalize_options(self):25+ TestCommand.finalize_options(self)26+ self.test_args = []27+ self.test_suite = True28+29+ def run_tests(self):30+ import pytest31+32+ errno = pytest.main(self.pytest_args)33+ sys.exit(errno)34+35+36 if sys.argv[-1] == 'publish':37 os.system('python setup.py sdist upload')38 sys.exit()39 8 unmodified lines48 'requests.packages.urllib3.packages.ssl_match_hostname',49 ]50 51 requires = []52+test_requirements = ['pytest>=2.8.0', 'pytest-httpbin==0.0.7']53 29-version = ''54+if not JYTHON:55+ test_requirements.append('pytest-cov')56+57 with open('requests/__init__.py', 'r') as fd:58 version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',59 fd.read(), re.MULTILINE).group(1)60 25 unmodified lines86 'Intended Audience :: Developers',87 'Natural Language :: English',88 'License :: OSI Approved :: Apache Software License',89 'Programming Language :: Python',90+ 'Programming Language :: Python :: 2.6',91 'Programming Language :: Python :: 2.7',92 'Programming Language :: Python :: 3',93 'Programming Language :: Python :: 3.3',94 'Programming Language :: Python :: 3.4',95 'Programming Language :: Python :: 3.5',96+ 'Programming Language :: Python :: Implementation :: CPython',97+ 'Programming Language :: Python :: Implementation :: PyPy',98+ 'Programming Language :: Python :: Implementation :: Jython',99 ),100+ cmdclass={'test': PyTest},101+ tests_require=test_requirements,102 extras_require={103 'security': ['pyOpenSSL>=0.13', 'ndg-httpsclient', 'pyasn1'],104 },105 )modified:test_requests.py+119 added-156 removed
5 unmodified lines6 from __future__ import division7 import json8 import os9 import pickle10-import unittest10 import collections11 import contextlib12 13 import io58 unmodified lines72 # Requests to this URL should always fail with a connection timeout (nothing73 # listening on that port)74 TARPIT = "http://10.255.255.1"75 77-class TestRequests(object):76 79- _multiprocess_can_split_ = True77+class TestRequests:78 81- def setUp(self):82- """Create simple data set with headers."""83- pass84-85- def tearDown(self):86- """Teardown."""87- pass88-79 def test_entry_points(self):80 81 requests.session82 requests.session().get3 unmodified lines86 requests.put87 requests.patch88 requests.post89 100- def test_invalid_url(self):101- with pytest.raises(MissingSchema):102- requests.get('hiwpefhipowhefopw')103- with pytest.raises(InvalidSchema):104- requests.get('localhost:3128')105- with pytest.raises(InvalidSchema):106- requests.get('localhost.localdomain:3128/')107- with pytest.raises(InvalidSchema):108- requests.get('10.122.1.1:3128/')109- with pytest.raises(InvalidURL):110- requests.get('http://')90+ @pytest.mark.parametrize(91+ 'exception, url',92+ (93+ (MissingSchema, 'hiwpefhipowhefopw'),94+ (InvalidSchema, 'localhost:3128'),95+ (InvalidSchema, 'localhost.localdomain:3128/'),96+ (InvalidSchema, '10.122.1.1:3128/'),97+ (InvalidURL, 'http://'),98+ )99+ )100+ def test_invalid_url(self, exception, url):101+ with pytest.raises(exception):102+ requests.get(url)103 104 def test_basic_building(self):105 req = requests.Request()106 req.url = 'http://kennethreitz.org/'2 unmodified lines109 pr = req.prepare()110 assert pr.url == req.url111 assert pr.body == 'life=42'112 121- def test_no_content_length(self, httpbin):122- get_req = requests.Request('GET', httpbin('get')).prepare()123- assert 'Content-Length' not in get_req.headers124- head_req = requests.Request('HEAD', httpbin('head')).prepare()125- assert 'Content-Length' not in head_req.headers113+ @pytest.mark.parametrize('method', ('GET', 'HEAD'))114+ def test_no_content_length(self, httpbin, method):115+ req = requests.Request(method, httpbin(method.lower())).prepare()116+ assert 'Content-Length' not in req.headers117 118 def test_override_content_length(self, httpbin):119 headers = {120 'Content-Length': 'not zero'6 unmodified lines127 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()128 129 assert request.path_url == '/get/test%20case'130 140- def test_params_are_added_before_fragment(self):141- request = requests.Request('GET',142- "http://example.com/path#fragment", params={"a": "b"}).prepare()143- assert request.url == "http://example.com/path?a=b#fragment"144- request = requests.Request('GET',145- "http://example.com/path?key=value#fragment", params={"a": "b"}).prepare()146- assert request.url == "http://example.com/path?key=value&a=b#fragment"131+ @pytest.mark.parametrize(132+ 'url, expected',133+ (134+ ('http://example.com/path#fragment', 'http://example.com/path?a=b#fragment'),135+ ('http://example.com/path?key=value#fragment', 'http://example.com/path?key=value&a=b#fragment')136+ )137+ )138+ def test_params_are_added_before_fragment(self, url, expected):139+ request = requests.Request('GET', url, params={"a": "b"}).prepare()140+ assert request.url == expected141 142 def test_params_original_order_is_preserved_by_default(self):143 param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))144 session = requests.Session()10 unmodified lines155 request = requests.Request('PUT', 'http://example.com',156 data=u"ööö".encode("utf-8")).prepare()157 assert isinstance(request.body, bytes)158 159+ @pytest.mark.parametrize('scheme', ('http://', 'HTTP://', 'hTTp://', 'HttP://'))165- def test_mixed_case_scheme_acceptable(self, httpbin):160+ def test_mixed_case_scheme_acceptable(self, httpbin, scheme):161 s = requests.Session()162 s.proxies = getproxies()163 parts = urlparse(httpbin('get'))169- schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://']170- for scheme in schemes:171- url = scheme + parts.netloc + parts.path172- r = requests.Request('GET', url)173- r = s.send(r.prepare())174- assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)164+ url = scheme + parts.netloc + parts.path165+ r = requests.Request('GET', url)166+ r = s.send(r.prepare())167+ assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)168 169 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):170 r = requests.Request('GET', httpbin('get'))171 s = requests.Session()143 unmodified lines315 req = requests.Request('GET', httpbin('get'))316 prep = ses.prepare_request(req)317 assert 'Accept-Encoding' not in prep.headers318 319+ @pytest.mark.parametrize('key', ('User-agent', 'user-agent'))326- def test_user_agent_transfers(self, httpbin):320+ def test_user_agent_transfers(self, httpbin, key):321 322 heads = {329- 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'323+ key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'324 }325 326 r = requests.get(httpbin('user-agent'), headers=heads)333- assert heads['User-agent'] in r.text327+ assert heads[key] in r.text328 335- heads = {336- 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'337- }338-339- r = requests.get(httpbin('user-agent'), headers=heads)340- assert heads['user-agent'] in r.text341-329 def test_HTTP_200_OK_HEAD(self, httpbin):330 r = requests.head(httpbin('get'))331 assert r.status_code == 200332 15 unmodified lines348 s.auth = auth349 r = s.get(url)350 assert r.status_code == 200351 365- def test_connection_error_invalid_domain(self):366- """Connecting to an unknown domain should raise a ConnectionError"""367- with pytest.raises(ConnectionError):368- requests.get("http://doesnotexist.google.com")352+ @pytest.mark.parametrize(353+ 'url, exception',354+ (355+ # Connecting to an unknown domain should raise a ConnectionError356+ ('http://doesnotexist.google.com', ConnectionError),357+ # Connecting to an invalid port should raise a ConnectionError358+ ('http://localhost:1', ConnectionError),359+ # Inputing a URL that cannot be parsed should raise an InvalidURL error360+ ('http://fe80::5054:ff:fe5a:fc0', InvalidURL)361+ )362+ )363+ def test_errors(self, url, exception):364+ with pytest.raises(exception):365+ requests.get(url, timeout=1)366 370- def test_connection_error_invalid_port(self):371- """Connecting to an invalid port should raise a ConnectionError"""372- with pytest.raises(ConnectionError):373- requests.get("http://localhost:1", timeout=1)374-375- def test_LocationParseError(self):376- """Inputing a URL that cannot be parsed should raise an InvalidURL error"""377- with pytest.raises(InvalidURL):378- requests.get("http://fe80::5054:ff:fe5a:fc0")379-367 def test_basicauth_with_netrc(self, httpbin):368 auth = ('user', 'pass')369 wrong_auth = ('wronguser', 'wrongpass')370 url = httpbin('basic-auth', 'user', 'pass')95 unmodified lines466 467 def test_POSTBIN_GET_POST_FILES(self, httpbin):468 469 url = httpbin('post')483- post1 = requests.post(url).raise_for_status()470+ requests.post(url).raise_for_status()471 472 post1 = requests.post(url, data={'some': 'data'})473 assert post1.status_code == 200474 9 unmodified lines484 485 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):486 487 url = httpbin('post')501- post1 = requests.post(url).raise_for_status()488+ requests.post(url).raise_for_status()489 490 post1 = requests.post(url, data={'some': 'data'})491 assert post1.status_code == 200492 29 unmodified lines522 def test_decompress_gzip(self, httpbin):523 r = requests.get(httpbin('gzip'))524 r.content.decode('ascii')525 539- def test_unicode_get(self, httpbin):540- url = httpbin('/get')541- requests.get(url, params={'foo': 'føø'})542- requests.get(url, params={'føø': 'føø'})543- requests.get(url, params={'føø': 'føø'})544- requests.get(url, params={'foo': 'foo'})545- requests.get(httpbin('ø'), params={'foo': 'foo'})526+ @pytest.mark.parametrize(527+ 'url, params',528+ (529+ ('/get', {'foo': 'føø'}),530+ ('/get', {'føø': 'føø'}),531+ ('/get', {'føø': 'føø'}),532+ ('/get', {'foo': 'foo'}),533+ ('ø', {'foo': 'foo'}),534+ )535+ )536+ def test_unicode_get(self, httpbin, url, params):537+ requests.get(httpbin(url), params=params)538 539 def test_unicode_header_name(self, httpbin):540 requests.put(541 httpbin('put'),15 unmodified lines557 params={'blah': 'asdf1234'},558 files={'file': ('test_requests.py', open(__file__, 'rb'))})559 assert r.status_code == 200560 561+ @pytest.mark.parametrize(562+ 'data', (563+ {'stuff': u('ëlïxr')},564+ {'stuff': u('ëlïxr').encode('utf-8')},565+ {'stuff': 'elixr'},566+ {'stuff': 'elixr'.encode('utf-8')},567+ )568+ )569- def test_unicode_multipart_post(self, httpbin):569+ def test_unicode_multipart_post(self, httpbin, data):570 r = requests.post(httpbin('post'),571- data={'stuff': u('ëlïxr')},571+ data=data,572 files={'file': ('test_requests.py', open(__file__, 'rb'))})573 assert r.status_code == 200574 575- r = requests.post(httpbin('post'),576- data={'stuff': u('ëlïxr').encode('utf-8')},577- files={'file': ('test_requests.py', open(__file__, 'rb'))})578- assert r.status_code == 200579-580- r = requests.post(httpbin('post'),581- data={'stuff': 'elixr'},582- files={'file': ('test_requests.py', open(__file__, 'rb'))})583- assert r.status_code == 200584-585- r = requests.post(httpbin('post'),586- data={'stuff': 'elixr'.encode('utf-8')},587- files={'file': ('test_requests.py', open(__file__, 'rb'))})588- assert r.status_code == 200589-575 def test_unicode_multipart_post_fieldnames(self, httpbin):576 filename = os.path.splitext(__file__)[0] + '.py'577 r = requests.Request(method='POST',578 url=httpbin('post'),32 unmodified lines611 assert b"text/py-content-type" in r.request.body612 613 def test_hook_receives_request_arguments(self, httpbin):614 def hook(resp, **kwargs):615+ # FIXME. Not executed616 assert resp is not None617 assert kwargs != {}618 619 requests.Request('GET', httpbin(), hooks={'response': hook})483 unmodified lines1103 total = r.history[-1].history1104 i = 01105 for item in r.history:1106 assert item.history == total[0:i]1121- i = i + 11107+ i += 11108 1109 def test_json_param_post_content_type_works(self, httpbin):1110 r = requests.post(1111 httpbin('post'),36 unmodified lines1148 next(r.iter_lines())1149 assert len(list(r.iter_lines())) == 31150 1151 1166-class TestContentEncodingDetection(unittest.TestCase):1152+class TestContentEncodingDetection:1153 1154 def test_none(self):1155 encodings = requests.utils.get_encodings_from_content('')1156 assert not len(encodings)1157 1172- def test_html_charset(self):1173- """HTML5 meta charset attribute"""1174- content = '<meta charset="UTF-8">'1158+ @pytest.mark.parametrize(1159+ 'content', (1160+ # HTML5 meta charset attribute1161+ '<meta charset="UTF-8">',1162+ # HTML4 pragma directive1163+ '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">',1164+ # XHTML 1.x served with text/html MIME type1165+ '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />',1166+ # XHTML 1.x served as XML1167+ '<?xml version="1.0" encoding="UTF-8"?>',1168+ )1169+ )1170+ def test_pragmas(self, content):1171 encodings = requests.utils.get_encodings_from_content(content)1172 assert len(encodings) == 11173 assert encodings[0] == 'UTF-8'1174 1179- def test_html4_pragma(self):1180- """HTML4 pragma directive"""1181- content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8">'1182- encodings = requests.utils.get_encodings_from_content(content)1183- assert len(encodings) == 11184- assert encodings[0] == 'UTF-8'1185-1186- def test_xhtml_pragma(self):1187- """XHTML 1.x served with text/html MIME type"""1188- content = '<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />'1189- encodings = requests.utils.get_encodings_from_content(content)1190- assert len(encodings) == 11191- assert encodings[0] == 'UTF-8'1192-1193- def test_xml(self):1194- """XHTML 1.x served as XML"""1195- content = '<?xml version="1.0" encoding="UTF-8"?>'1196- encodings = requests.utils.get_encodings_from_content(content)1197- assert len(encodings) == 11198- assert encodings[0] == 'UTF-8'1199-1175 def test_precedence(self):1176 content = '''1177 <?xml version="1.0" encoding="XML"?>1178 <meta charset="HTML5">2 unmodified lines1181 encodings = requests.utils.get_encodings_from_content(content)1182 assert encodings == ['HTML5', 'HTML4', 'XML']1183 1184 1210-class TestCaseInsensitiveDict(unittest.TestCase):1185+class TestCaseInsensitiveDict:1186 1212- def test_mapping_init(self):1213- cid = CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'})1187+ @pytest.mark.parametrize(1188+ 'cid',1189+ (1190+ CaseInsensitiveDict({'Foo': 'foo', 'BAr': 'bar'}),1191+ CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')]),1192+ CaseInsensitiveDict(FOO='foo', BAr='bar'),1193+ )1194+ )1195+ def test_init(self, cid):1196 assert len(cid) == 21197 assert 'foo' in cid1198 assert 'bar' in cid1199 1218- def test_iterable_init(self):1219- cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1220- assert len(cid) == 21221- assert 'foo' in cid1222- assert 'bar' in cid1223-1224- def test_kwargs_init(self):1225- cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1226- assert len(cid) == 21227- assert 'foo' in cid1228- assert 'bar' in cid1229-1200 def test_docstring_example(self):1201 cid = CaseInsensitiveDict()1202 cid['Accept'] = 'application/json'1203 assert cid['aCCEPT'] == 'application/json'121 unmodified lines1325 cid['changed'] = True1326 assert cid != cid_copy1327 1328 1359-class UtilsTestCase(unittest.TestCase):1329+class TestUtils:1330 1331 def test_super_len_io_streams(self):1332 """ Ensures that we properly deal with different kinds of IO streams. """1333 # uses StringIO or io.StringIO (see import above)102 unmodified lines1436 assert not address_in_network('172.16.0.1', '192.168.1.0/24')1437 1438 def test_get_auth_from_url(self):1439 """Ensures that username and password in well-encoded URI as per1470- RFC 3986 are correclty extracted."""1440+ RFC 3986 are correctly extracted."""1441 from requests.utils import get_auth_from_url1442 from requests.compat import quote1443 percent_encoding_test_chars = "%!*'();:@&=+$,/?#[] "1444 url_address = "request.com/url.html#test"20 unmodified lines1465 quoted = 'http://example.com/fiz?buz=%25ppicture'1466 assert quoted == requote_uri(quoted)1467 1468 1499-class TestMorselToCookieExpires(unittest.TestCase):1469+class TestMorselToCookieExpires:1470 1471 """Tests for morsel_to_cookie when morsel contains expires."""1472 1473 def test_expires_valid_str(self):3 unmodified lines1477 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1478 cookie = morsel_to_cookie(morsel)1479 assert cookie.expires == 11480 1481+ @pytest.mark.parametrize(1482+ 'value, exception',1483+ (1484+ (100, TypeError),1485+ ('woops', ValueError),1486+ )1487+ )1511- def test_expires_invalid_int(self):1488+ def test_expires_invalid_int(self, value, exception):1489 """Test case where an invalid type is passed for expires."""1513-1490 morsel = Morsel()1515- morsel['expires'] = 1001516- with pytest.raises(TypeError):1491+ morsel['expires'] = value1492+ with pytest.raises(exception):1493 morsel_to_cookie(morsel)1494 1519- def test_expires_invalid_str(self):1520- """Test case where an invalid string is input."""1521-1522- morsel = Morsel()1523- morsel['expires'] = 'woops'1524- with pytest.raises(ValueError):1525- morsel_to_cookie(morsel)1526-1495 def test_expires_none(self):1496 """Test case where expires is None."""1497 1498 morsel = Morsel()1 unmodified line1500 cookie = morsel_to_cookie(morsel)1501 assert cookie.expires is None1502 1503 1536-class TestMorselToCookieMaxAge(unittest.TestCase):1504+class TestMorselToCookieMaxAge:1505 1506 """Tests for morsel_to_cookie when morsel contains max-age."""1507 1508 def test_max_age_valid_int(self):43 unmodified lines1552 1553 def test_read_timeout(self, httpbin):1554 try:1555 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1588- assert False, "The recv() request should time out."1556+ pytest.fail('The recv() request should time out.')1557 except ReadTimeout:1558 pass1559 1560 def test_connect_timeout(self):1561 try:1562 requests.get(TARPIT, timeout=(0.1, None))1595- assert False, "The connect() request should time out."1563+ pytest.fail('The connect() request should time out.')1564 except ConnectTimeout as e:1565 assert isinstance(e, ConnectionError)1566 assert isinstance(e, Timeout)1567 1568 def test_total_timeout_connect(self):1569 try:1570 requests.get(TARPIT, timeout=(0.1, 0.1))1603- assert False, "The connect() request should time out."1571+ pytest.fail('The connect() request should time out.')1572 except ConnectTimeout:1573 pass1574 1575 def test_encoded_methods(self, httpbin):60 unmodified lines1636 TestRedirects.default_keyword_args)1637 assert session.calls[-1] == send_call1638 1639 1672-1640 @pytest.fixture1641 def list_of_tuples():1642 return [1643 (('a', 'b'), ('c', 'd')),86 unmodified lines1730 from requests.packages import chardet1731 1732 with pytest.raises(ImportError):1733 from requests.packages import webbrowser1767-1768-1769-if __name__ == '__main__':1770- unittest.main()added:tox.ini+8 added
1+[tox]2+envlist = py26, py27, py33, py34, py35, pypy3+4+[testenv]5+setenv =6+ PYTHONPATH = {toxinidir}:{toxinidir}/requests7+whitelist_externals = make8+commands = make test