blob: dafcb0cbd56ba33a741c8357d392bc87acfabfd1 [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
12import sys
Senthil Kumaran0f476d42010-09-30 06:09:18 +000013import re
Georg Brandlb533e262008-05-25 18:19:30 +000014import base64
Martin Panterd274b3f2016-04-18 03:45:18 +000015import ntpath
Georg Brandlb533e262008-05-25 18:19:30 +000016import shutil
Pierre Quentel351adda2017-04-02 12:26:12 +020017import email.message
18import email.utils
Serhiy Storchakacb5bc402014-08-17 08:22:11 +030019import html
Georg Brandl24420152008-05-26 16:32:26 +000020import http.client
Pierre Quentel351adda2017-04-02 12:26:12 +020021import urllib.parse
Georg Brandlb533e262008-05-25 18:19:30 +000022import tempfile
Berker Peksag04bc5b92016-03-14 06:06:03 +020023import time
Pierre Quentel351adda2017-04-02 12:26:12 +020024import datetime
Senthil Kumaran0f476d42010-09-30 06:09:18 +000025from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000026
27import unittest
28from test import support
Victor Stinner45df8202010-04-28 22:31:17 +000029threading = support.import_module('threading')
Georg Brandlb533e262008-05-25 18:19:30 +000030
Georg Brandlb533e262008-05-25 18:19:30 +000031class NoLogRequestHandler:
32 def log_message(self, *args):
33 # don't write log messages to stderr
34 pass
35
Barry Warsaw820c1202008-06-12 04:06:45 +000036 def read(self, n=None):
37 return ''
38
Georg Brandlb533e262008-05-25 18:19:30 +000039
40class TestServerThread(threading.Thread):
41 def __init__(self, test_object, request_handler):
42 threading.Thread.__init__(self)
43 self.request_handler = request_handler
44 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000045
46 def run(self):
Antoine Pitroucb342182011-03-21 00:26:51 +010047 self.server = HTTPServer(('localhost', 0), self.request_handler)
48 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000049 self.test_object.server_started.set()
50 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000051 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000052 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000053 finally:
54 self.server.server_close()
55
56 def stop(self):
57 self.server.shutdown()
58
59
60class BaseTestCase(unittest.TestCase):
61 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000062 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000063 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000064 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000065 self.thread = TestServerThread(self, self.request_handler)
66 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000067 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000068
69 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000070 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020071 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000072 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000073 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000074
75 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010076 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000077 self.connection.request(method, uri, body, headers)
78 return self.connection.getresponse()
79
80
81class BaseHTTPServerTestCase(BaseTestCase):
82 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
83 protocol_version = 'HTTP/1.1'
84 default_request_version = 'HTTP/1.1'
85
86 def do_TEST(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020087 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000088 self.send_header('Content-Type', 'text/html')
89 self.send_header('Connection', 'close')
90 self.end_headers()
91
92 def do_KEEP(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', 'keep-alive')
96 self.end_headers()
97
98 def do_KEYERROR(self):
99 self.send_error(999)
100
Senthil Kumaran52d27202012-10-10 23:16:21 -0700101 def do_NOTFOUND(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200102 self.send_error(HTTPStatus.NOT_FOUND)
Senthil Kumaran52d27202012-10-10 23:16:21 -0700103
Senthil Kumaran26886442013-03-15 07:53:21 -0700104 def do_EXPLAINERROR(self):
105 self.send_error(999, "Short Message",
Martin Panter46f50722016-05-26 05:35:26 +0000106 "This is a long \n explanation")
Senthil Kumaran26886442013-03-15 07:53:21 -0700107
Georg Brandlb533e262008-05-25 18:19:30 +0000108 def do_CUSTOM(self):
109 self.send_response(999)
110 self.send_header('Content-Type', 'text/html')
111 self.send_header('Connection', 'close')
112 self.end_headers()
113
Armin Ronacher8d96d772011-01-22 13:13:05 +0000114 def do_LATINONEHEADER(self):
115 self.send_response(999)
116 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000117 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000118 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000119 body = self.headers['x-special-incoming'].encode('utf-8')
120 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000121
Martin Pantere42e1292016-06-08 08:29:13 +0000122 def do_SEND_ERROR(self):
123 self.send_error(int(self.path[1:]))
124
125 def do_HEAD(self):
126 self.send_error(int(self.path[1:]))
127
Georg Brandlb533e262008-05-25 18:19:30 +0000128 def setUp(self):
129 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100130 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000131 self.con.connect()
132
133 def test_command(self):
134 self.con.request('GET', '/')
135 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200136 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000137
138 def test_request_line_trimming(self):
139 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400140 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000141 self.con.endheaders()
142 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200143 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000144
145 def test_version_bogus(self):
146 self.con._http_vsn_str = 'FUBAR'
147 self.con.putrequest('GET', '/')
148 self.con.endheaders()
149 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200150 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000151
152 def test_version_digits(self):
153 self.con._http_vsn_str = 'HTTP/9.9.9'
154 self.con.putrequest('GET', '/')
155 self.con.endheaders()
156 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200157 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000158
159 def test_version_none_get(self):
160 self.con._http_vsn_str = ''
161 self.con.putrequest('GET', '/')
162 self.con.endheaders()
163 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200164 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000165
166 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400167 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000168 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400169 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000170 self.con.endheaders()
171 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200172 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000173
174 def test_version_invalid(self):
175 self.con._http_vsn = 99
176 self.con._http_vsn_str = 'HTTP/9.9'
177 self.con.putrequest('GET', '/')
178 self.con.endheaders()
179 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200180 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000181
182 def test_send_blank(self):
183 self.con._http_vsn_str = ''
184 self.con.putrequest('', '')
185 self.con.endheaders()
186 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200187 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000188
189 def test_header_close(self):
190 self.con.putrequest('GET', '/')
191 self.con.putheader('Connection', 'close')
192 self.con.endheaders()
193 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200194 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000195
Berker Peksag20853612016-08-25 01:13:34 +0300196 def test_header_keep_alive(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000197 self.con._http_vsn_str = 'HTTP/1.1'
198 self.con.putrequest('GET', '/')
199 self.con.putheader('Connection', 'keep-alive')
200 self.con.endheaders()
201 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200202 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000203
204 def test_handler(self):
205 self.con.request('TEST', '/')
206 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200207 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000208
209 def test_return_header_keep_alive(self):
210 self.con.request('KEEP', '/')
211 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000212 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000213 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000214 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000215
216 def test_internal_key_error(self):
217 self.con.request('KEYERROR', '/')
218 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000219 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000220
221 def test_return_custom_status(self):
222 self.con.request('CUSTOM', '/')
223 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000224 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000225
Senthil Kumaran26886442013-03-15 07:53:21 -0700226 def test_return_explain_error(self):
227 self.con.request('EXPLAINERROR', '/')
228 res = self.con.getresponse()
229 self.assertEqual(res.status, 999)
230 self.assertTrue(int(res.getheader('Content-Length')))
231
Armin Ronacher8d96d772011-01-22 13:13:05 +0000232 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000233 self.con.request('LATINONEHEADER', '/', headers={
234 'X-Special-Incoming': 'Ärger mit Unicode'
235 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000236 res = self.con.getresponse()
237 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000238 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000239
Senthil Kumaran52d27202012-10-10 23:16:21 -0700240 def test_error_content_length(self):
241 # Issue #16088: standard error responses should have a content-length
242 self.con.request('NOTFOUND', '/')
243 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200244 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
245
Senthil Kumaran52d27202012-10-10 23:16:21 -0700246 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700247 self.assertEqual(int(res.getheader('Content-Length')), len(data))
248
Martin Pantere42e1292016-06-08 08:29:13 +0000249 def test_send_error(self):
250 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
251 HTTPStatus.RESET_CONTENT)
252 for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
253 HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
254 HTTPStatus.SWITCHING_PROTOCOLS):
255 self.con.request('SEND_ERROR', '/{}'.format(code))
256 res = self.con.getresponse()
257 self.assertEqual(code, res.status)
258 self.assertEqual(None, res.getheader('Content-Length'))
259 self.assertEqual(None, res.getheader('Content-Type'))
260 if code not in allow_transfer_encoding_codes:
261 self.assertEqual(None, res.getheader('Transfer-Encoding'))
262
263 data = res.read()
264 self.assertEqual(b'', data)
265
266 def test_head_via_send_error(self):
267 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
268 HTTPStatus.RESET_CONTENT)
269 for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
270 HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
271 HTTPStatus.SWITCHING_PROTOCOLS):
272 self.con.request('HEAD', '/{}'.format(code))
273 res = self.con.getresponse()
274 self.assertEqual(code, res.status)
275 if code == HTTPStatus.OK:
276 self.assertTrue(int(res.getheader('Content-Length')) > 0)
277 self.assertIn('text/html', res.getheader('Content-Type'))
278 else:
279 self.assertEqual(None, res.getheader('Content-Length'))
280 self.assertEqual(None, res.getheader('Content-Type'))
281 if code not in allow_transfer_encoding_codes:
282 self.assertEqual(None, res.getheader('Transfer-Encoding'))
283
284 data = res.read()
285 self.assertEqual(b'', data)
286
Georg Brandlb533e262008-05-25 18:19:30 +0000287
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200288class RequestHandlerLoggingTestCase(BaseTestCase):
289 class request_handler(BaseHTTPRequestHandler):
290 protocol_version = 'HTTP/1.1'
291 default_request_version = 'HTTP/1.1'
292
293 def do_GET(self):
294 self.send_response(HTTPStatus.OK)
295 self.end_headers()
296
297 def do_ERROR(self):
298 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
299
300 def test_get(self):
301 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
302 self.con.connect()
303
304 with support.captured_stderr() as err:
305 self.con.request('GET', '/')
306 self.con.getresponse()
307
308 self.assertTrue(
309 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
310
311 def test_err(self):
312 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
313 self.con.connect()
314
315 with support.captured_stderr() as err:
316 self.con.request('ERROR', '/')
317 self.con.getresponse()
318
319 lines = err.getvalue().split('\n')
320 self.assertTrue(lines[0].endswith('code 404, message File not found'))
321 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
322
323
Georg Brandlb533e262008-05-25 18:19:30 +0000324class SimpleHTTPServerTestCase(BaseTestCase):
325 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
326 pass
327
328 def setUp(self):
329 BaseTestCase.setUp(self)
330 self.cwd = os.getcwd()
331 basetempdir = tempfile.gettempdir()
332 os.chdir(basetempdir)
333 self.data = b'We are the knights who say Ni!'
334 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
335 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panterfc475a92016-04-09 04:56:10 +0000336 self.base_url = '/' + self.tempdir_name
Brett Cannon105df5d2010-10-29 23:43:42 +0000337 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
338 temp.write(self.data)
Pierre Quentel351adda2017-04-02 12:26:12 +0200339 mtime = os.fstat(temp.fileno()).st_mtime
340 # compute last modification datetime for browser cache tests
341 last_modif = datetime.datetime.fromtimestamp(mtime,
342 datetime.timezone.utc)
343 self.last_modif_datetime = last_modif.replace(microsecond=0)
344 self.last_modif_header = email.utils.formatdate(
345 last_modif.timestamp(), usegmt=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000346
347 def tearDown(self):
348 try:
349 os.chdir(self.cwd)
350 try:
351 shutil.rmtree(self.tempdir)
352 except:
353 pass
354 finally:
355 BaseTestCase.tearDown(self)
356
357 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300358 def close_conn():
359 """Don't close reader yet so we can check if there was leftover
360 buffered input"""
361 nonlocal reader
362 reader = response.fp
363 response.fp = None
364 reader = None
365 response._close_conn = close_conn
366
Georg Brandlb533e262008-05-25 18:19:30 +0000367 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000368 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000369 self.assertEqual(response.status, status)
370 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000371 if data:
372 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300373 # Ensure the server has not set up a persistent connection, and has
374 # not sent any extra data
375 self.assertEqual(response.version, 10)
376 self.assertEqual(response.msg.get("Connection", "close"), "close")
377 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
378
379 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300380 return body
381
Ned Deily14183202015-01-05 01:02:30 -0800382 @support.requires_mac_ver(10, 5)
Steve Dowere58571b2016-09-08 11:11:13 -0700383 @unittest.skipIf(sys.platform == 'win32',
384 'undecodable name cannot be decoded on win32')
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300385 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
386 'need support.TESTFN_UNDECODABLE')
387 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300388 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300389 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
390 with open(os.path.join(self.tempdir, filename), 'wb') as f:
391 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000392 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300393 if sys.platform == 'darwin':
394 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
395 # UTF-8 into a percent-encoded value.
396 for name in os.listdir(self.tempdir):
397 if name != 'test': # Ignore a filename created in setUp().
398 filename = name
399 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200400 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300401 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
402 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300403 .encode(enc, 'surrogateescape'), body)
Martin Panterda3bb382016-04-11 00:40:08 +0000404 self.assertIn(('>%s<' % html.escape(filename, quote=False))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300405 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000406 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200407 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300408 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000409
410 def test_get(self):
411 #constructs the path relative to the root directory of the HTTPServer
Martin Panterfc475a92016-04-09 04:56:10 +0000412 response = self.request(self.base_url + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200413 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700414 # check for trailing "/" which should return 404. See Issue17324
Martin Panterfc475a92016-04-09 04:56:10 +0000415 response = self.request(self.base_url + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200416 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Martin Panterfc475a92016-04-09 04:56:10 +0000417 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200418 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000419 response = self.request(self.base_url)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200420 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000421 response = self.request(self.base_url + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200422 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000423 response = self.request(self.base_url + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200424 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600425 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000426 self.base_url + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000427 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200428 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000429 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200430 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300431
432 data = b"Dummy index file\r\n"
433 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
434 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000435 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300436 self.check_status_and_reason(response, HTTPStatus.OK, data)
437
438 # chmod() doesn't work as expected on Windows, and filesystem
439 # permissions are ignored by root on Unix.
440 if os.name == 'posix' and os.geteuid() != 0:
441 os.chmod(self.tempdir, 0)
442 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000443 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200444 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300445 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000446 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000447
448 def test_head(self):
449 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000450 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200451 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000452 self.assertEqual(response.getheader('content-length'),
453 str(len(self.data)))
454 self.assertEqual(response.getheader('content-type'),
455 'application/octet-stream')
456
Pierre Quentel351adda2017-04-02 12:26:12 +0200457 def test_browser_cache(self):
458 """Check that when a request to /test is sent with the request header
459 If-Modified-Since set to date of last modification, the server returns
460 status code 304, not 200
461 """
462 headers = email.message.Message()
463 headers['If-Modified-Since'] = self.last_modif_header
464 response = self.request(self.base_url + '/test', headers=headers)
465 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
466
467 # one hour after last modification : must return 304
468 new_dt = self.last_modif_datetime + datetime.timedelta(hours=1)
469 headers = email.message.Message()
470 headers['If-Modified-Since'] = email.utils.format_datetime(new_dt,
471 usegmt=True)
472 response = self.request(self.base_url + '/test', headers=headers)
473 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
474
475 def test_browser_cache_file_changed(self):
476 # with If-Modified-Since earlier than Last-Modified, must return 200
477 dt = self.last_modif_datetime
478 # build datetime object : 365 days before last modification
479 old_dt = dt - datetime.timedelta(days=365)
480 headers = email.message.Message()
481 headers['If-Modified-Since'] = email.utils.format_datetime(old_dt,
482 usegmt=True)
483 response = self.request(self.base_url + '/test', headers=headers)
484 self.check_status_and_reason(response, HTTPStatus.OK)
485
486 def test_browser_cache_with_If_None_Match_header(self):
487 # if If-None-Match header is present, ignore If-Modified-Since
488
489 headers = email.message.Message()
490 headers['If-Modified-Since'] = self.last_modif_header
491 headers['If-None-Match'] = "*"
492 response = self.request(self.base_url + '/test', headers=headers)
493 self.check_status_and_reason(response, HTTPStatus.OK)
494
Georg Brandlb533e262008-05-25 18:19:30 +0000495 def test_invalid_requests(self):
496 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200497 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000498 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400499 response = self.request('/', method='custom')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200500 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000501 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200502 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000503
Pierre Quentel351adda2017-04-02 12:26:12 +0200504 def test_last_modified(self):
505 """Checks that the datetime returned in Last-Modified response header
506 is the actual datetime of last modification, rounded to the second
507 """
508 response = self.request(self.base_url + '/test')
509 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
510 last_modif_header = response.headers['Last-modified']
511 self.assertEqual(last_modif_header, self.last_modif_header)
512
Martin Panterfc475a92016-04-09 04:56:10 +0000513 def test_path_without_leading_slash(self):
514 response = self.request(self.tempdir_name + '/test')
515 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
516 response = self.request(self.tempdir_name + '/test/')
517 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
518 response = self.request(self.tempdir_name + '/')
519 self.check_status_and_reason(response, HTTPStatus.OK)
520 response = self.request(self.tempdir_name)
521 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
522 response = self.request(self.tempdir_name + '/?hi=2')
523 self.check_status_and_reason(response, HTTPStatus.OK)
524 response = self.request(self.tempdir_name + '?hi=1')
525 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
526 self.assertEqual(response.getheader("Location"),
527 self.tempdir_name + "/?hi=1")
528
Martin Panterda3bb382016-04-11 00:40:08 +0000529 def test_html_escape_filename(self):
530 filename = '<test&>.txt'
531 fullpath = os.path.join(self.tempdir, filename)
532
533 try:
534 open(fullpath, 'w').close()
535 except OSError:
536 raise unittest.SkipTest('Can not create file %s on current file '
537 'system' % filename)
538
539 try:
540 response = self.request(self.base_url + '/')
541 body = self.check_status_and_reason(response, HTTPStatus.OK)
542 enc = response.headers.get_content_charset()
543 finally:
544 os.unlink(fullpath) # avoid affecting test_undecodable_filename
545
546 self.assertIsNotNone(enc)
547 html_text = '>%s<' % html.escape(filename, quote=False)
548 self.assertIn(html_text.encode(enc), body)
549
Georg Brandlb533e262008-05-25 18:19:30 +0000550
551cgi_file1 = """\
552#!%s
553
554print("Content-type: text/html")
555print()
556print("Hello World")
557"""
558
559cgi_file2 = """\
560#!%s
561import cgi
562
563print("Content-type: text/html")
564print()
565
566form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000567print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
568 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000569"""
570
Martin Pantera02e18a2015-10-03 05:38:07 +0000571cgi_file4 = """\
572#!%s
573import os
574
575print("Content-type: text/html")
576print()
577
578print(os.environ["%s"])
579"""
580
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100581
582@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
583 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000584class CGIHTTPServerTestCase(BaseTestCase):
585 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
586 pass
587
Antoine Pitroue768c392012-08-05 14:52:45 +0200588 linesep = os.linesep.encode('ascii')
589
Georg Brandlb533e262008-05-25 18:19:30 +0000590 def setUp(self):
591 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000592 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000593 self.parent_dir = tempfile.mkdtemp()
594 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700595 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000596 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700597 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400598 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000599 self.file1_path = None
600 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700601 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000602 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000603
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000604 # The shebang line should be pure ASCII: use symlink if possible.
605 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000606 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000607 self.pythonexe = os.path.join(self.parent_dir, 'python')
608 os.symlink(sys.executable, self.pythonexe)
609 else:
610 self.pythonexe = sys.executable
611
Victor Stinner3218c312010-10-17 20:13:36 +0000612 try:
613 # The python executable path is written as the first line of the
614 # CGI Python script. The encoding cookie cannot be used, and so the
615 # path should be encodable to the default script encoding (utf-8)
616 self.pythonexe.encode('utf-8')
617 except UnicodeEncodeError:
618 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200619 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000620
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400621 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
622 with open(self.nocgi_path, 'w') as fp:
623 fp.write(cgi_file1 % self.pythonexe)
624 os.chmod(self.nocgi_path, 0o777)
625
Georg Brandlb533e262008-05-25 18:19:30 +0000626 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000627 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000628 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000629 os.chmod(self.file1_path, 0o777)
630
631 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000632 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000633 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000634 os.chmod(self.file2_path, 0o777)
635
Ned Deily915a30f2014-07-12 22:06:26 -0700636 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
637 with open(self.file3_path, 'w', encoding='utf-8') as file3:
638 file3.write(cgi_file1 % self.pythonexe)
639 os.chmod(self.file3_path, 0o777)
640
Martin Pantera02e18a2015-10-03 05:38:07 +0000641 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
642 with open(self.file4_path, 'w', encoding='utf-8') as file4:
643 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
644 os.chmod(self.file4_path, 0o777)
645
Georg Brandlb533e262008-05-25 18:19:30 +0000646 os.chdir(self.parent_dir)
647
648 def tearDown(self):
649 try:
650 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000651 if self.pythonexe != sys.executable:
652 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400653 if self.nocgi_path:
654 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000655 if self.file1_path:
656 os.remove(self.file1_path)
657 if self.file2_path:
658 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700659 if self.file3_path:
660 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000661 if self.file4_path:
662 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700663 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000664 os.rmdir(self.cgi_dir)
665 os.rmdir(self.parent_dir)
666 finally:
667 BaseTestCase.tearDown(self)
668
Senthil Kumarand70846b2012-04-12 02:34:32 +0800669 def test_url_collapse_path(self):
670 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000671 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800672 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000673 '..': IndexError,
674 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800675 '/': '//',
676 '//': '//',
677 '/\\': '//\\',
678 '/.//': '//',
679 'cgi-bin/file1.py': '/cgi-bin/file1.py',
680 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
681 'a': '//a',
682 '/a': '//a',
683 '//a': '//a',
684 './a': '//a',
685 './C:/': '/C:/',
686 '/a/b': '/a/b',
687 '/a/b/': '/a/b/',
688 '/a/b/.': '/a/b/',
689 '/a/b/c/..': '/a/b/',
690 '/a/b/c/../d': '/a/b/d',
691 '/a/b/c/../d/e/../f': '/a/b/d/f',
692 '/a/b/c/../d/e/../../f': '/a/b/f',
693 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000694 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800695 '/a/b/c/../d/e/../../../f': '/a/f',
696 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000697 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800698 '/a/b/c/../d/e/../../../../f/..': '//',
699 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000700 }
701 for path, expected in test_vectors.items():
702 if isinstance(expected, type) and issubclass(expected, Exception):
703 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800704 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000705 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800706 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000707 self.assertEqual(expected, actual,
708 msg='path = %r\nGot: %r\nWanted: %r' %
709 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000710
Georg Brandlb533e262008-05-25 18:19:30 +0000711 def test_headers_and_content(self):
712 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200713 self.assertEqual(
714 (res.read(), res.getheader('Content-type'), res.status),
715 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000716
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400717 def test_issue19435(self):
718 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200719 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400720
Georg Brandlb533e262008-05-25 18:19:30 +0000721 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000722 params = urllib.parse.urlencode(
723 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000724 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
725 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
726
Antoine Pitroue768c392012-08-05 14:52:45 +0200727 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000728
729 def test_invaliduri(self):
730 res = self.request('/cgi-bin/invalid')
731 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200732 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000733
734 def test_authorization(self):
735 headers = {b'Authorization' : b'Basic ' +
736 base64.b64encode(b'username:pass')}
737 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200738 self.assertEqual(
739 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
740 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000741
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000742 def test_no_leading_slash(self):
743 # http://bugs.python.org/issue2254
744 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200745 self.assertEqual(
746 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
747 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000748
Senthil Kumaran42713722010-10-03 17:55:45 +0000749 def test_os_environ_is_not_altered(self):
750 signature = "Test CGI Server"
751 os.environ['SERVER_SOFTWARE'] = signature
752 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200753 self.assertEqual(
754 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
755 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000756 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
757
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700758 def test_urlquote_decoding_in_cgi_check(self):
759 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200760 self.assertEqual(
761 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
762 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700763
Ned Deily915a30f2014-07-12 22:06:26 -0700764 def test_nested_cgi_path_issue21323(self):
765 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200766 self.assertEqual(
767 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
768 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700769
Martin Pantera02e18a2015-10-03 05:38:07 +0000770 def test_query_with_multiple_question_mark(self):
771 res = self.request('/cgi-bin/file4.py?a=b?c=d')
772 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000773 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000774 (res.read(), res.getheader('Content-type'), res.status))
775
Martin Pantercb29e8c2015-10-03 05:55:46 +0000776 def test_query_with_continuous_slashes(self):
777 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
778 self.assertEqual(
779 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000780 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000781 (res.read(), res.getheader('Content-type'), res.status))
782
Georg Brandlb533e262008-05-25 18:19:30 +0000783
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000784class SocketlessRequestHandler(SimpleHTTPRequestHandler):
785 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000786 self.get_called = False
787 self.protocol_version = "HTTP/1.1"
788
789 def do_GET(self):
790 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200791 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000792 self.send_header('Content-Type', 'text/html')
793 self.end_headers()
794 self.wfile.write(b'<html><body>Data</body></html>\r\n')
795
796 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000797 pass
798
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000799class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
800 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200801 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000802 return False
803
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800804
805class AuditableBytesIO:
806
807 def __init__(self):
808 self.datas = []
809
810 def write(self, data):
811 self.datas.append(data)
812
813 def getData(self):
814 return b''.join(self.datas)
815
816 @property
817 def numWrites(self):
818 return len(self.datas)
819
820
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000821class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200822 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000823
824 Test the support for the Expect 100-continue header.
825 """
826
827 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
828
829 def setUp (self):
830 self.handler = SocketlessRequestHandler()
831
832 def send_typical_request(self, message):
833 input = BytesIO(message)
834 output = BytesIO()
835 self.handler.rfile = input
836 self.handler.wfile = output
837 self.handler.handle_one_request()
838 output.seek(0)
839 return output.readlines()
840
841 def verify_get_called(self):
842 self.assertTrue(self.handler.get_called)
843
844 def verify_expected_headers(self, headers):
845 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
846 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
847
848 def verify_http_server_response(self, response):
849 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200850 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000851
852 def test_http_1_1(self):
853 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
854 self.verify_http_server_response(result[0])
855 self.verify_expected_headers(result[1:-1])
856 self.verify_get_called()
857 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500858 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
859 self.assertEqual(self.handler.command, 'GET')
860 self.assertEqual(self.handler.path, '/')
861 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
862 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000863
864 def test_http_1_0(self):
865 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
866 self.verify_http_server_response(result[0])
867 self.verify_expected_headers(result[1:-1])
868 self.verify_get_called()
869 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500870 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
871 self.assertEqual(self.handler.command, 'GET')
872 self.assertEqual(self.handler.path, '/')
873 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
874 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000875
876 def test_http_0_9(self):
877 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
878 self.assertEqual(len(result), 1)
879 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
880 self.verify_get_called()
881
Martin Pantere82338d2016-11-19 01:06:37 +0000882 def test_extra_space(self):
883 result = self.send_typical_request(
884 b'GET /spaced out HTTP/1.1\r\n'
885 b'Host: dummy\r\n'
886 b'\r\n'
887 )
888 self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
889 self.verify_expected_headers(result[1:result.index(b'\r\n')])
890 self.assertFalse(self.handler.get_called)
891
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000892 def test_with_continue_1_0(self):
893 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
894 self.verify_http_server_response(result[0])
895 self.verify_expected_headers(result[1:-1])
896 self.verify_get_called()
897 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500898 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
899 self.assertEqual(self.handler.command, 'GET')
900 self.assertEqual(self.handler.path, '/')
901 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
902 headers = (("Expect", "100-continue"),)
903 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000904
905 def test_with_continue_1_1(self):
906 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
907 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500908 self.assertEqual(result[1], b'\r\n')
909 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000910 self.verify_expected_headers(result[2:-1])
911 self.verify_get_called()
912 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500913 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
914 self.assertEqual(self.handler.command, 'GET')
915 self.assertEqual(self.handler.path, '/')
916 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
917 headers = (("Expect", "100-continue"),)
918 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000919
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800920 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000921
922 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800923 output = AuditableBytesIO()
924 handler = SocketlessRequestHandler()
925 handler.rfile = input
926 handler.wfile = output
927 handler.request_version = 'HTTP/1.1'
928 handler.requestline = ''
929 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000930
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800931 handler.send_error(418)
932 self.assertEqual(output.numWrites, 2)
933
934 def test_header_buffering_of_send_response_only(self):
935
936 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
937 output = AuditableBytesIO()
938 handler = SocketlessRequestHandler()
939 handler.rfile = input
940 handler.wfile = output
941 handler.request_version = 'HTTP/1.1'
942
943 handler.send_response_only(418)
944 self.assertEqual(output.numWrites, 0)
945 handler.end_headers()
946 self.assertEqual(output.numWrites, 1)
947
948 def test_header_buffering_of_send_header(self):
949
950 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
951 output = AuditableBytesIO()
952 handler = SocketlessRequestHandler()
953 handler.rfile = input
954 handler.wfile = output
955 handler.request_version = 'HTTP/1.1'
956
957 handler.send_header('Foo', 'foo')
958 handler.send_header('bar', 'bar')
959 self.assertEqual(output.numWrites, 0)
960 handler.end_headers()
961 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
962 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000963
964 def test_header_unbuffered_when_continue(self):
965
966 def _readAndReseek(f):
967 pos = f.tell()
968 f.seek(0)
969 data = f.read()
970 f.seek(pos)
971 return data
972
973 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
974 output = BytesIO()
975 self.handler.rfile = input
976 self.handler.wfile = output
977 self.handler.request_version = 'HTTP/1.1'
978
979 self.handler.handle_one_request()
980 self.assertNotEqual(_readAndReseek(output), b'')
981 result = _readAndReseek(output).split(b'\r\n')
982 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500983 self.assertEqual(result[1], b'')
984 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000985
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000986 def test_with_continue_rejected(self):
987 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
988 self.handler = RejectingSocketlessRequestHandler()
989 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
990 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
991 self.verify_expected_headers(result[1:-1])
992 # The expect handler should short circuit the usual get method by
993 # returning false here, so get_called should be false
994 self.assertFalse(self.handler.get_called)
995 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
996 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
997
Antoine Pitrouc4924372010-12-16 16:48:36 +0000998 def test_request_length(self):
999 # Issue #10714: huge request lines are discarded, to avoid Denial
1000 # of Service attacks.
1001 result = self.send_typical_request(b'GET ' + b'x' * 65537)
1002 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
1003 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001004 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001005
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001006 def test_header_length(self):
1007 # Issue #6791: same for headers
1008 result = self.send_typical_request(
1009 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +00001010 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001011 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001012 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1013
Martin Panteracc03192016-04-03 00:45:46 +00001014 def test_too_many_headers(self):
1015 result = self.send_typical_request(
1016 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
1017 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
1018 self.assertFalse(self.handler.get_called)
1019 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1020
Martin Panterda3bb382016-04-11 00:40:08 +00001021 def test_html_escape_on_error(self):
1022 result = self.send_typical_request(
1023 b'<script>alert("hello")</script> / HTTP/1.1')
1024 result = b''.join(result)
1025 text = '<script>alert("hello")</script>'
1026 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
1027
Benjamin Peterson70e28472015-02-17 21:11:10 -05001028 def test_close_connection(self):
1029 # handle_one_request() should be repeatedly called until
1030 # it sets close_connection
1031 def handle_one_request():
1032 self.handler.close_connection = next(close_values)
1033 self.handler.handle_one_request = handle_one_request
1034
1035 close_values = iter((True,))
1036 self.handler.handle()
1037 self.assertRaises(StopIteration, next, close_values)
1038
1039 close_values = iter((False, False, True))
1040 self.handler.handle()
1041 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001042
Berker Peksag04bc5b92016-03-14 06:06:03 +02001043 def test_date_time_string(self):
1044 now = time.time()
1045 # this is the old code that formats the timestamp
1046 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
1047 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
1048 self.handler.weekdayname[wd],
1049 day,
1050 self.handler.monthname[month],
1051 year, hh, mm, ss
1052 )
1053 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
1054
1055
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001056class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
1057 """ Test url parsing """
1058 def setUp(self):
1059 self.translated = os.getcwd()
1060 self.translated = os.path.join(self.translated, 'filename')
1061 self.handler = SocketlessRequestHandler()
1062
1063 def test_query_arguments(self):
1064 path = self.handler.translate_path('/filename')
1065 self.assertEqual(path, self.translated)
1066 path = self.handler.translate_path('/filename?foo=bar')
1067 self.assertEqual(path, self.translated)
1068 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
1069 self.assertEqual(path, self.translated)
1070
1071 def test_start_with_double_slash(self):
1072 path = self.handler.translate_path('//filename')
1073 self.assertEqual(path, self.translated)
1074 path = self.handler.translate_path('//filename?foo=bar')
1075 self.assertEqual(path, self.translated)
1076
Martin Panterd274b3f2016-04-18 03:45:18 +00001077 def test_windows_colon(self):
1078 with support.swap_attr(server.os, 'path', ntpath):
1079 path = self.handler.translate_path('c:c:c:foo/filename')
1080 path = path.replace(ntpath.sep, os.sep)
1081 self.assertEqual(path, self.translated)
1082
1083 path = self.handler.translate_path('\\c:../filename')
1084 path = path.replace(ntpath.sep, os.sep)
1085 self.assertEqual(path, self.translated)
1086
1087 path = self.handler.translate_path('c:\\c:..\\foo/filename')
1088 path = path.replace(ntpath.sep, os.sep)
1089 self.assertEqual(path, self.translated)
1090
1091 path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
1092 path = path.replace(ntpath.sep, os.sep)
1093 self.assertEqual(path, self.translated)
1094
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001095
Berker Peksag366c5702015-02-13 20:48:15 +02001096class MiscTestCase(unittest.TestCase):
1097 def test_all(self):
1098 expected = []
1099 blacklist = {'executable', 'nobody_uid', 'test'}
1100 for name in dir(server):
1101 if name.startswith('_') or name in blacklist:
1102 continue
1103 module_object = getattr(server, name)
1104 if getattr(module_object, '__module__', None) == 'http.server':
1105 expected.append(name)
1106 self.assertCountEqual(server.__all__, expected)
1107
1108
Georg Brandlb533e262008-05-25 18:19:30 +00001109def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001110 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001111 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001112 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001113 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001114 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001115 BaseHTTPServerTestCase,
1116 SimpleHTTPServerTestCase,
1117 CGIHTTPServerTestCase,
1118 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001119 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001120 )
Georg Brandlb533e262008-05-25 18:19:30 +00001121 finally:
1122 os.chdir(cwd)
1123
1124if __name__ == '__main__':
1125 test_main()