Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit b575432

Browse files
committed
Issue #23440: Improve http.server.SimpleHTTPRequestHandler tests
* Tests that index.html is served, rather than an automatic directory listing * Tests that there is no extra data sent after the response Patch by Martin Panter.
1 parent b7666a3 commit b575432

1 file changed

Lines changed: 29 additions & 7 deletions

File tree

Lib/test/test_httpservers.py

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -298,12 +298,28 @@ def tearDown(self):
298298
BaseTestCase.tearDown(self)
299299

300300
def check_status_and_reason(self, response, status, data=None):
301+
def close_conn():
302+
"""Don't close reader yet so we can check if there was leftover
303+
buffered input"""
304+
nonlocal reader
305+
reader = response.fp
306+
response.fp = None
307+
reader = None
308+
response._close_conn = close_conn
309+
301310
body = response.read()
302311
self.assertTrue(response)
303312
self.assertEqual(response.status, status)
304313
self.assertIsNotNone(response.reason)
305314
if data:
306315
self.assertEqual(data, body)
316+
# Ensure the server has not set up a persistent connection, and has
317+
# not sent any extra data
318+
self.assertEqual(response.version, 10)
319+
self.assertEqual(response.msg.get("Connection", "close"), "close")
320+
self.assertEqual(reader.read(30), b'', 'Connection should be closed')
321+
322+
reader.close()
307323
return body
308324

309325
@support.requires_mac_ver(10, 5)
@@ -353,15 +369,21 @@ def test_get(self):
353369
self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
354370
response = self.request('/' + 'ThisDoesNotExist' + '/')
355371
self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
356-
with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as f:
357-
response = self.request('/' + self.tempdir_name + '/')
358-
self.check_status_and_reason(response, HTTPStatus.OK)
359-
# chmod() doesn't work as expected on Windows, and filesystem
360-
# permissions are ignored by root on Unix.
361-
if os.name == 'posix' and os.geteuid() != 0:
362-
os.chmod(self.tempdir, 0)
372+
373+
data = b"Dummy index file\r\n"
374+
with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
375+
f.write(data)
376+
response = self.request('/' + self.tempdir_name + '/')
377+
self.check_status_and_reason(response, HTTPStatus.OK, data)
378+
379+
# chmod() doesn't work as expected on Windows, and filesystem
380+
# permissions are ignored by root on Unix.
381+
if os.name == 'posix' and os.geteuid() != 0:
382+
os.chmod(self.tempdir, 0)
383+
try:
363384
response = self.request(self.tempdir_name + '/')
364385
self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
386+
finally:
365387
os.chmod(self.tempdir, 0o755)
366388

367389
def test_head(self):

0 commit comments

Comments
 (0)