Skip to content
Myr

Merge pull request #2991 from Stranger6667/tests-refactoring

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

[WIP] Test suite refactoring

authored by Kenneth Reitz · committed by Kenneth Reitz · parents b782e66, 6c2942b · 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

7 files+172 added−161 removed

added:.coveragerc+7 added
1[run]2omit = */packages/*34[report]5show_missing = true6precision = 27exclude_lines = pytest.fail
modified:.gitignore-1 removed
3 unmodified lines
4nosetests.xml5junit-report.xml6pylint.txt7toy.py8tox.ini8violations.pyflakes.txt9cover/10build/11docs/_build
12 unmodified lines
modified:AUTHORS.rst+2 added-1 removed
160 unmodified lines
161- 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 lines
56test:7 # This runs all of the tests. To run an individual test, run py.test with8 # the -k flag, like "py.test -k test_path_is_not_double_encoded"9 py.test test_requests.py9 python setup.py test -a "test_requests.py"1011coverage: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"1314ci: init15 py.test --junitxml=junit.xml16
23 unmodified lines
modified:setup.py+34 added-1 removed
1#!/usr/bin/env python23import os4import platform5import re6import sys78from codecs import open910from setuptools import setup11from setuptools.command.test import test as TestCommand121314JYTHON = platform.system() == 'Java'151617class PyTest(TestCommand):18 user_options = [('pytest-args=', 'a', "Arguments to pass into py.test")]1920 def initialize_options(self):21 TestCommand.initialize_options(self)22 self.pytest_args = []2324 def finalize_options(self):25 TestCommand.finalize_options(self)26 self.test_args = []27 self.test_suite = True2829 def run_tests(self):30 import pytest3132 errno = pytest.main(self.pytest_args)33 sys.exit(errno)343536if sys.argv[-1] == 'publish':37 os.system('python setup.py sdist upload')38 sys.exit()39
8 unmodified lines
48 'requests.packages.urllib3.packages.ssl_match_hostname',49]5051requires = []52test_requirements = ['pytest>=2.8.0', 'pytest-httpbin==0.0.7']5329version = ''54if not JYTHON:55 test_requirements.append('pytest-cov')5657with 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 lines
86 '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 lines
6from __future__ import division7import json8import os9import pickle10import unittest10import collections11import contextlib1213import io
58 unmodified lines
72# Requests to this URL should always fail with a connection timeout (nothing73# listening on that port)74TARPIT = "http://10.255.255.1"7577class TestRequests(object):7679 _multiprocess_can_split_ = True77class TestRequests:7881 def setUp(self):82 """Create simple data set with headers."""83 pass8485 def tearDown(self):86 """Teardown."""87 pass8879 def test_entry_points(self):8081 requests.session82 requests.session().get
3 unmodified lines
86 requests.put87 requests.patch88 requests.post89100 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)103104 def test_basic_building(self):105 req = requests.Request()106 req.url = 'http://kennethreitz.org/'
2 unmodified lines
109 pr = req.prepare()110 assert pr.url == req.url111 assert pr.body == 'life=42'112121 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.headers117118 def test_override_content_length(self, httpbin):119 headers = {120 'Content-Length': 'not zero'
6 unmodified lines
127 request = requests.Request('GET', "http://0.0.0.0/get/test case").prepare()128129 assert request.path_url == '/get/test%20case'130140 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 == expected141142 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 lines
155 request = requests.Request('PUT', 'http://example.com',156 data=u"ööö".encode("utf-8")).prepare()157 assert isinstance(request.body, bytes)158159 @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)168169 def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):170 r = requests.Request('GET', httpbin('get'))171 s = requests.Session()
143 unmodified lines
315 req = requests.Request('GET', httpbin('get'))316 prep = ses.prepare_request(req)317 assert 'Accept-Encoding' not in prep.headers318319 @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):321322 heads = {329 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'323 key: 'Mozilla/5.0 (github.com/kennethreitz/requests)'324 }325326 r = requests.get(httpbin('user-agent'), headers=heads)333 assert heads['User-agent'] in r.text327 assert heads[key] in r.text328335 heads = {336 'user-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'337 }338339 r = requests.get(httpbin('user-agent'), headers=heads)340 assert heads['user-agent'] in r.text341329 def test_HTTP_200_OK_HEAD(self, httpbin):330 r = requests.head(httpbin('get'))331 assert r.status_code == 200332
15 unmodified lines
348 s.auth = auth349 r = s.get(url)350 assert r.status_code == 200351365 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)366370 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)374375 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")379367 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 lines
466467 def test_POSTBIN_GET_POST_FILES(self, httpbin):468469 url = httpbin('post')483 post1 = requests.post(url).raise_for_status()470 requests.post(url).raise_for_status()471472 post1 = requests.post(url, data={'some': 'data'})473 assert post1.status_code == 200474
9 unmodified lines
484485 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):486487 url = httpbin('post')501 post1 = requests.post(url).raise_for_status()488 requests.post(url).raise_for_status()489490 post1 = requests.post(url, data={'some': 'data'})491 assert post1.status_code == 200492
29 unmodified lines
522 def test_decompress_gzip(self, httpbin):523 r = requests.get(httpbin('gzip'))524 r.content.decode('ascii')525539 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)538539 def test_unicode_header_name(self, httpbin):540 requests.put(541 httpbin('put'),
15 unmodified lines
557 params={'blah': 'asdf1234'},558 files={'file': ('test_requests.py', open(__file__, 'rb'))})559 assert r.status_code == 200560561 @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 == 200574575 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 == 200579580 r = requests.post(httpbin('post'),581 data={'stuff': 'elixr'},582 files={'file': ('test_requests.py', open(__file__, 'rb'))})583 assert r.status_code == 200584585 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 == 200589575 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 lines
611 assert b"text/py-content-type" in r.request.body612613 def test_hook_receives_request_arguments(self, httpbin):614 def hook(resp, **kwargs):615 # FIXME. Not executed616 assert resp is not None617 assert kwargs != {}618619 requests.Request('GET', httpbin(), hooks={'response': hook})
483 unmodified lines
1103 total = r.history[-1].history1104 i = 01105 for item in r.history:1106 assert item.history == total[0:i]1121 i = i + 11107 i += 111081109 def test_json_param_post_content_type_works(self, httpbin):1110 r = requests.post(1111 httpbin('post'),
36 unmodified lines
1148 next(r.iter_lines())1149 assert len(list(r.iter_lines())) == 3115011511166class TestContentEncodingDetection(unittest.TestCase):1152class TestContentEncodingDetection:11531154 def test_none(self):1155 encodings = requests.utils.get_encodings_from_content('')1156 assert not len(encodings)11571172 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'11741179 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'11851186 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'11921193 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'11991175 def test_precedence(self):1176 content = '''1177 <?xml version="1.0" encoding="XML"?>1178 <meta charset="HTML5">
2 unmodified lines
1181 encodings = requests.utils.get_encodings_from_content(content)1182 assert encodings == ['HTML5', 'HTML4', 'XML']118311841210class TestCaseInsensitiveDict(unittest.TestCase):1185class TestCaseInsensitiveDict:11861212 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 cid11991218 def test_iterable_init(self):1219 cid = CaseInsensitiveDict([('Foo', 'foo'), ('BAr', 'bar')])1220 assert len(cid) == 21221 assert 'foo' in cid1222 assert 'bar' in cid12231224 def test_kwargs_init(self):1225 cid = CaseInsensitiveDict(FOO='foo', BAr='bar')1226 assert len(cid) == 21227 assert 'foo' in cid1228 assert 'bar' in cid12291200 def test_docstring_example(self):1201 cid = CaseInsensitiveDict()1202 cid['Accept'] = 'application/json'1203 assert cid['aCCEPT'] == 'application/json'
121 unmodified lines
1325 cid['changed'] = True1326 assert cid != cid_copy132713281359class UtilsTestCase(unittest.TestCase):1329class TestUtils:13301331 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 lines
1436 assert not address_in_network('172.16.0.1', '192.168.1.0/24')14371438 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 lines
1465 quoted = 'http://example.com/fiz?buz=%25ppicture'1466 assert quoted == requote_uri(quoted)146714681499class TestMorselToCookieExpires(unittest.TestCase):1469class TestMorselToCookieExpires:14701471 """Tests for morsel_to_cookie when morsel contains expires."""14721473 def test_expires_valid_str(self):
3 unmodified lines
1477 morsel['expires'] = 'Thu, 01-Jan-1970 00:00:01 GMT'1478 cookie = morsel_to_cookie(morsel)1479 assert cookie.expires == 114801481 @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."""15131490 morsel = Morsel()1515 morsel['expires'] = 1001516 with pytest.raises(TypeError):1491 morsel['expires'] = value1492 with pytest.raises(exception):1493 morsel_to_cookie(morsel)14941519 def test_expires_invalid_str(self):1520 """Test case where an invalid string is input."""15211522 morsel = Morsel()1523 morsel['expires'] = 'woops'1524 with pytest.raises(ValueError):1525 morsel_to_cookie(morsel)15261495 def test_expires_none(self):1496 """Test case where expires is None."""14971498 morsel = Morsel()
1 unmodified line
1500 cookie = morsel_to_cookie(morsel)1501 assert cookie.expires is None150215031536class TestMorselToCookieMaxAge(unittest.TestCase):1504class TestMorselToCookieMaxAge:15051506 """Tests for morsel_to_cookie when morsel contains max-age."""15071508 def test_max_age_valid_int(self):
43 unmodified lines
15521553 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 pass15591560 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)15671568 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 pass15741575 def test_encoded_methods(self, httpbin):
60 unmodified lines
1636 TestRedirects.default_keyword_args)1637 assert session.calls[-1] == send_call1638163916721640@pytest.fixture1641def list_of_tuples():1642 return [1643 (('a', 'b'), ('c', 'd')),
86 unmodified lines
1730 from requests.packages import chardet17311732 with pytest.raises(ImportError):1733 from requests.packages import webbrowser176717681769if __name__ == '__main__':1770 unittest.main()
added:tox.ini+8 added
1[tox]2envlist = py26, py27, py33, py34, py35, pypy34[testenv]5setenv =6 PYTHONPATH = {toxinidir}:{toxinidir}/requests7whitelist_externals = make8commands = make test