Merge pull request #2859 from kennethreitz/pytest-httpbin
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Move test suite offline using pytest-httpbin
authored by Ian Cordasco · committed by Ian Cordasco · parents 4dffe5e, 43b90d7 · Browse files · 2 files·+141 added−137 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+141 added−137 removed
- other:+141 added−137 removed
Provenance
- Commit
f7e0494- Tree
95301b7- Author
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Committer
Ian Cordasco <sigmavirus24@users.noreply.github.com>- Parent 1
4dffe5e- Parent 2
43b90d7
2 files changed+141 added−137 removed
modified:requirements.txt+2 added
1 py==1.4.302 pytest==2.8.13 pytest-cov==2.1.04+pytest-httpbin==0.0.75+httpbin==0.4.06 wheelmodified:test_requests.py+139 added-137 removed
46 unmodified lines47 def u(s):48 return s.decode('unicode-escape')49 50 51-# Requests to this URL should always fail with a connection timeout (nothing52-# listening on that port)53-TARPIT = "http://10.255.255.1"54-HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')55-# Issue #1483: Make sure the URL always has a trailing slash56-HTTPBIN = HTTPBIN.rstrip('/') + '/'51+@pytest.fixture52+def httpbin(httpbin):53+ # Issue #1483: Make sure the URL always has a trailing slash54+ httpbin_url = httpbin.url.rstrip('/') + '/'55 56+ def inner(*suffix):57+ return urljoin(httpbin_url, '/'.join(suffix))58 59-def httpbin(*suffix):60- """Returns url for HTTPBIN resource."""61- return urljoin(HTTPBIN, '/'.join(suffix))59+ return inner60 61 64-class RequestsTestCase(unittest.TestCase):62+@pytest.fixture63+def httpsbin_url(httpbin_secure):64+ # Issue #1483: Make sure the URL always has a trailing slash65+ httpbin_url = httpbin_secure.url.rstrip('/') + '/'66 67+ def inner(*suffix):68+ return urljoin(httpbin_url, '/'.join(suffix))69+70+ return inner71+72+73+# Requests to this URL should always fail with a connection timeout (nothing74+# listening on that port)75+TARPIT = "http://10.255.255.1"76+77+class TestRequests(object):78+79 _multiprocess_can_split_ = True80 81 def setUp(self):82 """Create simple data set with headers."""34 unmodified lines117 pr = req.prepare()118 assert pr.url == req.url119 assert pr.body == 'life=42'120 108- def test_no_content_length(self):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.headers126 114- def test_override_content_length(self):127+ def test_override_content_length(self, httpbin):128 headers = {129 'Content-Length': 'not zero'130 }131 r = requests.Request('POST', httpbin('post'), headers=headers).prepare()24 unmodified lines156 request = requests.Request('GET', 'http://example.com',157 params=b'test=foo').prepare()158 assert request.url == 'http://example.com/?test=foo'159 147- def test_mixed_case_scheme_acceptable(self):160+ def test_mixed_case_scheme_acceptable(self, httpbin):161 s = requests.Session()162 s.proxies = getproxies()163 parts = urlparse(httpbin('get'))151- schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://',152- 'https://', 'HTTPS://', 'hTTps://', 'HttPs://']164+ schemes = ['http://', 'HTTP://', 'hTTp://', 'HttP://']165 for scheme in schemes:166 url = scheme + parts.netloc + parts.path167 r = requests.Request('GET', url)168 r = s.send(r.prepare())169 assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)170 159- def test_HTTP_200_OK_GET_ALTERNATIVE(self):171+ def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):172 r = requests.Request('GET', httpbin('get'))173 s = requests.Session()174 s.proxies = getproxies()175 176 r = s.send(r.prepare())177 178 assert r.status_code == 200179 168- def test_HTTP_302_ALLOW_REDIRECT_GET(self):180+ def test_HTTP_302_ALLOW_REDIRECT_GET(self, httpbin):181 r = requests.get(httpbin('redirect', '1'))182 assert r.status_code == 200183 assert r.history[0].status_code == 302184 assert r.history[0].is_redirect1 unmodified line186 # def test_HTTP_302_ALLOW_REDIRECT_POST(self):187 # r = requests.post(httpbin('status', '302'), data={'some': 'data'})188 # self.assertEqual(r.status_code, 200)189 178- def test_HTTP_200_OK_GET_WITH_PARAMS(self):190+ def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):191 heads = {'User-agent': 'Mozilla/5.0'}192 193 r = requests.get(httpbin('user-agent'), headers=heads)194 195 assert heads['User-agent'] in r.text196 assert r.status_code == 200197 186- def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self):198+ def test_HTTP_200_OK_GET_WITH_MIXED_PARAMS(self, httpbin):199 heads = {'User-agent': 'Mozilla/5.0'}200 201 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)202 assert r.status_code == 200203 192- def test_set_cookie_on_301(self):204+ def test_set_cookie_on_301(self, httpbin):205 s = requests.session()206 url = httpbin('cookies/set?foo=bar')207 s.get(url)208 assert s.cookies['foo'] == 'bar'209 198- def test_cookie_sent_on_redirect(self):210+ def test_cookie_sent_on_redirect(self, httpbin):211 s = requests.session()212 s.get(httpbin('cookies/set?foo=bar'))213 r = s.get(httpbin('redirect/1')) # redirects to httpbin('get')214 assert 'Cookie' in r.json()['headers']215 204- def test_cookie_removed_on_expire(self):216+ def test_cookie_removed_on_expire(self, httpbin):217 s = requests.session()218 s.get(httpbin('cookies/set?foo=bar'))219 assert s.cookies['foo'] == 'bar'220 s.get(4 unmodified lines225 }226 )227 assert 'foo' not in s.cookies228 217- def test_cookie_quote_wrapped(self):229+ def test_cookie_quote_wrapped(self, httpbin):230 s = requests.session()231 s.get(httpbin('cookies/set?foo="bar:baz"'))232 assert s.cookies['foo'] == '"bar:baz"'233 222- def test_cookie_persists_via_api(self):234+ def test_cookie_persists_via_api(self, httpbin):235 s = requests.session()236 r = s.get(httpbin('redirect/1'), cookies={'foo': 'bar'})237 assert 'foo' in r.request.headers['Cookie']238 assert 'foo' in r.history[0].request.headers['Cookie']239 228- def test_request_cookie_overrides_session_cookie(self):240+ def test_request_cookie_overrides_session_cookie(self, httpbin):241 s = requests.session()242 s.cookies['foo'] = 'bar'243 r = s.get(httpbin('cookies'), cookies={'foo': 'baz'})244 assert r.json()['cookies']['foo'] == 'baz'245 # Session cookie should not be modified246 assert s.cookies['foo'] == 'bar'247 236- def test_request_cookies_not_persisted(self):248+ def test_request_cookies_not_persisted(self, httpbin):249 s = requests.session()250 s.get(httpbin('cookies'), cookies={'foo': 'baz'})251 # Sending a request with cookies should not add cookies to the session252 assert not s.cookies253 242- def test_generic_cookiejar_works(self):254+ def test_generic_cookiejar_works(self, httpbin):255 cj = cookielib.CookieJar()256 cookiejar_from_dict({'foo': 'bar'}, cj)257 s = requests.session()258 s.cookies = cj2 unmodified lines261 assert r.json()['cookies']['foo'] == 'bar'262 # Make sure the session cj is still the custom one263 assert s.cookies is cj264 253- def test_param_cookiejar_works(self):265+ def test_param_cookiejar_works(self, httpbin):266 cj = cookielib.CookieJar()267 cookiejar_from_dict({'foo': 'bar'}, cj)268 s = requests.session()269 r = s.get(httpbin('cookies'), cookies=cj)270 # Make sure the cookie was sent271 assert r.json()['cookies']['foo'] == 'bar'272 261- def test_requests_in_history_are_not_overridden(self):273+ def test_requests_in_history_are_not_overridden(self, httpbin):274 resp = requests.get(httpbin('redirect/3'))275 urls = [r.url for r in resp.history]276 req_urls = [r.request.url for r in resp.history]277 assert urls == req_urls278 267- def test_history_is_always_a_list(self):279+ def test_history_is_always_a_list(self, httpbin):280 """281 Show that even with redirects, Response.history is always a list.282 """283 resp = requests.get(httpbin('get'))1 unmodified line285 resp = requests.get(httpbin('redirect/1'))286 assert isinstance(resp.history, list)287 assert not isinstance(resp.history, tuple)288 277- def test_headers_on_session_with_None_are_not_sent(self):289+ def test_headers_on_session_with_None_are_not_sent(self, httpbin):290 """Do not send headers in Session.headers with None values."""291 ses = requests.Session()292 ses.headers['Accept-Encoding'] = None293 req = requests.Request('GET', httpbin('get'))294 prep = ses.prepare_request(req)295 assert 'Accept-Encoding' not in prep.headers296 285- def test_user_agent_transfers(self):297+ def test_user_agent_transfers(self, httpbin):298 299 heads = {300 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'301 }7 unmodified lines309 310 r = requests.get(httpbin('user-agent'), headers=heads)311 assert heads['user-agent'] in r.text312 301- def test_HTTP_200_OK_HEAD(self):313+ def test_HTTP_200_OK_HEAD(self, httpbin):314 r = requests.head(httpbin('get'))315 assert r.status_code == 200316 305- def test_HTTP_200_OK_PUT(self):317+ def test_HTTP_200_OK_PUT(self, httpbin):318 r = requests.put(httpbin('put'))319 assert r.status_code == 200320 309- def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self):321+ def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):322 auth = ('user', 'pass')323 url = httpbin('basic-auth', 'user', 'pass')324 325 r = requests.get(url, auth=auth)14 unmodified lines340 341 def test_connection_error_invalid_port(self):342 """Connecting to an invalid port should raise a ConnectionError"""343 with pytest.raises(ConnectionError):332- requests.get("http://httpbin.org:1", timeout=1)344+ requests.get("http://localhost:1", timeout=1)345 346 def test_LocationParseError(self):347 """Inputing a URL that cannot be parsed should raise an InvalidURL error"""348 with pytest.raises(InvalidURL):349 requests.get("http://fe80::5054:ff:fe5a:fc0")350 339- def test_basicauth_with_netrc(self):351+ def test_basicauth_with_netrc(self, httpbin):352 auth = ('user', 'pass')353 wrong_auth = ('wronguser', 'wrongpass')354 url = httpbin('basic-auth', 'user', 'pass')355 344- def get_netrc_auth_mock(url):345- return auth346- requests.sessions.get_netrc_auth = get_netrc_auth_mock356+ old_auth = requests.sessions.get_netrc_auth357 348- # Should use netrc and work.349- r = requests.get(url)350- assert r.status_code == 200358+ try:359+ def get_netrc_auth_mock(url):360+ return auth361+ requests.sessions.get_netrc_auth = get_netrc_auth_mock362 352- # Given auth should override and fail.353- r = requests.get(url, auth=wrong_auth)354- assert r.status_code == 401363+ # Should use netrc and work.364+ r = requests.get(url)365+ assert r.status_code == 200366 356- s = requests.session()367+ # Given auth should override and fail.368+ r = requests.get(url, auth=wrong_auth)369+ assert r.status_code == 401370 358- # Should use netrc and work.359- r = s.get(url)360- assert r.status_code == 200371+ s = requests.session()372 362- # Given auth should override and fail.363- s.auth = wrong_auth364- r = s.get(url)365- assert r.status_code == 401373+ # Should use netrc and work.374+ r = s.get(url)375+ assert r.status_code == 200376 367- def test_DIGEST_HTTP_200_OK_GET(self):377+ # Given auth should override and fail.378+ s.auth = wrong_auth379+ r = s.get(url)380+ assert r.status_code == 401381+ finally:382+ requests.sessions.get_netrc_auth = old_auth383 384+ def test_DIGEST_HTTP_200_OK_GET(self, httpbin):385+386 auth = HTTPDigestAuth('user', 'pass')387 url = httpbin('digest-auth', 'auth', 'user', 'pass')388 389 r = requests.get(url, auth=auth)6 unmodified lines396 s.auth = HTTPDigestAuth('user', 'pass')397 r = s.get(url)398 assert r.status_code == 200399 383- def test_DIGEST_AUTH_RETURNS_COOKIE(self):400+ def test_DIGEST_AUTH_RETURNS_COOKIE(self, httpbin):401 url = httpbin('digest-auth', 'auth', 'user', 'pass')402 auth = HTTPDigestAuth('user', 'pass')403 r = requests.get(url)404 assert r.cookies['fake'] == 'fake_value'405 406 r = requests.get(url, auth=auth)407 assert r.status_code == 200408 392- def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self):409+ def test_DIGEST_AUTH_SETS_SESSION_COOKIES(self, httpbin):410 url = httpbin('digest-auth', 'auth', 'user', 'pass')411 auth = HTTPDigestAuth('user', 'pass')412 s = requests.Session()413 s.get(url, auth=auth)414 assert s.cookies['fake'] == 'fake_value'415 399- def test_DIGEST_STREAM(self):416+ def test_DIGEST_STREAM(self, httpbin):417 418 auth = HTTPDigestAuth('user', 'pass')419 url = httpbin('digest-auth', 'auth', 'user', 'pass')420 2 unmodified lines423 424 r = requests.get(url, auth=auth, stream=False)425 assert r.raw.read() == b''426 410- def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):427+ def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):428 429 auth = HTTPDigestAuth('user', 'wrongpass')430 url = httpbin('digest-auth', 'auth', 'user', 'pass')431 7 unmodified lines439 s.auth = auth440 r = s.get(url)441 assert r.status_code == 401442 426- def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):443+ def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):444 445 auth = HTTPDigestAuth('user', 'pass')446 url = httpbin('digest-auth', 'auth', 'user', 'pass')447 448 r = requests.get(url, auth=auth)449 assert '"auth"' in r.request.headers['Authorization']450 434- def test_DIGESTAUTH_THREADED(self):451+ def test_POSTBIN_GET_POST_FILES(self, httpbin):452 436- auth = HTTPDigestAuth('user', 'pass')437- url = httpbin('digest-auth', 'auth', 'user', 'pass')438- session = requests.Session()439- session.auth=auth440-441- def do_request(i):442- r = session.get(url)443- assert '"auth"' in r.request.headers['Authorization']444- return 1445- if ThreadPool is not None:446- pool = ThreadPool(processes=50)447- pool.map(do_request, range(100))448-449- def test_POSTBIN_GET_POST_FILES(self):450-453 url = httpbin('post')454 post1 = requests.post(url).raise_for_status()455 456 post1 = requests.post(url, data={'some': 'data'})8 unmodified lines465 466 with pytest.raises(ValueError):467 requests.post(url, files=['bad file data'])468 467- def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):469+ def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):470 471 url = httpbin('post')472 post1 = requests.post(url).raise_for_status()473 10 unmodified lines484 485 with pytest.raises(ValueError):486 requests.post(url, files=['bad file data'])487 486- def test_conflicting_post_params(self):488+ def test_conflicting_post_params(self, httpbin):489 url = httpbin('post')490 with open('requirements.txt') as f:491 pytest.raises(ValueError, "requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})")492 pytest.raises(ValueError, "requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})")493 492- def test_request_ok_set(self):494+ def test_request_ok_set(self, httpbin):495 r = requests.get(httpbin('status', '404'))496 assert not r.ok497 496- def test_status_raising(self):498+ def test_status_raising(self, httpbin):499 r = requests.get(httpbin('status', '404'))500 with pytest.raises(requests.exceptions.HTTPError):501 r.raise_for_status()502 503 r = requests.get(httpbin('status', '500'))504 assert not r.ok505 504- def test_decompress_gzip(self):506+ def test_decompress_gzip(self, httpbin):507 r = requests.get(httpbin('gzip'))508 r.content.decode('ascii')509 508- def test_unicode_get(self):510+ def test_unicode_get(self, httpbin):511 url = httpbin('/get')512 requests.get(url, params={'foo': 'føø'})513 requests.get(url, params={'føø': 'føø'})514 requests.get(url, params={'føø': 'føø'})515 requests.get(url, params={'foo': 'foo'})516 requests.get(httpbin('ø'), params={'foo': 'foo'})517 516- def test_unicode_header_name(self):518+ def test_unicode_header_name(self, httpbin):519 requests.put(520 httpbin('put'),521 headers={str('Content-Type'): 'application/octet-stream'},522 data='\xff') # compat.str is unicode.523 522- def test_pyopenssl_redirect(self):523- requests.get('https://httpbin.org/status/301')524+ def test_pyopenssl_redirect(self, httpsbin_url, httpbin_ca_bundle):525+ requests.get(httpsbin_url('status', '301'), verify=httpbin_ca_bundle)526 525- def test_urlencoded_get_query_multivalued_param(self):527+ def test_urlencoded_get_query_multivalued_param(self, httpbin):528 529 r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))530 assert r.status_code == 200531 assert r.url == httpbin('get?test=foo&test=baz')532 531- def test_different_encodings_dont_break_post(self):533+ def test_different_encodings_dont_break_post(self, httpbin):534 r = requests.post(httpbin('post'),535 data={'stuff': json.dumps({'a': 123})},536 params={'blah': 'asdf1234'},537 files={'file': ('test_requests.py', open(__file__, 'rb'))})538 assert r.status_code == 200539 538- def test_unicode_multipart_post(self):540+ def test_unicode_multipart_post(self, httpbin):541 r = requests.post(httpbin('post'),542 data={'stuff': u('ëlïxr')},543 files={'file': ('test_requests.py', open(__file__, 'rb'))})544 assert r.status_code == 20012 unmodified lines557 data={'stuff': 'elixr'.encode('utf-8')},558 files={'file': ('test_requests.py', open(__file__, 'rb'))})559 assert r.status_code == 200560 559- def test_unicode_multipart_post_fieldnames(self):561+ def test_unicode_multipart_post_fieldnames(self, httpbin):562 filename = os.path.splitext(__file__)[0] + '.py'563 r = requests.Request(method='POST',564 url=httpbin('post'),565 data={'stuff'.encode('utf-8'): 'elixr'},2 unmodified lines568 prep = r.prepare()569 assert b'name="stuff"' in prep.body570 assert b'name="b\'stuff\'"' not in prep.body571 570- def test_unicode_method_name(self):572+ def test_unicode_method_name(self, httpbin):573 files = {'file': open('test_requests.py', 'rb')}574 r = requests.request(575 method=u('POST'), url=httpbin('post'), files=files)576 assert r.status_code == 200577 576- def test_unicode_method_name_with_request_object(self):578+ def test_unicode_method_name_with_request_object(self, httpbin):579 files = {'file': open('test_requests.py', 'rb')}580 s = requests.Session()581 req = requests.Request(u("POST"), httpbin('post'), files=files)582 prep = s.prepare_request(req)2 unmodified lines585 586 resp = s.send(prep)587 assert resp.status_code == 200588 587- def test_custom_content_type(self):589+ def test_custom_content_type(self, httpbin):590 r = requests.post(591 httpbin('post'),592 data={'stuff': json.dumps({'a': 123})},593 files={'file1': ('test_requests.py', open(__file__, 'rb')),1 unmodified line595 'text/py-content-type')})596 assert r.status_code == 200597 assert b"text/py-content-type" in r.request.body598 597- def test_hook_receives_request_arguments(self):599+ def test_hook_receives_request_arguments(self, httpbin):600 def hook(resp, **kwargs):601 assert resp is not None602 assert kwargs != {}603 602- requests.Request('GET', HTTPBIN, hooks={'response': hook})604+ requests.Request('GET', httpbin(), hooks={'response': hook})605 604- def test_session_hooks_are_used_with_no_request_hooks(self):606+ def test_session_hooks_are_used_with_no_request_hooks(self, httpbin):607 hook = lambda x, *args, **kwargs: x608 s = requests.Session()609 s.hooks['response'].append(hook)608- r = requests.Request('GET', HTTPBIN)610+ r = requests.Request('GET', httpbin())611 prep = s.prepare_request(r)612 assert prep.hooks['response'] != []613 assert prep.hooks['response'] == [hook]614 613- def test_session_hooks_are_overriden_by_request_hooks(self):615+ def test_session_hooks_are_overriden_by_request_hooks(self, httpbin):616 hook1 = lambda x, *args, **kwargs: x617 hook2 = lambda x, *args, **kwargs: x618 assert hook1 is not hook2619 s = requests.Session()620 s.hooks['response'].append(hook2)619- r = requests.Request('GET', HTTPBIN, hooks={'response': [hook1]})621+ r = requests.Request('GET', httpbin(), hooks={'response': [hook1]})622 prep = s.prepare_request(r)623 assert prep.hooks['response'] == [hook1]624 623- def test_prepared_request_hook(self):625+ def test_prepared_request_hook(self, httpbin):626 def hook(resp, **kwargs):627 resp.hook_working = True628 return resp629 628- req = requests.Request('GET', HTTPBIN, hooks={'response': hook})630+ req = requests.Request('GET', httpbin(), hooks={'response': hook})631 prep = req.prepare()632 633 s = requests.Session()634 s.proxies = getproxies()635 resp = s.send(prep)636 637 assert hasattr(resp, 'hook_working')638 637- def test_prepared_from_session(self):639+ def test_prepared_from_session(self, httpbin):640 class DummyAuth(requests.auth.AuthBase):641 def __call__(self, r):642 r.headers['Dummy-Auth-Test'] = 'dummy-auth-test-ok'643 return r144 unmodified lines788 assert items == list(items)789 # make sure one can use items multiple times790 assert list(items) == list(items)791 790- def test_time_elapsed_blank(self):792+ def test_time_elapsed_blank(self, httpbin):793 r = requests.get(httpbin('get'))794 td = r.elapsed795 total_seconds = ((td.microseconds + (td.seconds + td.days * 24 * 3600)796 * 10**6) / 10**6)30 unmodified lines827 r.encoding = 'ascii'828 chunks = r.iter_content(decode_unicode=True)829 assert all(isinstance(chunk, str) for chunk in chunks)830 829- def test_request_and_response_are_pickleable(self):831+ def test_request_and_response_are_pickleable(self, httpbin):832 r = requests.get(httpbin('get'))833 834 # verify we can pickle the original request835 assert pickle.loads(pickle.dumps(r.request))23 unmodified lines859 def test_get_auth_from_url_encoded_hashes(self):860 url = 'http://user:pass%23pass@complex.url.com/path?query=yes'861 assert ('user', 'pass#pass') == requests.utils.get_auth_from_url(url)862 861- def test_cannot_send_unprepared_requests(self):862- r = requests.Request(url=HTTPBIN)863+ def test_cannot_send_unprepared_requests(self, httpbin):864+ r = requests.Request(url=httpbin())865 with pytest.raises(ValueError):866 requests.Session().send(r)867 868 def test_http_error(self):5 unmodified lines874 error = requests.exceptions.HTTPError('message', response=response)875 assert str(error) == 'message'876 assert error.response == response877 876- def test_session_pickling(self):878+ def test_session_pickling(self, httpbin):879 r = requests.Request('GET', httpbin('get'))880 s = requests.Session()881 882 s = pickle.loads(pickle.dumps(s))1 unmodified line884 885 r = s.send(r.prepare())886 assert r.status_code == 200887 886- def test_fixes_1329(self):888+ def test_fixes_1329(self, httpbin):889 """890 Ensure that header updates are done case-insensitively.891 """892 s = requests.Session()4 unmodified lines897 assert headers['accept'] == 'application/json'898 assert headers['Accept'] == 'application/json'899 assert headers['ACCEPT'] == 'application/json'900 899- def test_uppercase_scheme_redirect(self):901+ def test_uppercase_scheme_redirect(self, httpbin):902 parts = urlparse(httpbin('html'))903 url = "HTTP://" + parts.netloc + parts.path904 r = requests.get(httpbin('redirect-to'), params={'url': url})905 assert r.status_code == 20036 unmodified lines942 s2.mount('https://', HTTPAdapter())943 assert 'http://' in s2.adapters944 assert 'https://' in s2.adapters945 944- def test_header_remove_is_case_insensitive(self):946+ def test_header_remove_is_case_insensitive(self, httpbin):947 # From issue #1321948 s = requests.Session()949 s.headers['foo'] = 'bar'950 r = s.get(httpbin('get'), headers={'FOO': None})951 assert 'foo' not in r.request.headers952 951- def test_params_are_merged_case_sensitive(self):953+ def test_params_are_merged_case_sensitive(self, httpbin):954 s = requests.Session()955 s.params['foo'] = 'bar'956 r = s.get(httpbin('get'), params={'FOO': 'bar'})957 assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}6 unmodified lines964 )965 r = requests.Request('GET', url).prepare()966 assert r.url == url967 966- def test_header_keys_are_native(self):968+ def test_header_keys_are_native(self, httpbin):969 headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}970 r = requests.Request('GET', httpbin('get'), headers=headers)971 p = r.prepare()972 1 unmodified line974 # we go.975 assert 'unicode' in p.headers.keys()976 assert 'byte' in p.headers.keys()977 976- def test_can_send_nonstring_objects_with_files(self):978+ def test_can_send_nonstring_objects_with_files(self, httpbin):979 data = {'a': 0.0}980 files = {'b': 'foo'}981 r = requests.Request('POST', httpbin('post'), data=data, files=files)982 p = r.prepare()983 984 assert 'multipart/form-data' in p.headers['Content-Type']985 984- def test_can_send_bytes_bytearray_objects_with_files(self):986+ def test_can_send_bytes_bytearray_objects_with_files(self, httpbin):987 # Test bytes:988 data = {'a': 'this is a string'}989 files = {'b': b'foo'}990 r = requests.Request('POST', httpbin('post'), data=data, files=files)4 unmodified lines995 r = requests.Request('POST', httpbin('post'), data=data, files=files)996 p = r.prepare()997 assert 'multipart/form-data' in p.headers['Content-Type']998 997- def test_can_send_file_object_with_non_string_filename(self):999+ def test_can_send_file_object_with_non_string_filename(self, httpbin):1000 f = io.BytesIO()1001 f.name = 21002 r = requests.Request('POST', httpbin('post'), files={'f': f})1003 p = r.prepare()1004 1005 assert 'multipart/form-data' in p.headers['Content-Type']1006 1005- def test_autoset_header_values_are_native(self):1007+ def test_autoset_header_values_are_native(self, httpbin):1008 data = 'this is a string'1009 length = '16'1010 req = requests.Request('POST', httpbin('post'), data=data)1011 p = req.prepare()10 unmodified lines1022 req = requests.Request('GET', test_url)1023 preq = req.prepare()1024 assert test_url == preq.url1025 1024- def test_auth_is_stripped_on_redirect_off_host(self):1026+ def test_auth_is_stripped_on_redirect_off_host(self, httpbin):1027 r = requests.get(1028 httpbin('redirect-to'),1029 params={'url': 'http://www.google.co.uk'},1030 auth=('user', 'pass'),1031 )1032 assert r.history[0].request.headers['Authorization']1033 assert not r.request.headers.get('Authorization', '')1034 1033- def test_auth_is_retained_for_redirect_on_host(self):1035+ def test_auth_is_retained_for_redirect_on_host(self, httpbin):1036 r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))1037 h1 = r.history[0].request.headers['Authorization']1038 h2 = r.request.headers['Authorization']1039 1040 assert h1 == h21041 1040- def test_manual_redirect_with_partial_body_read(self):1042+ def test_manual_redirect_with_partial_body_read(self, httpbin):1043 s = requests.Session()1044 r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)1045 assert r1.is_redirect1046 rg = s.resolve_redirects(r1, r1.request, stream=True)24 unmodified lines1071 return resp1072 1073 adapter.build_response = build_response1074 1073- def test_redirect_with_wrong_gzipped_header(self):1075+ def test_redirect_with_wrong_gzipped_header(self, httpbin):1076 s = requests.Session()1077 url = httpbin('redirect/1')1078 self._patch_adapter_gzipped_redirect(s, url)1079 s.get(url)2 unmodified lines1082 s = _basic_auth_str("test", "test")1083 assert isinstance(s, builtin_str)1084 assert s == "Basic dGVzdDp0ZXN0"1085 1084- def test_requests_history_is_saved(self):1086+ def test_requests_history_is_saved(self, httpbin):1087 r = requests.get(httpbin('redirect/5'))1088 total = r.history[-1].history1089 i = 01090 for item in r.history:1091 assert item.history == total[0:i]1092 i = i + 11093 1092- def test_json_param_post_content_type_works(self):1094+ def test_json_param_post_content_type_works(self, httpbin):1095 r = requests.post(1096 httpbin('post'),1097 json={'life': 42}1098 )1099 assert r.status_code == 2001100 assert 'application/json' in r.request.headers['Content-Type']1101 assert {'life': 42} == r.json()['json']1102 1101- def test_json_param_post_should_not_override_data_param(self):1102- r = requests.Request(method='POST', url='http://httpbin.org/post',1103+ def test_json_param_post_should_not_override_data_param(self, httpbin):1104+ r = requests.Request(method='POST', url=httpbin('post'),1105 data={'stuff': 'elixr'},1106 json={'music': 'flute'})1107 prep = r.prepare()1108 assert 'stuff=elixr' == prep.body1109 1108- def test_response_iter_lines(self):1110+ def test_response_iter_lines(self, httpbin):1111 r = requests.get(httpbin('stream/4'), stream=True)1112 assert r.status_code == 2001113 1114 it = r.iter_lines()1115 next(it)1116 assert len(list(it)) == 31117 1116- def test_unconsumed_session_response_closes_connection(self):1118+ def test_unconsumed_session_response_closes_connection(self, httpbin):1119 s = requests.session()1120 1121 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1122 pass1123 1122- self.assertFalse(response._content_consumed)1123- self.assertTrue(response.raw.closed)1124+ assert response._content_consumed is False1125+ assert response.raw.closed1126 1127 @pytest.mark.xfail1126- def test_response_iter_lines_reentrant(self):1128+ def test_response_iter_lines_reentrant(self, httpbin):1129 """Response.iter_lines() is not reentrant safe"""1130 r = requests.get(httpbin('stream/4'), stream=True)1131 assert r.status_code == 2001132 385 unmodified lines1518 morsel_to_cookie(morsel)1519 1520 1521 class TestTimeout:1520- def test_stream_timeout(self):1522+ def test_stream_timeout(self, httpbin):1523 try:1524 requests.get(httpbin('delay/10'), timeout=2.0)1525 except requests.exceptions.Timeout as e:1526 assert 'Read timed out' in e.args[0].args[0]1527 1526- def test_invalid_timeout(self):1528+ def test_invalid_timeout(self, httpbin):1529 with pytest.raises(ValueError) as e:1530 requests.get(httpbin('get'), timeout=(3, 4, 5))1531 assert '(connect, read)' in str(e)1532 1533 with pytest.raises(ValueError) as e:1534 requests.get(httpbin('get'), timeout="foo")1535 assert 'must be an int or float' in str(e)1536 1535- def test_none_timeout(self):1537+ def test_none_timeout(self, httpbin):1538 """ Check that you can set None as a valid timeout value.1539 1540 To actually test this behavior, we'd want to check that setting the1541 timeout to None actually lets the request block past the system default3 unmodified lines1545 """1546 r = requests.get(httpbin('get'), timeout=None)1547 assert r.status_code == 2001548 1547- def test_read_timeout(self):1549+ def test_read_timeout(self, httpbin):1550 try:1551 requests.get(httpbin('delay/10'), timeout=(None, 0.1))1552 assert False, "The recv() request should time out."1553 except ReadTimeout:13 unmodified lines1567 assert False, "The connect() request should time out."1568 except ConnectTimeout:1569 pass1570 1569- def test_encoded_methods(self):1571+ def test_encoded_methods(self, httpbin):1572 """See: https://github.com/kennethreitz/requests/issues/2316"""1573 r = requests.request(b'GET', httpbin('get'))1574 assert r.ok1575 42 unmodified lines1618 'allow_redirects': False,1619 'proxies': {},1620 }1621 1620- def test_requests_are_updated_each_time(self):1622+ def test_requests_are_updated_each_time(self, httpbin):1623 session = RedirectSession([303, 307])1624 prep = requests.Request('POST', httpbin('post')).prepare()1625 r0 = session.send(prep)1626 assert r0.request.method == 'POST'73 unmodified lines1700 )1701 assert_copy(p, p.copy())1702 1703 1702-def test_urllib3_retries():1704+def test_urllib3_retries(httpbin):1705 from requests.packages.urllib3.util import Retry1706 s = requests.Session()1707 s.mount('http://', HTTPAdapter(max_retries=Retry(1708 total=2, status_forcelist=[500]2 unmodified lines1711 with pytest.raises(RetryError):1712 s.get(httpbin('status/500'))1713 1714 1713-def test_urllib3_pool_connection_closed():1715+def test_urllib3_pool_connection_closed(httpbin):1716 s = requests.Session()1717 s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))1718 1719 try:1720 s.get(httpbin('status/200'))1721 except ConnectionError as e:1720- assert u"HTTPConnectionPool(host='httpbin.org', port=80): Pool is closed." in str(e)1722+ assert u"Pool is closed." in str(e)1723 1724 def test_vendor_aliases():1725 from requests.packages import urllib31726 from requests.packages import chardet6 unmodified lines