blob: 71a0511e53a72fe7a3d2c7647d6c7bd25b289531 [file] [log] [blame]
Georg Brandlb533e262008-05-25 18:19:30 +00001"""Unittests for the various HTTPServer modules.
2
3Written by Cody A.W. Somerville <cody-somerville@ubuntu.com>,
4Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest.
5"""
6
Georg Brandl24420152008-05-26 16:32:26 +00007from http.server import BaseHTTPRequestHandler, HTTPServer, \
8 SimpleHTTPRequestHandler, CGIHTTPRequestHandler
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02009from http import server, HTTPStatus
Georg Brandlb533e262008-05-25 18:19:30 +000010
11import os
Lisa Roach433433f2018-11-26 10:43:38 -080012import socket
Georg Brandlb533e262008-05-25 18:19:30 +000013import sys
Senthil Kumaran0f476d42010-09-30 06:09:18 +000014import re
Georg Brandlb533e262008-05-25 18:19:30 +000015import base64
Martin Panterd274b3f2016-04-18 03:45:18 +000016import ntpath
Géry Ogam781266e2019-09-11 15:03:46 +020017import pathlib
Georg Brandlb533e262008-05-25 18:19:30 +000018import shutil
Pierre Quentel351adda2017-04-02 12:26:12 +020019import email.message
20import email.utils
Serhiy Storchakacb5bc402014-08-17 08:22:11 +030021import html
Georg Brandl24420152008-05-26 16:32:26 +000022import http.client
Pierre Quentel351adda2017-04-02 12:26:12 +020023import urllib.parse
Georg Brandlb533e262008-05-25 18:19:30 +000024import tempfile
Berker Peksag04bc5b92016-03-14 06:06:03 +020025import time
Pierre Quentel351adda2017-04-02 12:26:12 +020026import datetime
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020027import threading
Stéphane Wirtela17a2f52017-05-24 09:29:06 +020028from unittest import mock
Senthil Kumaran0f476d42010-09-30 06:09:18 +000029from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000030
31import unittest
32from test import support
Hai Shie80697d2020-05-28 06:10:27 +080033from test.support import threading_helper
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020034
Georg Brandlb533e262008-05-25 18:19:30 +000035
Georg Brandlb533e262008-05-25 18:19:30 +000036class NoLogRequestHandler:
37 def log_message(self, *args):
38 # don't write log messages to stderr
39 pass
40
Barry Warsaw820c1202008-06-12 04:06:45 +000041 def read(self, n=None):
42 return ''
43
Georg Brandlb533e262008-05-25 18:19:30 +000044
45class TestServerThread(threading.Thread):
46 def __init__(self, test_object, request_handler):
47 threading.Thread.__init__(self)
48 self.request_handler = request_handler
49 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000050
51 def run(self):
Antoine Pitroucb342182011-03-21 00:26:51 +010052 self.server = HTTPServer(('localhost', 0), self.request_handler)
53 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000054 self.test_object.server_started.set()
55 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000056 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000057 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000058 finally:
59 self.server.server_close()
60
61 def stop(self):
62 self.server.shutdown()
Victor Stinner830d7d22017-08-22 18:05:07 +020063 self.join()
Georg Brandlb533e262008-05-25 18:19:30 +000064
65
66class BaseTestCase(unittest.TestCase):
67 def setUp(self):
Hai Shie80697d2020-05-28 06:10:27 +080068 self._threads = threading_helper.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000069 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000070 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000071 self.thread = TestServerThread(self, self.request_handler)
72 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000073 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000074
75 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000076 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020077 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000078 os.environ.__exit__()
Hai Shie80697d2020-05-28 06:10:27 +080079 threading_helper.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000080
81 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010082 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000083 self.connection.request(method, uri, body, headers)
84 return self.connection.getresponse()
85
86
87class BaseHTTPServerTestCase(BaseTestCase):
88 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
89 protocol_version = 'HTTP/1.1'
90 default_request_version = 'HTTP/1.1'
91
92 def do_TEST(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020093 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000094 self.send_header('Content-Type', 'text/html')
95 self.send_header('Connection', 'close')
96 self.end_headers()
97
98 def do_KEEP(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020099 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000100 self.send_header('Content-Type', 'text/html')
101 self.send_header('Connection', 'keep-alive')
102 self.end_headers()
103
104 def do_KEYERROR(self):
105 self.send_error(999)
106
Senthil Kumaran52d27202012-10-10 23:16:21 -0700107 def do_NOTFOUND(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200108 self.send_error(HTTPStatus.NOT_FOUND)
Senthil Kumaran52d27202012-10-10 23:16:21 -0700109
Senthil Kumaran26886442013-03-15 07:53:21 -0700110 def do_EXPLAINERROR(self):
111 self.send_error(999, "Short Message",
Martin Panter46f50722016-05-26 05:35:26 +0000112 "This is a long \n explanation")
Senthil Kumaran26886442013-03-15 07:53:21 -0700113
Georg Brandlb533e262008-05-25 18:19:30 +0000114 def do_CUSTOM(self):
115 self.send_response(999)
116 self.send_header('Content-Type', 'text/html')
117 self.send_header('Connection', 'close')
118 self.end_headers()
119
Armin Ronacher8d96d772011-01-22 13:13:05 +0000120 def do_LATINONEHEADER(self):
121 self.send_response(999)
122 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000123 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000124 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000125 body = self.headers['x-special-incoming'].encode('utf-8')
126 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000127
Martin Pantere42e1292016-06-08 08:29:13 +0000128 def do_SEND_ERROR(self):
129 self.send_error(int(self.path[1:]))
130
131 def do_HEAD(self):
132 self.send_error(int(self.path[1:]))
133
Georg Brandlb533e262008-05-25 18:19:30 +0000134 def setUp(self):
135 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100136 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000137 self.con.connect()
138
139 def test_command(self):
140 self.con.request('GET', '/')
141 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200142 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000143
144 def test_request_line_trimming(self):
145 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400146 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000147 self.con.endheaders()
148 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200149 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000150
151 def test_version_bogus(self):
152 self.con._http_vsn_str = 'FUBAR'
153 self.con.putrequest('GET', '/')
154 self.con.endheaders()
155 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200156 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000157
158 def test_version_digits(self):
159 self.con._http_vsn_str = 'HTTP/9.9.9'
160 self.con.putrequest('GET', '/')
161 self.con.endheaders()
162 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200163 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000164
165 def test_version_none_get(self):
166 self.con._http_vsn_str = ''
167 self.con.putrequest('GET', '/')
168 self.con.endheaders()
169 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200170 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000171
172 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400173 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000174 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400175 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000176 self.con.endheaders()
177 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200178 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000179
180 def test_version_invalid(self):
181 self.con._http_vsn = 99
182 self.con._http_vsn_str = 'HTTP/9.9'
183 self.con.putrequest('GET', '/')
184 self.con.endheaders()
185 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200186 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000187
188 def test_send_blank(self):
189 self.con._http_vsn_str = ''
190 self.con.putrequest('', '')
191 self.con.endheaders()
192 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200193 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000194
195 def test_header_close(self):
196 self.con.putrequest('GET', '/')
197 self.con.putheader('Connection', 'close')
198 self.con.endheaders()
199 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200200 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000201
Berker Peksag20853612016-08-25 01:13:34 +0300202 def test_header_keep_alive(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000203 self.con._http_vsn_str = 'HTTP/1.1'
204 self.con.putrequest('GET', '/')
205 self.con.putheader('Connection', 'keep-alive')
206 self.con.endheaders()
207 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200208 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000209
210 def test_handler(self):
211 self.con.request('TEST', '/')
212 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200213 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000214
215 def test_return_header_keep_alive(self):
216 self.con.request('KEEP', '/')
217 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000218 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000219 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000220 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000221
222 def test_internal_key_error(self):
223 self.con.request('KEYERROR', '/')
224 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000225 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000226
227 def test_return_custom_status(self):
228 self.con.request('CUSTOM', '/')
229 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000230 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000231
Senthil Kumaran26886442013-03-15 07:53:21 -0700232 def test_return_explain_error(self):
233 self.con.request('EXPLAINERROR', '/')
234 res = self.con.getresponse()
235 self.assertEqual(res.status, 999)
236 self.assertTrue(int(res.getheader('Content-Length')))
237
Armin Ronacher8d96d772011-01-22 13:13:05 +0000238 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000239 self.con.request('LATINONEHEADER', '/', headers={
240 'X-Special-Incoming': 'Ärger mit Unicode'
241 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000242 res = self.con.getresponse()
243 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000244 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000245
Senthil Kumaran52d27202012-10-10 23:16:21 -0700246 def test_error_content_length(self):
247 # Issue #16088: standard error responses should have a content-length
248 self.con.request('NOTFOUND', '/')
249 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200250 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
251
Senthil Kumaran52d27202012-10-10 23:16:21 -0700252 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700253 self.assertEqual(int(res.getheader('Content-Length')), len(data))
254
Martin Pantere42e1292016-06-08 08:29:13 +0000255 def test_send_error(self):
256 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
257 HTTPStatus.RESET_CONTENT)
258 for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
259 HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
260 HTTPStatus.SWITCHING_PROTOCOLS):
261 self.con.request('SEND_ERROR', '/{}'.format(code))
262 res = self.con.getresponse()
263 self.assertEqual(code, res.status)
264 self.assertEqual(None, res.getheader('Content-Length'))
265 self.assertEqual(None, res.getheader('Content-Type'))
266 if code not in allow_transfer_encoding_codes:
267 self.assertEqual(None, res.getheader('Transfer-Encoding'))
268
269 data = res.read()
270 self.assertEqual(b'', data)
271
272 def test_head_via_send_error(self):
273 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
274 HTTPStatus.RESET_CONTENT)
275 for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
276 HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
277 HTTPStatus.SWITCHING_PROTOCOLS):
278 self.con.request('HEAD', '/{}'.format(code))
279 res = self.con.getresponse()
280 self.assertEqual(code, res.status)
281 if code == HTTPStatus.OK:
282 self.assertTrue(int(res.getheader('Content-Length')) > 0)
283 self.assertIn('text/html', res.getheader('Content-Type'))
284 else:
285 self.assertEqual(None, res.getheader('Content-Length'))
286 self.assertEqual(None, res.getheader('Content-Type'))
287 if code not in allow_transfer_encoding_codes:
288 self.assertEqual(None, res.getheader('Transfer-Encoding'))
289
290 data = res.read()
291 self.assertEqual(b'', data)
292
Georg Brandlb533e262008-05-25 18:19:30 +0000293
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200294class RequestHandlerLoggingTestCase(BaseTestCase):
295 class request_handler(BaseHTTPRequestHandler):
296 protocol_version = 'HTTP/1.1'
297 default_request_version = 'HTTP/1.1'
298
299 def do_GET(self):
300 self.send_response(HTTPStatus.OK)
301 self.end_headers()
302
303 def do_ERROR(self):
304 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
305
306 def test_get(self):
307 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
308 self.con.connect()
309
310 with support.captured_stderr() as err:
311 self.con.request('GET', '/')
312 self.con.getresponse()
313
314 self.assertTrue(
315 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
316
317 def test_err(self):
318 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
319 self.con.connect()
320
321 with support.captured_stderr() as err:
322 self.con.request('ERROR', '/')
323 self.con.getresponse()
324
325 lines = err.getvalue().split('\n')
326 self.assertTrue(lines[0].endswith('code 404, message File not found'))
327 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
328
329
Georg Brandlb533e262008-05-25 18:19:30 +0000330class SimpleHTTPServerTestCase(BaseTestCase):
331 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
332 pass
333
334 def setUp(self):
335 BaseTestCase.setUp(self)
336 self.cwd = os.getcwd()
337 basetempdir = tempfile.gettempdir()
338 os.chdir(basetempdir)
339 self.data = b'We are the knights who say Ni!'
340 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
341 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panterfc475a92016-04-09 04:56:10 +0000342 self.base_url = '/' + self.tempdir_name
Victor Stinner28ce07a2017-07-28 18:15:02 +0200343 tempname = os.path.join(self.tempdir, 'test')
344 with open(tempname, 'wb') as temp:
Brett Cannon105df5d2010-10-29 23:43:42 +0000345 temp.write(self.data)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200346 temp.flush()
347 mtime = os.stat(tempname).st_mtime
Pierre Quentel351adda2017-04-02 12:26:12 +0200348 # compute last modification datetime for browser cache tests
349 last_modif = datetime.datetime.fromtimestamp(mtime,
350 datetime.timezone.utc)
351 self.last_modif_datetime = last_modif.replace(microsecond=0)
352 self.last_modif_header = email.utils.formatdate(
353 last_modif.timestamp(), usegmt=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000354
355 def tearDown(self):
356 try:
357 os.chdir(self.cwd)
358 try:
359 shutil.rmtree(self.tempdir)
360 except:
361 pass
362 finally:
363 BaseTestCase.tearDown(self)
364
365 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300366 def close_conn():
367 """Don't close reader yet so we can check if there was leftover
368 buffered input"""
369 nonlocal reader
370 reader = response.fp
371 response.fp = None
372 reader = None
373 response._close_conn = close_conn
374
Georg Brandlb533e262008-05-25 18:19:30 +0000375 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000376 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000377 self.assertEqual(response.status, status)
378 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000379 if data:
380 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300381 # Ensure the server has not set up a persistent connection, and has
382 # not sent any extra data
383 self.assertEqual(response.version, 10)
384 self.assertEqual(response.msg.get("Connection", "close"), "close")
385 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
386
387 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300388 return body
389
Ned Deilyb3edde82017-12-04 23:42:02 -0500390 @unittest.skipIf(sys.platform == 'darwin',
391 'undecodable name cannot always be decoded on macOS')
Steve Dowere58571b2016-09-08 11:11:13 -0700392 @unittest.skipIf(sys.platform == 'win32',
393 'undecodable name cannot be decoded on win32')
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300394 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
395 'need support.TESTFN_UNDECODABLE')
396 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300397 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300398 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
399 with open(os.path.join(self.tempdir, filename), 'wb') as f:
400 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000401 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300402 if sys.platform == 'darwin':
403 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
404 # UTF-8 into a percent-encoded value.
405 for name in os.listdir(self.tempdir):
406 if name != 'test': # Ignore a filename created in setUp().
407 filename = name
408 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200409 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300410 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
411 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300412 .encode(enc, 'surrogateescape'), body)
Martin Panterda3bb382016-04-11 00:40:08 +0000413 self.assertIn(('>%s<' % html.escape(filename, quote=False))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300414 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000415 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200416 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300417 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000418
419 def test_get(self):
420 #constructs the path relative to the root directory of the HTTPServer
Martin Panterfc475a92016-04-09 04:56:10 +0000421 response = self.request(self.base_url + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200422 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700423 # check for trailing "/" which should return 404. See Issue17324
Martin Panterfc475a92016-04-09 04:56:10 +0000424 response = self.request(self.base_url + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200425 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Martin Panterfc475a92016-04-09 04:56:10 +0000426 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200427 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000428 response = self.request(self.base_url)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200429 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000430 response = self.request(self.base_url + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200431 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000432 response = self.request(self.base_url + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200433 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600434 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000435 self.base_url + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000436 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200437 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000438 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200439 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300440
441 data = b"Dummy index file\r\n"
442 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
443 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000444 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300445 self.check_status_and_reason(response, HTTPStatus.OK, data)
446
447 # chmod() doesn't work as expected on Windows, and filesystem
448 # permissions are ignored by root on Unix.
449 if os.name == 'posix' and os.geteuid() != 0:
450 os.chmod(self.tempdir, 0)
451 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000452 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200453 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300454 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000455 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000456
457 def test_head(self):
458 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000459 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200460 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000461 self.assertEqual(response.getheader('content-length'),
462 str(len(self.data)))
463 self.assertEqual(response.getheader('content-type'),
464 'application/octet-stream')
465
Pierre Quentel351adda2017-04-02 12:26:12 +0200466 def test_browser_cache(self):
467 """Check that when a request to /test is sent with the request header
468 If-Modified-Since set to date of last modification, the server returns
469 status code 304, not 200
470 """
471 headers = email.message.Message()
472 headers['If-Modified-Since'] = self.last_modif_header
473 response = self.request(self.base_url + '/test', headers=headers)
474 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
475
476 # one hour after last modification : must return 304
477 new_dt = self.last_modif_datetime + datetime.timedelta(hours=1)
478 headers = email.message.Message()
479 headers['If-Modified-Since'] = email.utils.format_datetime(new_dt,
480 usegmt=True)
481 response = self.request(self.base_url + '/test', headers=headers)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200482 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
Pierre Quentel351adda2017-04-02 12:26:12 +0200483
484 def test_browser_cache_file_changed(self):
485 # with If-Modified-Since earlier than Last-Modified, must return 200
486 dt = self.last_modif_datetime
487 # build datetime object : 365 days before last modification
488 old_dt = dt - datetime.timedelta(days=365)
489 headers = email.message.Message()
490 headers['If-Modified-Since'] = email.utils.format_datetime(old_dt,
491 usegmt=True)
492 response = self.request(self.base_url + '/test', headers=headers)
493 self.check_status_and_reason(response, HTTPStatus.OK)
494
495 def test_browser_cache_with_If_None_Match_header(self):
496 # if If-None-Match header is present, ignore If-Modified-Since
497
498 headers = email.message.Message()
499 headers['If-Modified-Since'] = self.last_modif_header
500 headers['If-None-Match'] = "*"
501 response = self.request(self.base_url + '/test', headers=headers)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200502 self.check_status_and_reason(response, HTTPStatus.OK)
Pierre Quentel351adda2017-04-02 12:26:12 +0200503
Georg Brandlb533e262008-05-25 18:19:30 +0000504 def test_invalid_requests(self):
505 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200506 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000507 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400508 response = self.request('/', method='custom')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200509 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000510 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200511 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000512
Pierre Quentel351adda2017-04-02 12:26:12 +0200513 def test_last_modified(self):
514 """Checks that the datetime returned in Last-Modified response header
515 is the actual datetime of last modification, rounded to the second
516 """
517 response = self.request(self.base_url + '/test')
518 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
519 last_modif_header = response.headers['Last-modified']
520 self.assertEqual(last_modif_header, self.last_modif_header)
521
Martin Panterfc475a92016-04-09 04:56:10 +0000522 def test_path_without_leading_slash(self):
523 response = self.request(self.tempdir_name + '/test')
524 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
525 response = self.request(self.tempdir_name + '/test/')
526 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
527 response = self.request(self.tempdir_name + '/')
528 self.check_status_and_reason(response, HTTPStatus.OK)
529 response = self.request(self.tempdir_name)
530 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
531 response = self.request(self.tempdir_name + '/?hi=2')
532 self.check_status_and_reason(response, HTTPStatus.OK)
533 response = self.request(self.tempdir_name + '?hi=1')
534 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
535 self.assertEqual(response.getheader("Location"),
536 self.tempdir_name + "/?hi=1")
537
Martin Panterda3bb382016-04-11 00:40:08 +0000538 def test_html_escape_filename(self):
539 filename = '<test&>.txt'
540 fullpath = os.path.join(self.tempdir, filename)
541
542 try:
543 open(fullpath, 'w').close()
544 except OSError:
545 raise unittest.SkipTest('Can not create file %s on current file '
546 'system' % filename)
547
548 try:
549 response = self.request(self.base_url + '/')
550 body = self.check_status_and_reason(response, HTTPStatus.OK)
551 enc = response.headers.get_content_charset()
552 finally:
553 os.unlink(fullpath) # avoid affecting test_undecodable_filename
554
555 self.assertIsNotNone(enc)
556 html_text = '>%s<' % html.escape(filename, quote=False)
557 self.assertIn(html_text.encode(enc), body)
558
Georg Brandlb533e262008-05-25 18:19:30 +0000559
560cgi_file1 = """\
561#!%s
562
563print("Content-type: text/html")
564print()
565print("Hello World")
566"""
567
568cgi_file2 = """\
569#!%s
570import cgi
571
572print("Content-type: text/html")
573print()
574
575form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000576print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
577 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000578"""
579
Martin Pantera02e18a2015-10-03 05:38:07 +0000580cgi_file4 = """\
581#!%s
582import os
583
584print("Content-type: text/html")
585print()
586
587print(os.environ["%s"])
588"""
589
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100590
591@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
592 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000593class CGIHTTPServerTestCase(BaseTestCase):
594 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
595 pass
596
Antoine Pitroue768c392012-08-05 14:52:45 +0200597 linesep = os.linesep.encode('ascii')
598
Georg Brandlb533e262008-05-25 18:19:30 +0000599 def setUp(self):
600 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000601 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000602 self.parent_dir = tempfile.mkdtemp()
603 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700604 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Siwon Kang91daa9d2019-11-22 18:13:05 +0900605 self.sub_dir_1 = os.path.join(self.parent_dir, 'sub')
606 self.sub_dir_2 = os.path.join(self.sub_dir_1, 'dir')
607 self.cgi_dir_in_sub_dir = os.path.join(self.sub_dir_2, 'cgi-bin')
Georg Brandlb533e262008-05-25 18:19:30 +0000608 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700609 os.mkdir(self.cgi_child_dir)
Siwon Kang91daa9d2019-11-22 18:13:05 +0900610 os.mkdir(self.sub_dir_1)
611 os.mkdir(self.sub_dir_2)
612 os.mkdir(self.cgi_dir_in_sub_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400613 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000614 self.file1_path = None
615 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700616 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000617 self.file4_path = None
Siwon Kang91daa9d2019-11-22 18:13:05 +0900618 self.file5_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000619
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000620 # The shebang line should be pure ASCII: use symlink if possible.
621 # See issue #7668.
Steve Dower9048c492019-06-29 10:34:11 -0700622 self._pythonexe_symlink = None
Brian Curtin3b4499c2010-12-28 14:31:47 +0000623 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000624 self.pythonexe = os.path.join(self.parent_dir, 'python')
Steve Dower9048c492019-06-29 10:34:11 -0700625 self._pythonexe_symlink = support.PythonSymlink(self.pythonexe).__enter__()
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000626 else:
627 self.pythonexe = sys.executable
628
Victor Stinner3218c312010-10-17 20:13:36 +0000629 try:
630 # The python executable path is written as the first line of the
631 # CGI Python script. The encoding cookie cannot be used, and so the
632 # path should be encodable to the default script encoding (utf-8)
633 self.pythonexe.encode('utf-8')
634 except UnicodeEncodeError:
635 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200636 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000637
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400638 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
639 with open(self.nocgi_path, 'w') as fp:
640 fp.write(cgi_file1 % self.pythonexe)
641 os.chmod(self.nocgi_path, 0o777)
642
Georg Brandlb533e262008-05-25 18:19:30 +0000643 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000644 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000645 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000646 os.chmod(self.file1_path, 0o777)
647
648 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000649 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000650 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000651 os.chmod(self.file2_path, 0o777)
652
Ned Deily915a30f2014-07-12 22:06:26 -0700653 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
654 with open(self.file3_path, 'w', encoding='utf-8') as file3:
655 file3.write(cgi_file1 % self.pythonexe)
656 os.chmod(self.file3_path, 0o777)
657
Martin Pantera02e18a2015-10-03 05:38:07 +0000658 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
659 with open(self.file4_path, 'w', encoding='utf-8') as file4:
660 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
661 os.chmod(self.file4_path, 0o777)
662
Siwon Kang91daa9d2019-11-22 18:13:05 +0900663 self.file5_path = os.path.join(self.cgi_dir_in_sub_dir, 'file5.py')
664 with open(self.file5_path, 'w', encoding='utf-8') as file5:
665 file5.write(cgi_file1 % self.pythonexe)
666 os.chmod(self.file5_path, 0o777)
667
Georg Brandlb533e262008-05-25 18:19:30 +0000668 os.chdir(self.parent_dir)
669
670 def tearDown(self):
671 try:
672 os.chdir(self.cwd)
Steve Dower9048c492019-06-29 10:34:11 -0700673 if self._pythonexe_symlink:
674 self._pythonexe_symlink.__exit__(None, None, None)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400675 if self.nocgi_path:
676 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000677 if self.file1_path:
678 os.remove(self.file1_path)
679 if self.file2_path:
680 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700681 if self.file3_path:
682 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000683 if self.file4_path:
684 os.remove(self.file4_path)
Siwon Kang91daa9d2019-11-22 18:13:05 +0900685 if self.file5_path:
686 os.remove(self.file5_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700687 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000688 os.rmdir(self.cgi_dir)
Siwon Kang91daa9d2019-11-22 18:13:05 +0900689 os.rmdir(self.cgi_dir_in_sub_dir)
690 os.rmdir(self.sub_dir_2)
691 os.rmdir(self.sub_dir_1)
Georg Brandlb533e262008-05-25 18:19:30 +0000692 os.rmdir(self.parent_dir)
693 finally:
694 BaseTestCase.tearDown(self)
695
Senthil Kumarand70846b2012-04-12 02:34:32 +0800696 def test_url_collapse_path(self):
697 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000698 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800699 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000700 '..': IndexError,
701 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800702 '/': '//',
703 '//': '//',
704 '/\\': '//\\',
705 '/.//': '//',
706 'cgi-bin/file1.py': '/cgi-bin/file1.py',
707 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
708 'a': '//a',
709 '/a': '//a',
710 '//a': '//a',
711 './a': '//a',
712 './C:/': '/C:/',
713 '/a/b': '/a/b',
714 '/a/b/': '/a/b/',
715 '/a/b/.': '/a/b/',
716 '/a/b/c/..': '/a/b/',
717 '/a/b/c/../d': '/a/b/d',
718 '/a/b/c/../d/e/../f': '/a/b/d/f',
719 '/a/b/c/../d/e/../../f': '/a/b/f',
720 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000721 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800722 '/a/b/c/../d/e/../../../f': '/a/f',
723 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000724 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800725 '/a/b/c/../d/e/../../../../f/..': '//',
726 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000727 }
728 for path, expected in test_vectors.items():
729 if isinstance(expected, type) and issubclass(expected, Exception):
730 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800731 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000732 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800733 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000734 self.assertEqual(expected, actual,
735 msg='path = %r\nGot: %r\nWanted: %r' %
736 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000737
Georg Brandlb533e262008-05-25 18:19:30 +0000738 def test_headers_and_content(self):
739 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200740 self.assertEqual(
741 (res.read(), res.getheader('Content-type'), res.status),
742 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000743
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400744 def test_issue19435(self):
745 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200746 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400747
Georg Brandlb533e262008-05-25 18:19:30 +0000748 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000749 params = urllib.parse.urlencode(
750 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000751 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
752 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
753
Antoine Pitroue768c392012-08-05 14:52:45 +0200754 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000755
756 def test_invaliduri(self):
757 res = self.request('/cgi-bin/invalid')
758 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200759 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000760
761 def test_authorization(self):
762 headers = {b'Authorization' : b'Basic ' +
763 base64.b64encode(b'username:pass')}
764 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200765 self.assertEqual(
766 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
767 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000768
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000769 def test_no_leading_slash(self):
770 # http://bugs.python.org/issue2254
771 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200772 self.assertEqual(
773 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
774 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000775
Senthil Kumaran42713722010-10-03 17:55:45 +0000776 def test_os_environ_is_not_altered(self):
777 signature = "Test CGI Server"
778 os.environ['SERVER_SOFTWARE'] = signature
779 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200780 self.assertEqual(
781 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
782 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000783 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
784
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700785 def test_urlquote_decoding_in_cgi_check(self):
786 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200787 self.assertEqual(
788 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
789 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700790
Ned Deily915a30f2014-07-12 22:06:26 -0700791 def test_nested_cgi_path_issue21323(self):
792 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200793 self.assertEqual(
794 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
795 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700796
Martin Pantera02e18a2015-10-03 05:38:07 +0000797 def test_query_with_multiple_question_mark(self):
798 res = self.request('/cgi-bin/file4.py?a=b?c=d')
799 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000800 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000801 (res.read(), res.getheader('Content-type'), res.status))
802
Martin Pantercb29e8c2015-10-03 05:55:46 +0000803 def test_query_with_continuous_slashes(self):
804 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
805 self.assertEqual(
806 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000807 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000808 (res.read(), res.getheader('Content-type'), res.status))
809
Siwon Kang91daa9d2019-11-22 18:13:05 +0900810 def test_cgi_path_in_sub_directories(self):
Pablo Galindo24f5cac2019-12-04 09:29:10 +0000811 try:
812 CGIHTTPRequestHandler.cgi_directories.append('/sub/dir/cgi-bin')
813 res = self.request('/sub/dir/cgi-bin/file5.py')
814 self.assertEqual(
815 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
816 (res.read(), res.getheader('Content-type'), res.status))
817 finally:
818 CGIHTTPRequestHandler.cgi_directories.remove('/sub/dir/cgi-bin')
819
Siwon Kang91daa9d2019-11-22 18:13:05 +0900820
Georg Brandlb533e262008-05-25 18:19:30 +0000821
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000822class SocketlessRequestHandler(SimpleHTTPRequestHandler):
Géry Ogam781266e2019-09-11 15:03:46 +0200823 def __init__(self, directory=None):
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200824 request = mock.Mock()
825 request.makefile.return_value = BytesIO()
Géry Ogam781266e2019-09-11 15:03:46 +0200826 super().__init__(request, None, None, directory=directory)
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200827
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000828 self.get_called = False
829 self.protocol_version = "HTTP/1.1"
830
831 def do_GET(self):
832 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200833 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000834 self.send_header('Content-Type', 'text/html')
835 self.end_headers()
836 self.wfile.write(b'<html><body>Data</body></html>\r\n')
837
838 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000839 pass
840
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000841class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
842 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200843 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000844 return False
845
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800846
847class AuditableBytesIO:
848
849 def __init__(self):
850 self.datas = []
851
852 def write(self, data):
853 self.datas.append(data)
854
855 def getData(self):
856 return b''.join(self.datas)
857
858 @property
859 def numWrites(self):
860 return len(self.datas)
861
862
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000863class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200864 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000865
866 Test the support for the Expect 100-continue header.
867 """
868
869 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
870
871 def setUp (self):
872 self.handler = SocketlessRequestHandler()
873
874 def send_typical_request(self, message):
875 input = BytesIO(message)
876 output = BytesIO()
877 self.handler.rfile = input
878 self.handler.wfile = output
879 self.handler.handle_one_request()
880 output.seek(0)
881 return output.readlines()
882
883 def verify_get_called(self):
884 self.assertTrue(self.handler.get_called)
885
886 def verify_expected_headers(self, headers):
887 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
888 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
889
890 def verify_http_server_response(self, response):
891 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200892 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000893
894 def test_http_1_1(self):
895 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
896 self.verify_http_server_response(result[0])
897 self.verify_expected_headers(result[1:-1])
898 self.verify_get_called()
899 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500900 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
901 self.assertEqual(self.handler.command, 'GET')
902 self.assertEqual(self.handler.path, '/')
903 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
904 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000905
906 def test_http_1_0(self):
907 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
908 self.verify_http_server_response(result[0])
909 self.verify_expected_headers(result[1:-1])
910 self.verify_get_called()
911 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500912 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
913 self.assertEqual(self.handler.command, 'GET')
914 self.assertEqual(self.handler.path, '/')
915 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
916 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000917
918 def test_http_0_9(self):
919 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
920 self.assertEqual(len(result), 1)
921 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
922 self.verify_get_called()
923
Martin Pantere82338d2016-11-19 01:06:37 +0000924 def test_extra_space(self):
925 result = self.send_typical_request(
926 b'GET /spaced out HTTP/1.1\r\n'
927 b'Host: dummy\r\n'
928 b'\r\n'
929 )
930 self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
931 self.verify_expected_headers(result[1:result.index(b'\r\n')])
932 self.assertFalse(self.handler.get_called)
933
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000934 def test_with_continue_1_0(self):
935 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
936 self.verify_http_server_response(result[0])
937 self.verify_expected_headers(result[1:-1])
938 self.verify_get_called()
939 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500940 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
941 self.assertEqual(self.handler.command, 'GET')
942 self.assertEqual(self.handler.path, '/')
943 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
944 headers = (("Expect", "100-continue"),)
945 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000946
947 def test_with_continue_1_1(self):
948 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
949 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500950 self.assertEqual(result[1], b'\r\n')
951 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000952 self.verify_expected_headers(result[2:-1])
953 self.verify_get_called()
954 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500955 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
956 self.assertEqual(self.handler.command, 'GET')
957 self.assertEqual(self.handler.path, '/')
958 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
959 headers = (("Expect", "100-continue"),)
960 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000961
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800962 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000963
964 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800965 output = AuditableBytesIO()
966 handler = SocketlessRequestHandler()
967 handler.rfile = input
968 handler.wfile = output
969 handler.request_version = 'HTTP/1.1'
970 handler.requestline = ''
971 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000972
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800973 handler.send_error(418)
974 self.assertEqual(output.numWrites, 2)
975
976 def test_header_buffering_of_send_response_only(self):
977
978 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
979 output = AuditableBytesIO()
980 handler = SocketlessRequestHandler()
981 handler.rfile = input
982 handler.wfile = output
983 handler.request_version = 'HTTP/1.1'
984
985 handler.send_response_only(418)
986 self.assertEqual(output.numWrites, 0)
987 handler.end_headers()
988 self.assertEqual(output.numWrites, 1)
989
990 def test_header_buffering_of_send_header(self):
991
992 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
993 output = AuditableBytesIO()
994 handler = SocketlessRequestHandler()
995 handler.rfile = input
996 handler.wfile = output
997 handler.request_version = 'HTTP/1.1'
998
999 handler.send_header('Foo', 'foo')
1000 handler.send_header('bar', 'bar')
1001 self.assertEqual(output.numWrites, 0)
1002 handler.end_headers()
1003 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
1004 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +00001005
1006 def test_header_unbuffered_when_continue(self):
1007
1008 def _readAndReseek(f):
1009 pos = f.tell()
1010 f.seek(0)
1011 data = f.read()
1012 f.seek(pos)
1013 return data
1014
1015 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
1016 output = BytesIO()
1017 self.handler.rfile = input
1018 self.handler.wfile = output
1019 self.handler.request_version = 'HTTP/1.1'
1020
1021 self.handler.handle_one_request()
1022 self.assertNotEqual(_readAndReseek(output), b'')
1023 result = _readAndReseek(output).split(b'\r\n')
1024 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -05001025 self.assertEqual(result[1], b'')
1026 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +00001027
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001028 def test_with_continue_rejected(self):
1029 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
1030 self.handler = RejectingSocketlessRequestHandler()
1031 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
1032 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
1033 self.verify_expected_headers(result[1:-1])
1034 # The expect handler should short circuit the usual get method by
1035 # returning false here, so get_called should be false
1036 self.assertFalse(self.handler.get_called)
1037 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
1038 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
1039
Antoine Pitrouc4924372010-12-16 16:48:36 +00001040 def test_request_length(self):
1041 # Issue #10714: huge request lines are discarded, to avoid Denial
1042 # of Service attacks.
1043 result = self.send_typical_request(b'GET ' + b'x' * 65537)
1044 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
1045 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001046 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001047
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001048 def test_header_length(self):
1049 # Issue #6791: same for headers
1050 result = self.send_typical_request(
1051 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +00001052 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001053 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001054 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1055
Martin Panteracc03192016-04-03 00:45:46 +00001056 def test_too_many_headers(self):
1057 result = self.send_typical_request(
1058 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
1059 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
1060 self.assertFalse(self.handler.get_called)
1061 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1062
Martin Panterda3bb382016-04-11 00:40:08 +00001063 def test_html_escape_on_error(self):
1064 result = self.send_typical_request(
1065 b'<script>alert("hello")</script> / HTTP/1.1')
1066 result = b''.join(result)
1067 text = '<script>alert("hello")</script>'
1068 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
1069
Benjamin Peterson70e28472015-02-17 21:11:10 -05001070 def test_close_connection(self):
1071 # handle_one_request() should be repeatedly called until
1072 # it sets close_connection
1073 def handle_one_request():
1074 self.handler.close_connection = next(close_values)
1075 self.handler.handle_one_request = handle_one_request
1076
1077 close_values = iter((True,))
1078 self.handler.handle()
1079 self.assertRaises(StopIteration, next, close_values)
1080
1081 close_values = iter((False, False, True))
1082 self.handler.handle()
1083 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001084
Berker Peksag04bc5b92016-03-14 06:06:03 +02001085 def test_date_time_string(self):
1086 now = time.time()
1087 # this is the old code that formats the timestamp
1088 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
1089 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
1090 self.handler.weekdayname[wd],
1091 day,
1092 self.handler.monthname[month],
1093 year, hh, mm, ss
1094 )
1095 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
1096
1097
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001098class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
1099 """ Test url parsing """
1100 def setUp(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001101 self.translated_1 = os.path.join(os.getcwd(), 'filename')
1102 self.translated_2 = os.path.join('foo', 'filename')
1103 self.translated_3 = os.path.join('bar', 'filename')
1104 self.handler_1 = SocketlessRequestHandler()
1105 self.handler_2 = SocketlessRequestHandler(directory='foo')
1106 self.handler_3 = SocketlessRequestHandler(directory=pathlib.PurePath('bar'))
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001107
1108 def test_query_arguments(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001109 path = self.handler_1.translate_path('/filename')
1110 self.assertEqual(path, self.translated_1)
1111 path = self.handler_2.translate_path('/filename')
1112 self.assertEqual(path, self.translated_2)
1113 path = self.handler_3.translate_path('/filename')
1114 self.assertEqual(path, self.translated_3)
1115
1116 path = self.handler_1.translate_path('/filename?foo=bar')
1117 self.assertEqual(path, self.translated_1)
1118 path = self.handler_2.translate_path('/filename?foo=bar')
1119 self.assertEqual(path, self.translated_2)
1120 path = self.handler_3.translate_path('/filename?foo=bar')
1121 self.assertEqual(path, self.translated_3)
1122
1123 path = self.handler_1.translate_path('/filename?a=b&spam=eggs#zot')
1124 self.assertEqual(path, self.translated_1)
1125 path = self.handler_2.translate_path('/filename?a=b&spam=eggs#zot')
1126 self.assertEqual(path, self.translated_2)
1127 path = self.handler_3.translate_path('/filename?a=b&spam=eggs#zot')
1128 self.assertEqual(path, self.translated_3)
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001129
1130 def test_start_with_double_slash(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001131 path = self.handler_1.translate_path('//filename')
1132 self.assertEqual(path, self.translated_1)
1133 path = self.handler_2.translate_path('//filename')
1134 self.assertEqual(path, self.translated_2)
1135 path = self.handler_3.translate_path('//filename')
1136 self.assertEqual(path, self.translated_3)
1137
1138 path = self.handler_1.translate_path('//filename?foo=bar')
1139 self.assertEqual(path, self.translated_1)
1140 path = self.handler_2.translate_path('//filename?foo=bar')
1141 self.assertEqual(path, self.translated_2)
1142 path = self.handler_3.translate_path('//filename?foo=bar')
1143 self.assertEqual(path, self.translated_3)
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001144
Martin Panterd274b3f2016-04-18 03:45:18 +00001145 def test_windows_colon(self):
1146 with support.swap_attr(server.os, 'path', ntpath):
Géry Ogam781266e2019-09-11 15:03:46 +02001147 path = self.handler_1.translate_path('c:c:c:foo/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001148 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001149 self.assertEqual(path, self.translated_1)
1150 path = self.handler_2.translate_path('c:c:c:foo/filename')
1151 path = path.replace(ntpath.sep, os.sep)
1152 self.assertEqual(path, self.translated_2)
1153 path = self.handler_3.translate_path('c:c:c:foo/filename')
1154 path = path.replace(ntpath.sep, os.sep)
1155 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001156
Géry Ogam781266e2019-09-11 15:03:46 +02001157 path = self.handler_1.translate_path('\\c:../filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001158 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001159 self.assertEqual(path, self.translated_1)
1160 path = self.handler_2.translate_path('\\c:../filename')
1161 path = path.replace(ntpath.sep, os.sep)
1162 self.assertEqual(path, self.translated_2)
1163 path = self.handler_3.translate_path('\\c:../filename')
1164 path = path.replace(ntpath.sep, os.sep)
1165 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001166
Géry Ogam781266e2019-09-11 15:03:46 +02001167 path = self.handler_1.translate_path('c:\\c:..\\foo/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001168 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001169 self.assertEqual(path, self.translated_1)
1170 path = self.handler_2.translate_path('c:\\c:..\\foo/filename')
1171 path = path.replace(ntpath.sep, os.sep)
1172 self.assertEqual(path, self.translated_2)
1173 path = self.handler_3.translate_path('c:\\c:..\\foo/filename')
1174 path = path.replace(ntpath.sep, os.sep)
1175 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001176
Géry Ogam781266e2019-09-11 15:03:46 +02001177 path = self.handler_1.translate_path('c:c:foo\\c:c:bar/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001178 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001179 self.assertEqual(path, self.translated_1)
1180 path = self.handler_2.translate_path('c:c:foo\\c:c:bar/filename')
1181 path = path.replace(ntpath.sep, os.sep)
1182 self.assertEqual(path, self.translated_2)
1183 path = self.handler_3.translate_path('c:c:foo\\c:c:bar/filename')
1184 path = path.replace(ntpath.sep, os.sep)
1185 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001186
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001187
Berker Peksag366c5702015-02-13 20:48:15 +02001188class MiscTestCase(unittest.TestCase):
1189 def test_all(self):
1190 expected = []
1191 blacklist = {'executable', 'nobody_uid', 'test'}
1192 for name in dir(server):
1193 if name.startswith('_') or name in blacklist:
1194 continue
1195 module_object = getattr(server, name)
1196 if getattr(module_object, '__module__', None) == 'http.server':
1197 expected.append(name)
1198 self.assertCountEqual(server.__all__, expected)
1199
1200
Lisa Roach433433f2018-11-26 10:43:38 -08001201class ScriptTestCase(unittest.TestCase):
Jason R. Coombsf2890842019-02-07 08:22:45 -05001202
1203 def mock_server_class(self):
1204 return mock.MagicMock(
1205 return_value=mock.MagicMock(
1206 __enter__=mock.MagicMock(
1207 return_value=mock.MagicMock(
1208 socket=mock.MagicMock(
1209 getsockname=lambda: ('', 0),
1210 ),
1211 ),
1212 ),
1213 ),
1214 )
1215
1216 @mock.patch('builtins.print')
1217 def test_server_test_unspec(self, _):
1218 mock_server = self.mock_server_class()
1219 server.test(ServerClass=mock_server, bind=None)
1220 self.assertIn(
1221 mock_server.address_family,
1222 (socket.AF_INET6, socket.AF_INET),
1223 )
1224
1225 @mock.patch('builtins.print')
1226 def test_server_test_localhost(self, _):
1227 mock_server = self.mock_server_class()
1228 server.test(ServerClass=mock_server, bind="localhost")
1229 self.assertIn(
1230 mock_server.address_family,
1231 (socket.AF_INET6, socket.AF_INET),
1232 )
1233
1234 ipv6_addrs = (
1235 "::",
1236 "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
1237 "::1",
1238 )
1239
1240 ipv4_addrs = (
1241 "0.0.0.0",
1242 "8.8.8.8",
1243 "127.0.0.1",
1244 )
1245
Lisa Roach433433f2018-11-26 10:43:38 -08001246 @mock.patch('builtins.print')
1247 def test_server_test_ipv6(self, _):
Jason R. Coombsf2890842019-02-07 08:22:45 -05001248 for bind in self.ipv6_addrs:
1249 mock_server = self.mock_server_class()
1250 server.test(ServerClass=mock_server, bind=bind)
1251 self.assertEqual(mock_server.address_family, socket.AF_INET6)
Lisa Roach433433f2018-11-26 10:43:38 -08001252
Jason R. Coombsf2890842019-02-07 08:22:45 -05001253 @mock.patch('builtins.print')
1254 def test_server_test_ipv4(self, _):
1255 for bind in self.ipv4_addrs:
1256 mock_server = self.mock_server_class()
1257 server.test(ServerClass=mock_server, bind=bind)
1258 self.assertEqual(mock_server.address_family, socket.AF_INET)
Lisa Roach433433f2018-11-26 10:43:38 -08001259
1260
Georg Brandlb533e262008-05-25 18:19:30 +00001261def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001262 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001263 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001264 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001265 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001266 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001267 BaseHTTPServerTestCase,
1268 SimpleHTTPServerTestCase,
1269 CGIHTTPServerTestCase,
1270 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001271 MiscTestCase,
Lisa Roach433433f2018-11-26 10:43:38 -08001272 ScriptTestCase
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001273 )
Georg Brandlb533e262008-05-25 18:19:30 +00001274 finally:
1275 os.chdir(cwd)
1276
1277if __name__ == '__main__':
1278 test_main()