6
from requests.compat import JSONDecodeError
7
from tests.testserver.server import Server, consume_socket_content
9
from .utils import override_environ
12
def echo_response_handler(sock):
13
"""Simple handler that will take request and echo it back to requester."""
14
request_content = consume_socket_content(sock, timeout=0.5)
17
b"HTTP/1.1 200 OK\r\n"
18
b"Content-Length: %d\r\n\r\n"
20
) % (len(request_content), request_content)
24
def test_chunked_upload():
25
"""can safely send generators"""
26
close_server = threading.Event()
27
server = Server.basic_response_server(wait_to_close_event=close_server)
28
data = iter([b"a", b"b", b"c"])
30
with server as (host, port):
31
url = f"http://{host}:{port}/"
32
r = requests.post(url, data=data, stream=True)
33
close_server.set() # release server block
35
assert r.status_code == 200
36
assert r.request.headers["Transfer-Encoding"] == "chunked"
39
def test_chunked_encoding_error():
40
"""get a ChunkedEncodingError if the server returns a bad response"""
42
def incomplete_chunked_response_handler(sock):
43
request_content = consume_socket_content(sock, timeout=0.5)
45
# The server never ends the request and doesn't provide any valid chunks
47
b"HTTP/1.1 200 OK\r\n"
48
b"Transfer-Encoding: chunked\r\n"
45
# The server never ends the request and doesn't provide any valid chunks
47
b"HTTP/1.1 200 OK\r\n"
48
b"Transfer-Encoding: chunked\r\n"
51
return request_content
53
close_server = threading.Event()
54
server = Server(incomplete_chunked_response_handler)
56
with server as (host, port):
57
url = f"http://{host}:{port}/"
58
with pytest.raises(requests.exceptions.ChunkedEncodingError):
60
close_server.set() # release server block
63
def test_chunked_upload_uses_only_specified_host_header():
64
"""Ensure we use only the specified Host header for chunked requests."""
65
close_server = threading.Event()
66
server = Server(echo_response_handler, wait_to_close_event=close_server)
68
data = iter([b"a", b"b", b"c"])
69
custom_host = "sample-host"
71
with server as (host, port):
72
url = f"http://{host}:{port}/"
73
r = requests.post(url, data=data, headers={"Host": custom_host}, stream=True)
74
close_server.set() # release server block
76
expected_header = b"Host: %s\r\n" % custom_host.encode("utf-8")
77
assert expected_header in r.content
78
assert r.content.count(b"Host: ") == 1
81
def test_chunked_upload_doesnt_skip_host_header():
82
"""Ensure we don't omit all Host headers with chunked requests."""
83
close_server = threading.Event()
84
server = Server(echo_response_handler, wait_to_close_event=close_server)
81
def test_chunked_upload_doesnt_skip_host_header():
82
"""Ensure we don't omit all Host headers with chunked requests."""
83
close_server = threading.Event()
84
server = Server(echo_response_handler, wait_to_close_event=close_server)
86
data = iter([b"a", b"b", b"c"])
88
with server as (host, port):
89
expected_host = f"{host}:{port}"
90
url = f"http://{host}:{port}/"
91
r = requests.post(url, data=data, stream=True)
92
close_server.set() # release server block
94
expected_header = b"Host: %s\r\n" % expected_host.encode("utf-8")
95
assert expected_header in r.content
96
assert r.content.count(b"Host: ") == 1
99
def test_conflicting_content_lengths():
100
"""Ensure we correctly throw an InvalidHeader error if multiple
101
conflicting Content-Length headers are returned.
104
def multiple_content_length_response_handler(sock):
105
request_content = consume_socket_content(sock, timeout=0.5)
107
b"HTTP/1.1 200 OK\r\n"
108
b"Content-Type: text/plain\r\n"
109
b"Content-Length: 16\r\n"
110
b"Content-Length: 32\r\n\r\n"
111
b"-- Bad Actor -- Original Content\r\n"
115
return request_content
117
close_server = threading.Event()
118
server = Server(multiple_content_length_response_handler)
120
with server as (host, port):
121
url = f"http://{host}:{port}/"
122
with pytest.raises(requests.exceptions.InvalidHeader):
120
with server as (host, port):
121
url = f"http://{host}:{port}/"
122
with pytest.raises(requests.exceptions.InvalidHeader):
127
def test_digestauth_401_count_reset_on_redirect():
128
"""Ensure we correctly reset num_401_calls after a successful digest auth,
129
followed by a 302 redirect to another digest auth prompt.
131
See https://github.com/psf/requests/issues/1979.
133
text_401 = (b'HTTP/1.1 401 UNAUTHORIZED\r\n'
134
b'Content-Length: 0\r\n'
135
b'WWW-Authenticate: Digest nonce="6bf5d6e4da1ce66918800195d6b9130d"'
136
b', opaque="372825293d1c26955496c80ed6426e9e", '
137
b'realm="me@kennethreitz.com", qop=auth\r\n\r\n')
139
text_302 = (b'HTTP/1.1 302 FOUND\r\n'
140
b'Content-Length: 0\r\n'
141
b'Location: /\r\n\r\n')
143
text_200 = (b'HTTP/1.1 200 OK\r\n'
144
b'Content-Length: 0\r\n\r\n')
146
expected_digest = (b'Authorization: Digest username="user", '
147
b'realm="me@kennethreitz.com", '
148
b'nonce="6bf5d6e4da1ce66918800195d6b9130d", uri="/"')
150
auth = requests.auth.HTTPDigestAuth('user', 'pass')
152
def digest_response_handler(sock):
153
# Respond to initial GET with a challenge.
154
request_content = consume_socket_content(sock, timeout=0.5)
155
assert request_content.startswith(b"GET / HTTP/1.1")
152
def digest_response_handler(sock):
153
# Respond to initial GET with a challenge.
154
request_content = consume_socket_content(sock, timeout=0.5)
155
assert request_content.startswith(b"GET / HTTP/1.1")
158
# Verify we receive an Authorization header in response, then redirect.
159
request_content = consume_socket_content(sock, timeout=0.5)
160
assert expected_digest in request_content
163
# Verify Authorization isn't sent to the redirected host,
164
# then send another challenge.
165
request_content = consume_socket_content(sock, timeout=0.5)
166
assert b'Authorization:' not in request_content
169
# Verify Authorization is sent correctly again, and return 200 OK.
170
request_content = consume_socket_content(sock, timeout=0.5)
171
assert expected_digest in request_content
174
return request_content
176
close_server = threading.Event()
177
server = Server(digest_response_handler, wait_to_close_event=close_server)
179
with server as (host, port):
180
url = f'http://{host}:{port}/'
181
r = requests.get(url, auth=auth)
182
# Verify server succeeded in authenticating.
183
assert r.status_code == 200
184
# Verify Authorization was sent in final request.
185
assert 'Authorization' in r.request.headers
186
assert r.request.headers['Authorization'].startswith('Digest ')
187
# Verify redirect happened as we expected.
188
assert r.history[0].status_code == 302
185
assert 'Authorization' in r.request.headers
186
assert r.request.headers['Authorization'].startswith('Digest ')
187
# Verify redirect happened as we expected.
188
assert r.history[0].status_code == 302
192
def test_digestauth_401_only_sent_once():
193
"""Ensure we correctly respond to a 401 challenge once, and then
194
stop responding if challenged again.
196
text_401 = (b'HTTP/1.1 401 UNAUTHORIZED\r\n'
197
b'Content-Length: 0\r\n'
198
b'WWW-Authenticate: Digest nonce="6bf5d6e4da1ce66918800195d6b9130d"'
199
b', opaque="372825293d1c26955496c80ed6426e9e", '
200
b'realm="me@kennethreitz.com", qop=auth\r\n\r\n')
202
expected_digest = (b'Authorization: Digest username="user", '
203
b'realm="me@kennethreitz.com", '
204
b'nonce="6bf5d6e4da1ce66918800195d6b9130d", uri="/"')
206
auth = requests.auth.HTTPDigestAuth('user', 'pass')
208
def digest_failed_response_handler(sock):
209
# Respond to initial GET with a challenge.
210
request_content = consume_socket_content(sock, timeout=0.5)
211
assert request_content.startswith(b"GET / HTTP/1.1")
214
# Verify we receive an Authorization header in response, then
216
request_content = consume_socket_content(sock, timeout=0.5)
217
assert expected_digest in request_content
214
# Verify we receive an Authorization header in response, then
216
request_content = consume_socket_content(sock, timeout=0.5)
217
assert expected_digest in request_content
220
# Verify the client didn't respond to second challenge.
221
request_content = consume_socket_content(sock, timeout=0.5)
222
assert request_content == b''
224
return request_content
226
close_server = threading.Event()
227
server = Server(digest_failed_response_handler, wait_to_close_event=close_server)
229
with server as (host, port):
230
url = f'http://{host}:{port}/'
231
r = requests.get(url, auth=auth)
232
# Verify server didn't authenticate us.
233
assert r.status_code == 401
234
assert r.history[0].status_code == 401
238
def test_digestauth_only_on_4xx():
239
"""Ensure we only send digestauth on 4xx challenges.
241
See https://github.com/psf/requests/issues/3772.
243
text_200_chal = (b'HTTP/1.1 200 OK\r\n'
244
b'Content-Length: 0\r\n'
245
b'WWW-Authenticate: Digest nonce="6bf5d6e4da1ce66918800195d6b9130d"'
246
b', opaque="372825293d1c26955496c80ed6426e9e", '
247
b'realm="me@kennethreitz.com", qop=auth\r\n\r\n')
249
auth = requests.auth.HTTPDigestAuth('user', 'pass')
251
def digest_response_handler(sock):
252
# Respond to GET with a 200 containing www-authenticate header.
253
request_content = consume_socket_content(sock, timeout=0.5)
254
assert request_content.startswith(b"GET / HTTP/1.1")
255
sock.send(text_200_chal)
251
def digest_response_handler(sock):
252
# Respond to GET with a 200 containing www-authenticate header.
253
request_content = consume_socket_content(sock, timeout=0.5)
254
assert request_content.startswith(b"GET / HTTP/1.1")
255
sock.send(text_200_chal)
257
# Verify the client didn't respond with auth.
258
request_content = consume_socket_content(sock, timeout=0.5)
259
assert request_content == b''
261
return request_content
263
close_server = threading.Event()
264
server = Server(digest_response_handler, wait_to_close_event=close_server)
266
with server as (host, port):
267
url = f'http://{host}:{port}/'
268
r = requests.get(url, auth=auth)
269
# Verify server didn't receive auth from us.
270
assert r.status_code == 200
271
assert len(r.history) == 0
275
_schemes_by_var_prefix = [
277
('https', ['https']),
278
('all', ['http', 'https']),
282
for prefix, schemes in _schemes_by_var_prefix:
283
for scheme in schemes:
284
_proxy_combos.append((f"{prefix}_proxy", scheme))
286
_proxy_combos += [(var.upper(), scheme) for var, scheme in _proxy_combos]
289
@pytest.mark.parametrize("var,scheme", _proxy_combos)
290
def test_use_proxy_from_environment(httpbin, var, scheme):
291
url = f"{scheme}://httpbin.org"
292
fake_proxy = Server() # do nothing with the requests; just close the socket
293
with fake_proxy as (host, port):
294
proxy_url = f"socks5://{host}:{port}"
295
kwargs = {var: proxy_url}
296
with override_environ(**kwargs):
297
# fake proxy's lack of response will cause a ConnectionError
298
with pytest.raises(requests.exceptions.ConnectionError):
295
kwargs = {var: proxy_url}
296
with override_environ(**kwargs):
297
# fake proxy's lack of response will cause a ConnectionError
298
with pytest.raises(requests.exceptions.ConnectionError):
301
# the fake proxy received a request
302
assert len(fake_proxy.handler_results) == 1
304
# it had actual content (not checking for SOCKS protocol for now)
305
assert len(fake_proxy.handler_results[0]) > 0
308
def test_redirect_rfc1808_to_non_ascii_location():
310
expected_path = b'%C5%A1'
311
redirect_request = [] # stores the second request to the server
313
def redirect_resp_handler(sock):
314
consume_socket_content(sock, timeout=0.5)
315
location = f'//{host}:{port}/{path}'
318
b'HTTP/1.1 301 Moved Permanently\r\n'
319
b'Content-Length: 0\r\n'
322
) % location.encode('utf8')
324
redirect_request.append(consume_socket_content(sock, timeout=0.5))
325
sock.send(b'HTTP/1.1 200 OK\r\n\r\n')
327
close_server = threading.Event()
328
server = Server(redirect_resp_handler, wait_to_close_event=close_server)
330
with server as (host, port):
331
url = f'http://{host}:{port}'
332
r = requests.get(url=url, allow_redirects=True)
333
assert r.status_code == 200
334
assert len(r.history) == 1
335
assert r.history[0].status_code == 301
336
assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')
337
assert r.url == '{}/{}'.format(url, expected_path.decode('ascii'))
333
assert r.status_code == 200
334
assert len(r.history) == 1
335
assert r.history[0].status_code == 301
336
assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')
337
assert r.url == '{}/{}'.format(url, expected_path.decode('ascii'))
342
def test_fragment_not_sent_with_request():
343
"""Verify that the fragment portion of a URI isn't sent to the server."""
344
close_server = threading.Event()
345
server = Server(echo_response_handler, wait_to_close_event=close_server)
347
with server as (host, port):
348
url = f'http://{host}:{port}/path/to/thing/#view=edit&token=hunter2'
349
r = requests.get(url)
350
raw_request = r.content
352
assert r.status_code == 200
353
headers, body = raw_request.split(b'\r\n\r\n', 1)
354
status_line, headers = headers.split(b'\r\n', 1)
356
assert status_line == b'GET /path/to/thing/ HTTP/1.1'
357
for frag in (b'view', b'edit', b'token', b'hunter2'):
358
assert frag not in headers
359
assert frag not in body
364
def test_fragment_update_on_redirect():
365
"""Verify we only append previous fragment if one doesn't exist on new
366
location. If a new fragment is encountered in a Location header, it should
367
be added to all subsequent requests.
370
def response_handler(sock):
371
consume_socket_content(sock, timeout=0.5)
373
b'HTTP/1.1 302 FOUND\r\n'
374
b'Content-Length: 0\r\n'
375
b'Location: /get#relevant-section\r\n\r\n'
377
consume_socket_content(sock, timeout=0.5)
379
b'HTTP/1.1 302 FOUND\r\n'
380
b'Content-Length: 0\r\n'
381
b'Location: /final-url/\r\n\r\n'
383
consume_socket_content(sock, timeout=0.5)
385
b'HTTP/1.1 200 OK\r\n\r\n'
383
consume_socket_content(sock, timeout=0.5)
385
b'HTTP/1.1 200 OK\r\n\r\n'
388
close_server = threading.Event()
389
server = Server(response_handler, wait_to_close_event=close_server)
391
with server as (host, port):
392
url = f'http://{host}:{port}/path/to/thing/#view=edit&token=hunter2'
393
r = requests.get(url)
395
assert r.status_code == 200
396
assert len(r.history) == 2
397
assert r.history[0].request.url == url
399
# Verify we haven't overwritten the location with our previous fragment.
400
assert r.history[1].request.url == f'http://{host}:{port}/get#relevant-section'
401
# Verify previous fragment is used and not the original.
402
assert r.url == f'http://{host}:{port}/final-url/#relevant-section'
407
def test_json_decode_compatibility_for_alt_utf_encodings():
409
def response_handler(sock):
410
consume_socket_content(sock, timeout=0.5)
412
b'HTTP/1.1 200 OK\r\n'
413
b'Content-Length: 18\r\n\r\n'
414
b'\xff\xfe{\x00"\x00K0"\x00=\x00"\x00\xab0"\x00\r\n'
417
close_server = threading.Event()
418
server = Server(response_handler, wait_to_close_event=close_server)
420
with server as (host, port):
421
url = f'http://{host}:{port}/'
422
r = requests.get(url)
424
with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:
420
with server as (host, port):
421
url = f'http://{host}:{port}/'
422
r = requests.get(url)
424
with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:
426
assert isinstance(excinfo.value, requests.exceptions.RequestException)
427
assert isinstance(excinfo.value, JSONDecodeError)
428
assert r.text not in str(excinfo.value)