blob: 5049538e66418170da4d7d3a07d2d08fc5a2af1b [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
Jeremy Hylton1afc1692008-06-18 20:49:58 +000017import urllib.parse
Serhiy Storchakacb5bc402014-08-17 08:22:11 +030018import html
Georg Brandl24420152008-05-26 16:32:26 +000019import http.client
Georg Brandlb533e262008-05-25 18:19:30 +000020import tempfile
Berker Peksag04bc5b92016-03-14 06:06:03 +020021import time
Senthil Kumaran0f476d42010-09-30 06:09:18 +000022from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000023
24import unittest
25from test import support
Victor Stinner45df8202010-04-28 22:31:17 +000026threading = support.import_module('threading')
Georg Brandlb533e262008-05-25 18:19:30 +000027
Georg Brandlb533e262008-05-25 18:19:30 +000028class NoLogRequestHandler:
29 def log_message(self, *args):
30 # don't write log messages to stderr
31 pass
32
Barry Warsaw820c1202008-06-12 04:06:45 +000033 def read(self, n=None):
34 return ''
35
Georg Brandlb533e262008-05-25 18:19:30 +000036
37class TestServerThread(threading.Thread):
38 def __init__(self, test_object, request_handler):
39 threading.Thread.__init__(self)
40 self.request_handler = request_handler
41 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000042
43 def run(self):
Antoine Pitroucb342182011-03-21 00:26:51 +010044 self.server = HTTPServer(('localhost', 0), self.request_handler)
45 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000046 self.test_object.server_started.set()
47 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000048 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000049 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000050 finally:
51 self.server.server_close()
52
53 def stop(self):
54 self.server.shutdown()
55
56
57class BaseTestCase(unittest.TestCase):
58 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000059 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000060 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000061 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000062 self.thread = TestServerThread(self, self.request_handler)
63 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000064 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000065
66 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000067 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020068 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000069 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000070 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000071
72 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010073 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000074 self.connection.request(method, uri, body, headers)
75 return self.connection.getresponse()
76
77
78class BaseHTTPServerTestCase(BaseTestCase):
79 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
80 protocol_version = 'HTTP/1.1'
81 default_request_version = 'HTTP/1.1'
82
83 def do_TEST(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020084 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000085 self.send_header('Content-Type', 'text/html')
86 self.send_header('Connection', 'close')
87 self.end_headers()
88
89 def do_KEEP(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020090 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000091 self.send_header('Content-Type', 'text/html')
92 self.send_header('Connection', 'keep-alive')
93 self.end_headers()
94
95 def do_KEYERROR(self):
96 self.send_error(999)
97
Senthil Kumaran52d27202012-10-10 23:16:21 -070098 def do_NOTFOUND(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020099 self.send_error(HTTPStatus.NOT_FOUND)
Senthil Kumaran52d27202012-10-10 23:16:21 -0700100
Senthil Kumaran26886442013-03-15 07:53:21 -0700101 def do_EXPLAINERROR(self):
102 self.send_error(999, "Short Message",
Martin Panter46f50722016-05-26 05:35:26 +0000103 "This is a long \n explanation")
Senthil Kumaran26886442013-03-15 07:53:21 -0700104
Georg Brandlb533e262008-05-25 18:19:30 +0000105 def do_CUSTOM(self):
106 self.send_response(999)
107 self.send_header('Content-Type', 'text/html')
108 self.send_header('Connection', 'close')
109 self.end_headers()
110
Armin Ronacher8d96d772011-01-22 13:13:05 +0000111 def do_LATINONEHEADER(self):
112 self.send_response(999)
113 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000114 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000115 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000116 body = self.headers['x-special-incoming'].encode('utf-8')
117 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000118
Martin Pantere42e1292016-06-08 08:29:13 +0000119 def do_SEND_ERROR(self):
120 self.send_error(int(self.path[1:]))
121
122 def do_HEAD(self):
123 self.send_error(int(self.path[1:]))
124
Georg Brandlb533e262008-05-25 18:19:30 +0000125 def setUp(self):
126 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100127 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000128 self.con.connect()
129
130 def test_command(self):
131 self.con.request('GET', '/')
132 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200133 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000134
135 def test_request_line_trimming(self):
136 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400137 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000138 self.con.endheaders()
139 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200140 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000141
142 def test_version_bogus(self):
143 self.con._http_vsn_str = 'FUBAR'
144 self.con.putrequest('GET', '/')
145 self.con.endheaders()
146 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200147 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000148
149 def test_version_digits(self):
150 self.con._http_vsn_str = 'HTTP/9.9.9'
151 self.con.putrequest('GET', '/')
152 self.con.endheaders()
153 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200154 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000155
156 def test_version_none_get(self):
157 self.con._http_vsn_str = ''
158 self.con.putrequest('GET', '/')
159 self.con.endheaders()
160 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200161 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000162
163 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400164 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000165 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400166 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000167 self.con.endheaders()
168 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200169 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000170
171 def test_version_invalid(self):
172 self.con._http_vsn = 99
173 self.con._http_vsn_str = 'HTTP/9.9'
174 self.con.putrequest('GET', '/')
175 self.con.endheaders()
176 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200177 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000178
179 def test_send_blank(self):
180 self.con._http_vsn_str = ''
181 self.con.putrequest('', '')
182 self.con.endheaders()
183 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200184 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000185
186 def test_header_close(self):
187 self.con.putrequest('GET', '/')
188 self.con.putheader('Connection', 'close')
189 self.con.endheaders()
190 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200191 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000192
Berker Peksag20853612016-08-25 01:13:34 +0300193 def test_header_keep_alive(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000194 self.con._http_vsn_str = 'HTTP/1.1'
195 self.con.putrequest('GET', '/')
196 self.con.putheader('Connection', 'keep-alive')
197 self.con.endheaders()
198 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200199 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000200
201 def test_handler(self):
202 self.con.request('TEST', '/')
203 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200204 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000205
206 def test_return_header_keep_alive(self):
207 self.con.request('KEEP', '/')
208 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000209 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000210 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000211 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000212
213 def test_internal_key_error(self):
214 self.con.request('KEYERROR', '/')
215 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000216 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000217
218 def test_return_custom_status(self):
219 self.con.request('CUSTOM', '/')
220 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000221 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000222
Senthil Kumaran26886442013-03-15 07:53:21 -0700223 def test_return_explain_error(self):
224 self.con.request('EXPLAINERROR', '/')
225 res = self.con.getresponse()
226 self.assertEqual(res.status, 999)
227 self.assertTrue(int(res.getheader('Content-Length')))
228
Armin Ronacher8d96d772011-01-22 13:13:05 +0000229 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000230 self.con.request('LATINONEHEADER', '/', headers={
231 'X-Special-Incoming': 'Ärger mit Unicode'
232 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000233 res = self.con.getresponse()
234 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000235 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000236
Senthil Kumaran52d27202012-10-10 23:16:21 -0700237 def test_error_content_length(self):
238 # Issue #16088: standard error responses should have a content-length
239 self.con.request('NOTFOUND', '/')
240 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200241 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
242
Senthil Kumaran52d27202012-10-10 23:16:21 -0700243 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700244 self.assertEqual(int(res.getheader('Content-Length')), len(data))
245
Martin Pantere42e1292016-06-08 08:29:13 +0000246 def test_send_error(self):
247 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
248 HTTPStatus.RESET_CONTENT)
249 for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
250 HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
251 HTTPStatus.SWITCHING_PROTOCOLS):
252 self.con.request('SEND_ERROR', '/{}'.format(code))
253 res = self.con.getresponse()
254 self.assertEqual(code, res.status)
255 self.assertEqual(None, res.getheader('Content-Length'))
256 self.assertEqual(None, res.getheader('Content-Type'))
257 if code not in allow_transfer_encoding_codes:
258 self.assertEqual(None, res.getheader('Transfer-Encoding'))
259
260 data = res.read()
261 self.assertEqual(b'', data)
262
263 def test_head_via_send_error(self):
264 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
265 HTTPStatus.RESET_CONTENT)
266 for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
267 HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
268 HTTPStatus.SWITCHING_PROTOCOLS):
269 self.con.request('HEAD', '/{}'.format(code))
270 res = self.con.getresponse()
271 self.assertEqual(code, res.status)
272 if code == HTTPStatus.OK:
273 self.assertTrue(int(res.getheader('Content-Length')) > 0)
274 self.assertIn('text/html', res.getheader('Content-Type'))
275 else:
276 self.assertEqual(None, res.getheader('Content-Length'))
277 self.assertEqual(None, res.getheader('Content-Type'))
278 if code not in allow_transfer_encoding_codes:
279 self.assertEqual(None, res.getheader('Transfer-Encoding'))
280
281 data = res.read()
282 self.assertEqual(b'', data)
283
Georg Brandlb533e262008-05-25 18:19:30 +0000284
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200285class RequestHandlerLoggingTestCase(BaseTestCase):
286 class request_handler(BaseHTTPRequestHandler):
287 protocol_version = 'HTTP/1.1'
288 default_request_version = 'HTTP/1.1'
289
290 def do_GET(self):
291 self.send_response(HTTPStatus.OK)
292 self.end_headers()
293
294 def do_ERROR(self):
295 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
296
297 def test_get(self):
298 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
299 self.con.connect()
300
301 with support.captured_stderr() as err:
302 self.con.request('GET', '/')
303 self.con.getresponse()
304
305 self.assertTrue(
306 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
307
308 def test_err(self):
309 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
310 self.con.connect()
311
312 with support.captured_stderr() as err:
313 self.con.request('ERROR', '/')
314 self.con.getresponse()
315
316 lines = err.getvalue().split('\n')
317 self.assertTrue(lines[0].endswith('code 404, message File not found'))
318 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
319
320
Georg Brandlb533e262008-05-25 18:19:30 +0000321class SimpleHTTPServerTestCase(BaseTestCase):
322 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
323 pass
324
325 def setUp(self):
326 BaseTestCase.setUp(self)
327 self.cwd = os.getcwd()
328 basetempdir = tempfile.gettempdir()
329 os.chdir(basetempdir)
330 self.data = b'We are the knights who say Ni!'
331 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
332 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panterfc475a92016-04-09 04:56:10 +0000333 self.base_url = '/' + self.tempdir_name
Brett Cannon105df5d2010-10-29 23:43:42 +0000334 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
335 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000336
337 def tearDown(self):
338 try:
339 os.chdir(self.cwd)
340 try:
341 shutil.rmtree(self.tempdir)
342 except:
343 pass
344 finally:
345 BaseTestCase.tearDown(self)
346
347 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300348 def close_conn():
349 """Don't close reader yet so we can check if there was leftover
350 buffered input"""
351 nonlocal reader
352 reader = response.fp
353 response.fp = None
354 reader = None
355 response._close_conn = close_conn
356
Georg Brandlb533e262008-05-25 18:19:30 +0000357 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000358 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000359 self.assertEqual(response.status, status)
360 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000361 if data:
362 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300363 # Ensure the server has not set up a persistent connection, and has
364 # not sent any extra data
365 self.assertEqual(response.version, 10)
366 self.assertEqual(response.msg.get("Connection", "close"), "close")
367 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
368
369 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300370 return body
371
Ned Deily14183202015-01-05 01:02:30 -0800372 @support.requires_mac_ver(10, 5)
Steve Dowere58571b2016-09-08 11:11:13 -0700373 @unittest.skipIf(sys.platform == 'win32',
374 'undecodable name cannot be decoded on win32')
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300375 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
376 'need support.TESTFN_UNDECODABLE')
377 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300378 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300379 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
380 with open(os.path.join(self.tempdir, filename), 'wb') as f:
381 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000382 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300383 if sys.platform == 'darwin':
384 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
385 # UTF-8 into a percent-encoded value.
386 for name in os.listdir(self.tempdir):
387 if name != 'test': # Ignore a filename created in setUp().
388 filename = name
389 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200390 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300391 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
392 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300393 .encode(enc, 'surrogateescape'), body)
Martin Panterda3bb382016-04-11 00:40:08 +0000394 self.assertIn(('>%s<' % html.escape(filename, quote=False))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300395 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000396 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200397 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300398 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000399
400 def test_get(self):
401 #constructs the path relative to the root directory of the HTTPServer
Martin Panterfc475a92016-04-09 04:56:10 +0000402 response = self.request(self.base_url + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200403 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700404 # check for trailing "/" which should return 404. See Issue17324
Martin Panterfc475a92016-04-09 04:56:10 +0000405 response = self.request(self.base_url + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200406 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Martin Panterfc475a92016-04-09 04:56:10 +0000407 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200408 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000409 response = self.request(self.base_url)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200410 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000411 response = self.request(self.base_url + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200412 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000413 response = self.request(self.base_url + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200414 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600415 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000416 self.base_url + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000417 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200418 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000419 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200420 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300421
422 data = b"Dummy index file\r\n"
423 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
424 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000425 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300426 self.check_status_and_reason(response, HTTPStatus.OK, data)
427
428 # chmod() doesn't work as expected on Windows, and filesystem
429 # permissions are ignored by root on Unix.
430 if os.name == 'posix' and os.geteuid() != 0:
431 os.chmod(self.tempdir, 0)
432 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000433 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200434 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300435 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000436 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000437
438 def test_head(self):
439 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000440 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200441 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000442 self.assertEqual(response.getheader('content-length'),
443 str(len(self.data)))
444 self.assertEqual(response.getheader('content-type'),
445 'application/octet-stream')
446
447 def test_invalid_requests(self):
448 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200449 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000450 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400451 response = self.request('/', method='custom')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200452 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000453 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200454 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000455
Martin Panterfc475a92016-04-09 04:56:10 +0000456 def test_path_without_leading_slash(self):
457 response = self.request(self.tempdir_name + '/test')
458 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
459 response = self.request(self.tempdir_name + '/test/')
460 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
461 response = self.request(self.tempdir_name + '/')
462 self.check_status_and_reason(response, HTTPStatus.OK)
463 response = self.request(self.tempdir_name)
464 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
465 response = self.request(self.tempdir_name + '/?hi=2')
466 self.check_status_and_reason(response, HTTPStatus.OK)
467 response = self.request(self.tempdir_name + '?hi=1')
468 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
469 self.assertEqual(response.getheader("Location"),
470 self.tempdir_name + "/?hi=1")
471
Martin Panterda3bb382016-04-11 00:40:08 +0000472 def test_html_escape_filename(self):
473 filename = '<test&>.txt'
474 fullpath = os.path.join(self.tempdir, filename)
475
476 try:
477 open(fullpath, 'w').close()
478 except OSError:
479 raise unittest.SkipTest('Can not create file %s on current file '
480 'system' % filename)
481
482 try:
483 response = self.request(self.base_url + '/')
484 body = self.check_status_and_reason(response, HTTPStatus.OK)
485 enc = response.headers.get_content_charset()
486 finally:
487 os.unlink(fullpath) # avoid affecting test_undecodable_filename
488
489 self.assertIsNotNone(enc)
490 html_text = '>%s<' % html.escape(filename, quote=False)
491 self.assertIn(html_text.encode(enc), body)
492
Georg Brandlb533e262008-05-25 18:19:30 +0000493
494cgi_file1 = """\
495#!%s
496
497print("Content-type: text/html")
498print()
499print("Hello World")
500"""
501
502cgi_file2 = """\
503#!%s
504import cgi
505
506print("Content-type: text/html")
507print()
508
509form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000510print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
511 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000512"""
513
Martin Pantera02e18a2015-10-03 05:38:07 +0000514cgi_file4 = """\
515#!%s
516import os
517
518print("Content-type: text/html")
519print()
520
521print(os.environ["%s"])
522"""
523
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100524
525@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
526 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000527class CGIHTTPServerTestCase(BaseTestCase):
528 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
529 pass
530
Antoine Pitroue768c392012-08-05 14:52:45 +0200531 linesep = os.linesep.encode('ascii')
532
Georg Brandlb533e262008-05-25 18:19:30 +0000533 def setUp(self):
534 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000535 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000536 self.parent_dir = tempfile.mkdtemp()
537 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700538 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000539 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700540 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400541 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000542 self.file1_path = None
543 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700544 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000545 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000546
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000547 # The shebang line should be pure ASCII: use symlink if possible.
548 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000549 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000550 self.pythonexe = os.path.join(self.parent_dir, 'python')
551 os.symlink(sys.executable, self.pythonexe)
552 else:
553 self.pythonexe = sys.executable
554
Victor Stinner3218c312010-10-17 20:13:36 +0000555 try:
556 # The python executable path is written as the first line of the
557 # CGI Python script. The encoding cookie cannot be used, and so the
558 # path should be encodable to the default script encoding (utf-8)
559 self.pythonexe.encode('utf-8')
560 except UnicodeEncodeError:
561 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200562 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000563
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400564 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
565 with open(self.nocgi_path, 'w') as fp:
566 fp.write(cgi_file1 % self.pythonexe)
567 os.chmod(self.nocgi_path, 0o777)
568
Georg Brandlb533e262008-05-25 18:19:30 +0000569 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000570 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000571 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000572 os.chmod(self.file1_path, 0o777)
573
574 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000575 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000576 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000577 os.chmod(self.file2_path, 0o777)
578
Ned Deily915a30f2014-07-12 22:06:26 -0700579 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
580 with open(self.file3_path, 'w', encoding='utf-8') as file3:
581 file3.write(cgi_file1 % self.pythonexe)
582 os.chmod(self.file3_path, 0o777)
583
Martin Pantera02e18a2015-10-03 05:38:07 +0000584 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
585 with open(self.file4_path, 'w', encoding='utf-8') as file4:
586 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
587 os.chmod(self.file4_path, 0o777)
588
Georg Brandlb533e262008-05-25 18:19:30 +0000589 os.chdir(self.parent_dir)
590
591 def tearDown(self):
592 try:
593 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000594 if self.pythonexe != sys.executable:
595 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400596 if self.nocgi_path:
597 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000598 if self.file1_path:
599 os.remove(self.file1_path)
600 if self.file2_path:
601 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700602 if self.file3_path:
603 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000604 if self.file4_path:
605 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700606 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000607 os.rmdir(self.cgi_dir)
608 os.rmdir(self.parent_dir)
609 finally:
610 BaseTestCase.tearDown(self)
611
Senthil Kumarand70846b2012-04-12 02:34:32 +0800612 def test_url_collapse_path(self):
613 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000614 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800615 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000616 '..': IndexError,
617 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800618 '/': '//',
619 '//': '//',
620 '/\\': '//\\',
621 '/.//': '//',
622 'cgi-bin/file1.py': '/cgi-bin/file1.py',
623 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
624 'a': '//a',
625 '/a': '//a',
626 '//a': '//a',
627 './a': '//a',
628 './C:/': '/C:/',
629 '/a/b': '/a/b',
630 '/a/b/': '/a/b/',
631 '/a/b/.': '/a/b/',
632 '/a/b/c/..': '/a/b/',
633 '/a/b/c/../d': '/a/b/d',
634 '/a/b/c/../d/e/../f': '/a/b/d/f',
635 '/a/b/c/../d/e/../../f': '/a/b/f',
636 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000637 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800638 '/a/b/c/../d/e/../../../f': '/a/f',
639 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000640 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800641 '/a/b/c/../d/e/../../../../f/..': '//',
642 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000643 }
644 for path, expected in test_vectors.items():
645 if isinstance(expected, type) and issubclass(expected, Exception):
646 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800647 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000648 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800649 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000650 self.assertEqual(expected, actual,
651 msg='path = %r\nGot: %r\nWanted: %r' %
652 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000653
Georg Brandlb533e262008-05-25 18:19:30 +0000654 def test_headers_and_content(self):
655 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200656 self.assertEqual(
657 (res.read(), res.getheader('Content-type'), res.status),
658 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000659
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400660 def test_issue19435(self):
661 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200662 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400663
Georg Brandlb533e262008-05-25 18:19:30 +0000664 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000665 params = urllib.parse.urlencode(
666 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000667 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
668 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
669
Antoine Pitroue768c392012-08-05 14:52:45 +0200670 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000671
672 def test_invaliduri(self):
673 res = self.request('/cgi-bin/invalid')
674 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200675 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000676
677 def test_authorization(self):
678 headers = {b'Authorization' : b'Basic ' +
679 base64.b64encode(b'username:pass')}
680 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200681 self.assertEqual(
682 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
683 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000684
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000685 def test_no_leading_slash(self):
686 # http://bugs.python.org/issue2254
687 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200688 self.assertEqual(
689 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
690 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000691
Senthil Kumaran42713722010-10-03 17:55:45 +0000692 def test_os_environ_is_not_altered(self):
693 signature = "Test CGI Server"
694 os.environ['SERVER_SOFTWARE'] = signature
695 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200696 self.assertEqual(
697 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
698 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000699 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
700
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700701 def test_urlquote_decoding_in_cgi_check(self):
702 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200703 self.assertEqual(
704 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
705 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700706
Ned Deily915a30f2014-07-12 22:06:26 -0700707 def test_nested_cgi_path_issue21323(self):
708 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200709 self.assertEqual(
710 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
711 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700712
Martin Pantera02e18a2015-10-03 05:38:07 +0000713 def test_query_with_multiple_question_mark(self):
714 res = self.request('/cgi-bin/file4.py?a=b?c=d')
715 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000716 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000717 (res.read(), res.getheader('Content-type'), res.status))
718
Martin Pantercb29e8c2015-10-03 05:55:46 +0000719 def test_query_with_continuous_slashes(self):
720 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
721 self.assertEqual(
722 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000723 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000724 (res.read(), res.getheader('Content-type'), res.status))
725
Georg Brandlb533e262008-05-25 18:19:30 +0000726
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000727class SocketlessRequestHandler(SimpleHTTPRequestHandler):
728 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000729 self.get_called = False
730 self.protocol_version = "HTTP/1.1"
731
732 def do_GET(self):
733 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200734 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000735 self.send_header('Content-Type', 'text/html')
736 self.end_headers()
737 self.wfile.write(b'<html><body>Data</body></html>\r\n')
738
739 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000740 pass
741
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000742class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
743 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200744 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000745 return False
746
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800747
748class AuditableBytesIO:
749
750 def __init__(self):
751 self.datas = []
752
753 def write(self, data):
754 self.datas.append(data)
755
756 def getData(self):
757 return b''.join(self.datas)
758
759 @property
760 def numWrites(self):
761 return len(self.datas)
762
763
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000764class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200765 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000766
767 Test the support for the Expect 100-continue header.
768 """
769
770 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
771
772 def setUp (self):
773 self.handler = SocketlessRequestHandler()
774
775 def send_typical_request(self, message):
776 input = BytesIO(message)
777 output = BytesIO()
778 self.handler.rfile = input
779 self.handler.wfile = output
780 self.handler.handle_one_request()
781 output.seek(0)
782 return output.readlines()
783
784 def verify_get_called(self):
785 self.assertTrue(self.handler.get_called)
786
787 def verify_expected_headers(self, headers):
788 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
789 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
790
791 def verify_http_server_response(self, response):
792 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200793 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000794
795 def test_http_1_1(self):
796 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
797 self.verify_http_server_response(result[0])
798 self.verify_expected_headers(result[1:-1])
799 self.verify_get_called()
800 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500801 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
802 self.assertEqual(self.handler.command, 'GET')
803 self.assertEqual(self.handler.path, '/')
804 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
805 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000806
807 def test_http_1_0(self):
808 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
809 self.verify_http_server_response(result[0])
810 self.verify_expected_headers(result[1:-1])
811 self.verify_get_called()
812 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500813 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
814 self.assertEqual(self.handler.command, 'GET')
815 self.assertEqual(self.handler.path, '/')
816 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
817 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000818
819 def test_http_0_9(self):
820 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
821 self.assertEqual(len(result), 1)
822 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
823 self.verify_get_called()
824
Martin Pantere82338d2016-11-19 01:06:37 +0000825 def test_extra_space(self):
826 result = self.send_typical_request(
827 b'GET /spaced out HTTP/1.1\r\n'
828 b'Host: dummy\r\n'
829 b'\r\n'
830 )
831 self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
832 self.verify_expected_headers(result[1:result.index(b'\r\n')])
833 self.assertFalse(self.handler.get_called)
834
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000835 def test_with_continue_1_0(self):
836 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
837 self.verify_http_server_response(result[0])
838 self.verify_expected_headers(result[1:-1])
839 self.verify_get_called()
840 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500841 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
842 self.assertEqual(self.handler.command, 'GET')
843 self.assertEqual(self.handler.path, '/')
844 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
845 headers = (("Expect", "100-continue"),)
846 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000847
848 def test_with_continue_1_1(self):
849 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
850 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500851 self.assertEqual(result[1], b'\r\n')
852 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000853 self.verify_expected_headers(result[2:-1])
854 self.verify_get_called()
855 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500856 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
857 self.assertEqual(self.handler.command, 'GET')
858 self.assertEqual(self.handler.path, '/')
859 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
860 headers = (("Expect", "100-continue"),)
861 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000862
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800863 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000864
865 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800866 output = AuditableBytesIO()
867 handler = SocketlessRequestHandler()
868 handler.rfile = input
869 handler.wfile = output
870 handler.request_version = 'HTTP/1.1'
871 handler.requestline = ''
872 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000873
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800874 handler.send_error(418)
875 self.assertEqual(output.numWrites, 2)
876
877 def test_header_buffering_of_send_response_only(self):
878
879 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
880 output = AuditableBytesIO()
881 handler = SocketlessRequestHandler()
882 handler.rfile = input
883 handler.wfile = output
884 handler.request_version = 'HTTP/1.1'
885
886 handler.send_response_only(418)
887 self.assertEqual(output.numWrites, 0)
888 handler.end_headers()
889 self.assertEqual(output.numWrites, 1)
890
891 def test_header_buffering_of_send_header(self):
892
893 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
894 output = AuditableBytesIO()
895 handler = SocketlessRequestHandler()
896 handler.rfile = input
897 handler.wfile = output
898 handler.request_version = 'HTTP/1.1'
899
900 handler.send_header('Foo', 'foo')
901 handler.send_header('bar', 'bar')
902 self.assertEqual(output.numWrites, 0)
903 handler.end_headers()
904 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
905 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000906
907 def test_header_unbuffered_when_continue(self):
908
909 def _readAndReseek(f):
910 pos = f.tell()
911 f.seek(0)
912 data = f.read()
913 f.seek(pos)
914 return data
915
916 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
917 output = BytesIO()
918 self.handler.rfile = input
919 self.handler.wfile = output
920 self.handler.request_version = 'HTTP/1.1'
921
922 self.handler.handle_one_request()
923 self.assertNotEqual(_readAndReseek(output), b'')
924 result = _readAndReseek(output).split(b'\r\n')
925 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500926 self.assertEqual(result[1], b'')
927 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000928
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000929 def test_with_continue_rejected(self):
930 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
931 self.handler = RejectingSocketlessRequestHandler()
932 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
933 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
934 self.verify_expected_headers(result[1:-1])
935 # The expect handler should short circuit the usual get method by
936 # returning false here, so get_called should be false
937 self.assertFalse(self.handler.get_called)
938 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
939 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
940
Antoine Pitrouc4924372010-12-16 16:48:36 +0000941 def test_request_length(self):
942 # Issue #10714: huge request lines are discarded, to avoid Denial
943 # of Service attacks.
944 result = self.send_typical_request(b'GET ' + b'x' * 65537)
945 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
946 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500947 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000948
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000949 def test_header_length(self):
950 # Issue #6791: same for headers
951 result = self.send_typical_request(
952 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +0000953 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000954 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500955 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
956
Martin Panteracc03192016-04-03 00:45:46 +0000957 def test_too_many_headers(self):
958 result = self.send_typical_request(
959 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
960 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
961 self.assertFalse(self.handler.get_called)
962 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
963
Martin Panterda3bb382016-04-11 00:40:08 +0000964 def test_html_escape_on_error(self):
965 result = self.send_typical_request(
966 b'<script>alert("hello")</script> / HTTP/1.1')
967 result = b''.join(result)
968 text = '<script>alert("hello")</script>'
969 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
970
Benjamin Peterson70e28472015-02-17 21:11:10 -0500971 def test_close_connection(self):
972 # handle_one_request() should be repeatedly called until
973 # it sets close_connection
974 def handle_one_request():
975 self.handler.close_connection = next(close_values)
976 self.handler.handle_one_request = handle_one_request
977
978 close_values = iter((True,))
979 self.handler.handle()
980 self.assertRaises(StopIteration, next, close_values)
981
982 close_values = iter((False, False, True))
983 self.handler.handle()
984 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000985
Berker Peksag04bc5b92016-03-14 06:06:03 +0200986 def test_date_time_string(self):
987 now = time.time()
988 # this is the old code that formats the timestamp
989 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
990 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
991 self.handler.weekdayname[wd],
992 day,
993 self.handler.monthname[month],
994 year, hh, mm, ss
995 )
996 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
997
998
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000999class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
1000 """ Test url parsing """
1001 def setUp(self):
1002 self.translated = os.getcwd()
1003 self.translated = os.path.join(self.translated, 'filename')
1004 self.handler = SocketlessRequestHandler()
1005
1006 def test_query_arguments(self):
1007 path = self.handler.translate_path('/filename')
1008 self.assertEqual(path, self.translated)
1009 path = self.handler.translate_path('/filename?foo=bar')
1010 self.assertEqual(path, self.translated)
1011 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
1012 self.assertEqual(path, self.translated)
1013
1014 def test_start_with_double_slash(self):
1015 path = self.handler.translate_path('//filename')
1016 self.assertEqual(path, self.translated)
1017 path = self.handler.translate_path('//filename?foo=bar')
1018 self.assertEqual(path, self.translated)
1019
Martin Panterd274b3f2016-04-18 03:45:18 +00001020 def test_windows_colon(self):
1021 with support.swap_attr(server.os, 'path', ntpath):
1022 path = self.handler.translate_path('c:c:c:foo/filename')
1023 path = path.replace(ntpath.sep, os.sep)
1024 self.assertEqual(path, self.translated)
1025
1026 path = self.handler.translate_path('\\c:../filename')
1027 path = path.replace(ntpath.sep, os.sep)
1028 self.assertEqual(path, self.translated)
1029
1030 path = self.handler.translate_path('c:\\c:..\\foo/filename')
1031 path = path.replace(ntpath.sep, os.sep)
1032 self.assertEqual(path, self.translated)
1033
1034 path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
1035 path = path.replace(ntpath.sep, os.sep)
1036 self.assertEqual(path, self.translated)
1037
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001038
Berker Peksag366c5702015-02-13 20:48:15 +02001039class MiscTestCase(unittest.TestCase):
1040 def test_all(self):
1041 expected = []
1042 blacklist = {'executable', 'nobody_uid', 'test'}
1043 for name in dir(server):
1044 if name.startswith('_') or name in blacklist:
1045 continue
1046 module_object = getattr(server, name)
1047 if getattr(module_object, '__module__', None) == 'http.server':
1048 expected.append(name)
1049 self.assertCountEqual(server.__all__, expected)
1050
1051
Georg Brandlb533e262008-05-25 18:19:30 +00001052def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001053 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001054 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001055 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001056 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001057 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001058 BaseHTTPServerTestCase,
1059 SimpleHTTPServerTestCase,
1060 CGIHTTPServerTestCase,
1061 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001062 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001063 )
Georg Brandlb533e262008-05-25 18:19:30 +00001064 finally:
1065 os.chdir(cwd)
1066
1067if __name__ == '__main__':
1068 test_main()