Skip to content
Myr

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

2 files+141 added−137 removed

modified:requirements.txt+2 added
1py==1.4.302pytest==2.8.13pytest-cov==2.1.04pytest-httpbin==0.0.75httpbin==0.4.06wheel
modified:test_requests.py+139 added-137 removed
46 unmodified lines
47 def u(s):48 return s.decode('unicode-escape')495051# Requests to this URL should always fail with a connection timeout (nothing52# listening on that port)53TARPIT = "http://10.255.255.1"54HTTPBIN = os.environ.get('HTTPBIN_URL', 'http://httpbin.org/')55# Issue #1483: Make sure the URL always has a trailing slash56HTTPBIN = HTTPBIN.rstrip('/') + '/'51@pytest.fixture52def httpbin(httpbin):53 # Issue #1483: Make sure the URL always has a trailing slash54 httpbin_url = httpbin.url.rstrip('/') + '/'5556 def inner(*suffix):57 return urljoin(httpbin_url, '/'.join(suffix))5859def httpbin(*suffix):60 """Returns url for HTTPBIN resource."""61 return urljoin(HTTPBIN, '/'.join(suffix))59 return inner606164class RequestsTestCase(unittest.TestCase):62@pytest.fixture63def httpsbin_url(httpbin_secure):64 # Issue #1483: Make sure the URL always has a trailing slash65 httpbin_url = httpbin_secure.url.rstrip('/') + '/'6667 def inner(*suffix):68 return urljoin(httpbin_url, '/'.join(suffix))6970 return inner717273# Requests to this URL should always fail with a connection timeout (nothing74# listening on that port)75TARPIT = "http://10.255.255.1"7677class TestRequests(object):7879 _multiprocess_can_split_ = True8081 def setUp(self):82 """Create simple data set with headers."""
34 unmodified lines
117 pr = req.prepare()118 assert pr.url == req.url119 assert pr.body == 'life=42'120108 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.headers126114 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 lines
156 request = requests.Request('GET', 'http://example.com',157 params=b'test=foo').prepare()158 assert request.url == 'http://example.com/?test=foo'159147 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)170159 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()175176 r = s.send(r.prepare())177178 assert r.status_code == 200179168 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_redirect
1 unmodified line
186 # 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)189178 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'}192193 r = requests.get(httpbin('user-agent'), headers=heads)194195 assert heads['User-agent'] in r.text196 assert r.status_code == 200197186 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'}200201 r = requests.get(httpbin('get') + '?test=true', params={'q': 'test'}, headers=heads)202 assert r.status_code == 200203192 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'209198 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']215204 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 lines
225 }226 )227 assert 'foo' not in s.cookies228217 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"'233222 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']239228 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'247236 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.cookies253242 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 = cj
2 unmodified lines
261 assert r.json()['cookies']['foo'] == 'bar'262 # Make sure the session cj is still the custom one263 assert s.cookies is cj264253 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'272261 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_urls278267 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 line
285 resp = requests.get(httpbin('redirect/1'))286 assert isinstance(resp.history, list)287 assert not isinstance(resp.history, tuple)288277 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.headers296285 def test_user_agent_transfers(self):297 def test_user_agent_transfers(self, httpbin):298299 heads = {300 'User-agent': 'Mozilla/5.0 (github.com/kennethreitz/requests)'301 }
7 unmodified lines
309310 r = requests.get(httpbin('user-agent'), headers=heads)311 assert heads['user-agent'] in r.text312301 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 == 200316305 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 == 200320309 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')324325 r = requests.get(url, auth=auth)
14 unmodified lines
340341 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)345346 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")350339 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')355344 def get_netrc_auth_mock(url):345 return auth346 requests.sessions.get_netrc_auth = get_netrc_auth_mock356 old_auth = requests.sessions.get_netrc_auth357348 # 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_mock362352 # 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 == 200366356 s = requests.session()367 # Given auth should override and fail.368 r = requests.get(url, auth=wrong_auth)369 assert r.status_code == 401370358 # Should use netrc and work.359 r = s.get(url)360 assert r.status_code == 200371 s = requests.session()372362 # 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 == 200376367 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_auth383384 def test_DIGEST_HTTP_200_OK_GET(self, httpbin):385386 auth = HTTPDigestAuth('user', 'pass')387 url = httpbin('digest-auth', 'auth', 'user', 'pass')388389 r = requests.get(url, auth=auth)
6 unmodified lines
396 s.auth = HTTPDigestAuth('user', 'pass')397 r = s.get(url)398 assert r.status_code == 200399383 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'405406 r = requests.get(url, auth=auth)407 assert r.status_code == 200408392 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'415399 def test_DIGEST_STREAM(self):416 def test_DIGEST_STREAM(self, httpbin):417418 auth = HTTPDigestAuth('user', 'pass')419 url = httpbin('digest-auth', 'auth', 'user', 'pass')420
2 unmodified lines
423424 r = requests.get(url, auth=auth, stream=False)425 assert r.raw.read() == b''426410 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self):427 def test_DIGESTAUTH_WRONG_HTTP_401_GET(self, httpbin):428429 auth = HTTPDigestAuth('user', 'wrongpass')430 url = httpbin('digest-auth', 'auth', 'user', 'pass')431
7 unmodified lines
439 s.auth = auth440 r = s.get(url)441 assert r.status_code == 401442426 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self):443 def test_DIGESTAUTH_QUOTES_QOP_VALUE(self, httpbin):444445 auth = HTTPDigestAuth('user', 'pass')446 url = httpbin('digest-auth', 'auth', 'user', 'pass')447448 r = requests.get(url, auth=auth)449 assert '"auth"' in r.request.headers['Authorization']450434 def test_DIGESTAUTH_THREADED(self):451 def test_POSTBIN_GET_POST_FILES(self, httpbin):452436 auth = HTTPDigestAuth('user', 'pass')437 url = httpbin('digest-auth', 'auth', 'user', 'pass')438 session = requests.Session()439 session.auth=auth440441 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))448449 def test_POSTBIN_GET_POST_FILES(self):450453 url = httpbin('post')454 post1 = requests.post(url).raise_for_status()455456 post1 = requests.post(url, data={'some': 'data'})
8 unmodified lines
465466 with pytest.raises(ValueError):467 requests.post(url, files=['bad file data'])468467 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self):469 def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):470471 url = httpbin('post')472 post1 = requests.post(url).raise_for_status()473
10 unmodified lines
484485 with pytest.raises(ValueError):486 requests.post(url, files=['bad file data'])487486 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})")493492 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.ok497496 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()502503 r = requests.get(httpbin('status', '500'))504 assert not r.ok505504 def test_decompress_gzip(self):506 def test_decompress_gzip(self, httpbin):507 r = requests.get(httpbin('gzip'))508 r.content.decode('ascii')509508 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'})517516 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.523522 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)526525 def test_urlencoded_get_query_multivalued_param(self):527 def test_urlencoded_get_query_multivalued_param(self, httpbin):528529 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')532531 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 == 200539538 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 == 200
12 unmodified lines
557 data={'stuff': 'elixr'.encode('utf-8')},558 files={'file': ('test_requests.py', open(__file__, 'rb'))})559 assert r.status_code == 200560559 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 lines
568 prep = r.prepare()569 assert b'name="stuff"' in prep.body570 assert b'name="b\'stuff\'"' not in prep.body571570 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 == 200577576 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 lines
585586 resp = s.send(prep)587 assert resp.status_code == 200588587 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 line
595 'text/py-content-type')})596 assert r.status_code == 200597 assert b"text/py-content-type" in r.request.body598597 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 != {}603602 requests.Request('GET', HTTPBIN, hooks={'response': hook})604 requests.Request('GET', httpbin(), hooks={'response': hook})605604 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]614613 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]624623 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 resp629628 req = requests.Request('GET', HTTPBIN, hooks={'response': hook})630 req = requests.Request('GET', httpbin(), hooks={'response': hook})631 prep = req.prepare()632633 s = requests.Session()634 s.proxies = getproxies()635 resp = s.send(prep)636637 assert hasattr(resp, 'hook_working')638637 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 r
144 unmodified lines
788 assert items == list(items)789 # make sure one can use items multiple times790 assert list(items) == list(items)791790 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 lines
827 r.encoding = 'ascii'828 chunks = r.iter_content(decode_unicode=True)829 assert all(isinstance(chunk, str) for chunk in chunks)830829 def test_request_and_response_are_pickleable(self):831 def test_request_and_response_are_pickleable(self, httpbin):832 r = requests.get(httpbin('get'))833834 # verify we can pickle the original request835 assert pickle.loads(pickle.dumps(r.request))
23 unmodified lines
859 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)862861 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)867868 def test_http_error(self):
5 unmodified lines
874 error = requests.exceptions.HTTPError('message', response=response)875 assert str(error) == 'message'876 assert error.response == response877876 def test_session_pickling(self):878 def test_session_pickling(self, httpbin):879 r = requests.Request('GET', httpbin('get'))880 s = requests.Session()881882 s = pickle.loads(pickle.dumps(s))
1 unmodified line
884885 r = s.send(r.prepare())886 assert r.status_code == 200887886 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 lines
897 assert headers['accept'] == 'application/json'898 assert headers['Accept'] == 'application/json'899 assert headers['ACCEPT'] == 'application/json'900899 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 == 200
36 unmodified lines
942 s2.mount('https://', HTTPAdapter())943 assert 'http://' in s2.adapters944 assert 'https://' in s2.adapters945944 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.headers952951 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 lines
964 )965 r = requests.Request('GET', url).prepare()966 assert r.url == url967966 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 line
974 # we go.975 assert 'unicode' in p.headers.keys()976 assert 'byte' in p.headers.keys()977976 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()983984 assert 'multipart/form-data' in p.headers['Content-Type']985984 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 lines
995 r = requests.Request('POST', httpbin('post'), data=data, files=files)996 p = r.prepare()997 assert 'multipart/form-data' in p.headers['Content-Type']998997 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()10041005 assert 'multipart/form-data' in p.headers['Content-Type']10061005 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 lines
1022 req = requests.Request('GET', test_url)1023 preq = req.prepare()1024 assert test_url == preq.url10251024 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', '')10341033 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']10391040 assert h1 == h210411040 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 lines
1071 return resp10721073 adapter.build_response = build_response10741073 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 lines
1082 s = _basic_auth_str("test", "test")1083 assert isinstance(s, builtin_str)1084 assert s == "Basic dGVzdDp0ZXN0"10851084 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 + 110931092 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']11021101 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.body11091108 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 == 20011131114 it = r.iter_lines()1115 next(it)1116 assert len(list(it)) == 311171116 def test_unconsumed_session_response_closes_connection(self):1118 def test_unconsumed_session_response_closes_connection(self, httpbin):1119 s = requests.session()11201121 with contextlib.closing(s.get(httpbin('stream/4'), stream=True)) as response:1122 pass11231122 self.assertFalse(response._content_consumed)1123 self.assertTrue(response.raw.closed)1124 assert response._content_consumed is False1125 assert response.raw.closed11261127 @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 lines
1518 morsel_to_cookie(morsel)151915201521class 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]15271526 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)15321533 with pytest.raises(ValueError) as e:1534 requests.get(httpbin('get'), timeout="foo")1535 assert 'must be an int or float' in str(e)15361535 def test_none_timeout(self):1537 def test_none_timeout(self, httpbin):1538 """ Check that you can set None as a valid timeout value.15391540 To actually test this behavior, we'd want to check that setting the1541 timeout to None actually lets the request block past the system default
3 unmodified lines
1545 """1546 r = requests.get(httpbin('get'), timeout=None)1547 assert r.status_code == 20015481547 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 lines
1567 assert False, "The connect() request should time out."1568 except ConnectTimeout:1569 pass15701569 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 lines
1618 'allow_redirects': False,1619 'proxies': {},1620 }16211620 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 lines
1700 )1701 assert_copy(p, p.copy())170217031702def test_urllib3_retries():1704def 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 lines
1711 with pytest.raises(RetryError):1712 s.get(httpbin('status/500'))171317141713def test_urllib3_pool_connection_closed():1715def test_urllib3_pool_connection_closed(httpbin):1716 s = requests.Session()1717 s.mount('http://', HTTPAdapter(pool_connections=0, pool_maxsize=0))17181719 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)17231724def test_vendor_aliases():1725 from requests.packages import urllib31726 from requests.packages import chardet
6 unmodified lines