blob: 75044cbafa47b2918e791b2a3ef249d6c44e58e1 [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)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300373 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
374 'need support.TESTFN_UNDECODABLE')
375 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300376 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300377 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
378 with open(os.path.join(self.tempdir, filename), 'wb') as f:
379 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000380 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300381 if sys.platform == 'darwin':
382 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
383 # UTF-8 into a percent-encoded value.
384 for name in os.listdir(self.tempdir):
385 if name != 'test': # Ignore a filename created in setUp().
386 filename = name
387 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200388 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300389 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
390 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300391 .encode(enc, 'surrogateescape'), body)
Martin Panterda3bb382016-04-11 00:40:08 +0000392 self.assertIn(('>%s<' % html.escape(filename, quote=False))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300393 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000394 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200395 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300396 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000397
398 def test_get(self):
399 #constructs the path relative to the root directory of the HTTPServer
Martin Panterfc475a92016-04-09 04:56:10 +0000400 response = self.request(self.base_url + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200401 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700402 # check for trailing "/" which should return 404. See Issue17324
Martin Panterfc475a92016-04-09 04:56:10 +0000403 response = self.request(self.base_url + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200404 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Martin Panterfc475a92016-04-09 04:56:10 +0000405 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200406 self.check_status_and_reason(response, HTTPStatus.OK)
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.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000409 response = self.request(self.base_url + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200410 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000411 response = self.request(self.base_url + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200412 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600413 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000414 self.base_url + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000415 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200416 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
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)
Berker Peksagb5754322015-07-22 19:25:37 +0300419
420 data = b"Dummy index file\r\n"
421 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
422 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000423 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300424 self.check_status_and_reason(response, HTTPStatus.OK, data)
425
426 # chmod() doesn't work as expected on Windows, and filesystem
427 # permissions are ignored by root on Unix.
428 if os.name == 'posix' and os.geteuid() != 0:
429 os.chmod(self.tempdir, 0)
430 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000431 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200432 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300433 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000434 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000435
436 def test_head(self):
437 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000438 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200439 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000440 self.assertEqual(response.getheader('content-length'),
441 str(len(self.data)))
442 self.assertEqual(response.getheader('content-type'),
443 'application/octet-stream')
444
445 def test_invalid_requests(self):
446 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200447 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000448 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400449 response = self.request('/', method='custom')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200450 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000451 response = self.request('/', method='GETs')
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
Martin Panterfc475a92016-04-09 04:56:10 +0000454 def test_path_without_leading_slash(self):
455 response = self.request(self.tempdir_name + '/test')
456 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
457 response = self.request(self.tempdir_name + '/test/')
458 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
459 response = self.request(self.tempdir_name + '/')
460 self.check_status_and_reason(response, HTTPStatus.OK)
461 response = self.request(self.tempdir_name)
462 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
463 response = self.request(self.tempdir_name + '/?hi=2')
464 self.check_status_and_reason(response, HTTPStatus.OK)
465 response = self.request(self.tempdir_name + '?hi=1')
466 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
467 self.assertEqual(response.getheader("Location"),
468 self.tempdir_name + "/?hi=1")
469
Martin Panterda3bb382016-04-11 00:40:08 +0000470 def test_html_escape_filename(self):
471 filename = '<test&>.txt'
472 fullpath = os.path.join(self.tempdir, filename)
473
474 try:
475 open(fullpath, 'w').close()
476 except OSError:
477 raise unittest.SkipTest('Can not create file %s on current file '
478 'system' % filename)
479
480 try:
481 response = self.request(self.base_url + '/')
482 body = self.check_status_and_reason(response, HTTPStatus.OK)
483 enc = response.headers.get_content_charset()
484 finally:
485 os.unlink(fullpath) # avoid affecting test_undecodable_filename
486
487 self.assertIsNotNone(enc)
488 html_text = '>%s<' % html.escape(filename, quote=False)
489 self.assertIn(html_text.encode(enc), body)
490
Georg Brandlb533e262008-05-25 18:19:30 +0000491
492cgi_file1 = """\
493#!%s
494
495print("Content-type: text/html")
496print()
497print("Hello World")
498"""
499
500cgi_file2 = """\
501#!%s
502import cgi
503
504print("Content-type: text/html")
505print()
506
507form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000508print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
509 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000510"""
511
Martin Pantera02e18a2015-10-03 05:38:07 +0000512cgi_file4 = """\
513#!%s
514import os
515
516print("Content-type: text/html")
517print()
518
519print(os.environ["%s"])
520"""
521
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100522
523@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
524 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000525class CGIHTTPServerTestCase(BaseTestCase):
526 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
527 pass
528
Antoine Pitroue768c392012-08-05 14:52:45 +0200529 linesep = os.linesep.encode('ascii')
530
Georg Brandlb533e262008-05-25 18:19:30 +0000531 def setUp(self):
532 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000533 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000534 self.parent_dir = tempfile.mkdtemp()
535 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700536 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000537 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700538 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400539 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000540 self.file1_path = None
541 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700542 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000543 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000544
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000545 # The shebang line should be pure ASCII: use symlink if possible.
546 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000547 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000548 self.pythonexe = os.path.join(self.parent_dir, 'python')
549 os.symlink(sys.executable, self.pythonexe)
550 else:
551 self.pythonexe = sys.executable
552
Victor Stinner3218c312010-10-17 20:13:36 +0000553 try:
554 # The python executable path is written as the first line of the
555 # CGI Python script. The encoding cookie cannot be used, and so the
556 # path should be encodable to the default script encoding (utf-8)
557 self.pythonexe.encode('utf-8')
558 except UnicodeEncodeError:
559 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200560 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000561
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400562 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
563 with open(self.nocgi_path, 'w') as fp:
564 fp.write(cgi_file1 % self.pythonexe)
565 os.chmod(self.nocgi_path, 0o777)
566
Georg Brandlb533e262008-05-25 18:19:30 +0000567 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000568 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000569 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000570 os.chmod(self.file1_path, 0o777)
571
572 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000573 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000574 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000575 os.chmod(self.file2_path, 0o777)
576
Ned Deily915a30f2014-07-12 22:06:26 -0700577 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
578 with open(self.file3_path, 'w', encoding='utf-8') as file3:
579 file3.write(cgi_file1 % self.pythonexe)
580 os.chmod(self.file3_path, 0o777)
581
Martin Pantera02e18a2015-10-03 05:38:07 +0000582 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
583 with open(self.file4_path, 'w', encoding='utf-8') as file4:
584 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
585 os.chmod(self.file4_path, 0o777)
586
Georg Brandlb533e262008-05-25 18:19:30 +0000587 os.chdir(self.parent_dir)
588
589 def tearDown(self):
590 try:
591 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000592 if self.pythonexe != sys.executable:
593 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400594 if self.nocgi_path:
595 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000596 if self.file1_path:
597 os.remove(self.file1_path)
598 if self.file2_path:
599 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700600 if self.file3_path:
601 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000602 if self.file4_path:
603 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700604 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000605 os.rmdir(self.cgi_dir)
606 os.rmdir(self.parent_dir)
607 finally:
608 BaseTestCase.tearDown(self)
609
Senthil Kumarand70846b2012-04-12 02:34:32 +0800610 def test_url_collapse_path(self):
611 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000612 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800613 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000614 '..': IndexError,
615 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800616 '/': '//',
617 '//': '//',
618 '/\\': '//\\',
619 '/.//': '//',
620 'cgi-bin/file1.py': '/cgi-bin/file1.py',
621 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
622 'a': '//a',
623 '/a': '//a',
624 '//a': '//a',
625 './a': '//a',
626 './C:/': '/C:/',
627 '/a/b': '/a/b',
628 '/a/b/': '/a/b/',
629 '/a/b/.': '/a/b/',
630 '/a/b/c/..': '/a/b/',
631 '/a/b/c/../d': '/a/b/d',
632 '/a/b/c/../d/e/../f': '/a/b/d/f',
633 '/a/b/c/../d/e/../../f': '/a/b/f',
634 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000635 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800636 '/a/b/c/../d/e/../../../f': '/a/f',
637 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000638 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800639 '/a/b/c/../d/e/../../../../f/..': '//',
640 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000641 }
642 for path, expected in test_vectors.items():
643 if isinstance(expected, type) and issubclass(expected, Exception):
644 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800645 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000646 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800647 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000648 self.assertEqual(expected, actual,
649 msg='path = %r\nGot: %r\nWanted: %r' %
650 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000651
Georg Brandlb533e262008-05-25 18:19:30 +0000652 def test_headers_and_content(self):
653 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200654 self.assertEqual(
655 (res.read(), res.getheader('Content-type'), res.status),
656 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000657
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400658 def test_issue19435(self):
659 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200660 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400661
Georg Brandlb533e262008-05-25 18:19:30 +0000662 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000663 params = urllib.parse.urlencode(
664 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000665 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
666 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
667
Antoine Pitroue768c392012-08-05 14:52:45 +0200668 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000669
670 def test_invaliduri(self):
671 res = self.request('/cgi-bin/invalid')
672 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200673 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000674
675 def test_authorization(self):
676 headers = {b'Authorization' : b'Basic ' +
677 base64.b64encode(b'username:pass')}
678 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200679 self.assertEqual(
680 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
681 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000682
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000683 def test_no_leading_slash(self):
684 # http://bugs.python.org/issue2254
685 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200686 self.assertEqual(
687 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
688 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000689
Senthil Kumaran42713722010-10-03 17:55:45 +0000690 def test_os_environ_is_not_altered(self):
691 signature = "Test CGI Server"
692 os.environ['SERVER_SOFTWARE'] = signature
693 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200694 self.assertEqual(
695 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
696 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000697 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
698
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700699 def test_urlquote_decoding_in_cgi_check(self):
700 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200701 self.assertEqual(
702 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
703 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700704
Ned Deily915a30f2014-07-12 22:06:26 -0700705 def test_nested_cgi_path_issue21323(self):
706 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200707 self.assertEqual(
708 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
709 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700710
Martin Pantera02e18a2015-10-03 05:38:07 +0000711 def test_query_with_multiple_question_mark(self):
712 res = self.request('/cgi-bin/file4.py?a=b?c=d')
713 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000714 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000715 (res.read(), res.getheader('Content-type'), res.status))
716
Martin Pantercb29e8c2015-10-03 05:55:46 +0000717 def test_query_with_continuous_slashes(self):
718 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
719 self.assertEqual(
720 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000721 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000722 (res.read(), res.getheader('Content-type'), res.status))
723
Georg Brandlb533e262008-05-25 18:19:30 +0000724
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000725class SocketlessRequestHandler(SimpleHTTPRequestHandler):
726 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000727 self.get_called = False
728 self.protocol_version = "HTTP/1.1"
729
730 def do_GET(self):
731 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200732 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000733 self.send_header('Content-Type', 'text/html')
734 self.end_headers()
735 self.wfile.write(b'<html><body>Data</body></html>\r\n')
736
737 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000738 pass
739
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000740class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
741 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200742 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000743 return False
744
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800745
746class AuditableBytesIO:
747
748 def __init__(self):
749 self.datas = []
750
751 def write(self, data):
752 self.datas.append(data)
753
754 def getData(self):
755 return b''.join(self.datas)
756
757 @property
758 def numWrites(self):
759 return len(self.datas)
760
761
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000762class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200763 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000764
765 Test the support for the Expect 100-continue header.
766 """
767
768 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
769
770 def setUp (self):
771 self.handler = SocketlessRequestHandler()
772
773 def send_typical_request(self, message):
774 input = BytesIO(message)
775 output = BytesIO()
776 self.handler.rfile = input
777 self.handler.wfile = output
778 self.handler.handle_one_request()
779 output.seek(0)
780 return output.readlines()
781
782 def verify_get_called(self):
783 self.assertTrue(self.handler.get_called)
784
785 def verify_expected_headers(self, headers):
786 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
787 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
788
789 def verify_http_server_response(self, response):
790 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200791 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000792
793 def test_http_1_1(self):
794 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
795 self.verify_http_server_response(result[0])
796 self.verify_expected_headers(result[1:-1])
797 self.verify_get_called()
798 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500799 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
800 self.assertEqual(self.handler.command, 'GET')
801 self.assertEqual(self.handler.path, '/')
802 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
803 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000804
805 def test_http_1_0(self):
806 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
807 self.verify_http_server_response(result[0])
808 self.verify_expected_headers(result[1:-1])
809 self.verify_get_called()
810 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500811 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
812 self.assertEqual(self.handler.command, 'GET')
813 self.assertEqual(self.handler.path, '/')
814 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
815 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000816
817 def test_http_0_9(self):
818 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
819 self.assertEqual(len(result), 1)
820 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
821 self.verify_get_called()
822
823 def test_with_continue_1_0(self):
824 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
825 self.verify_http_server_response(result[0])
826 self.verify_expected_headers(result[1:-1])
827 self.verify_get_called()
828 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500829 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
830 self.assertEqual(self.handler.command, 'GET')
831 self.assertEqual(self.handler.path, '/')
832 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
833 headers = (("Expect", "100-continue"),)
834 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000835
836 def test_with_continue_1_1(self):
837 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
838 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500839 self.assertEqual(result[1], b'\r\n')
840 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000841 self.verify_expected_headers(result[2:-1])
842 self.verify_get_called()
843 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500844 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
845 self.assertEqual(self.handler.command, 'GET')
846 self.assertEqual(self.handler.path, '/')
847 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
848 headers = (("Expect", "100-continue"),)
849 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000850
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800851 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000852
853 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800854 output = AuditableBytesIO()
855 handler = SocketlessRequestHandler()
856 handler.rfile = input
857 handler.wfile = output
858 handler.request_version = 'HTTP/1.1'
859 handler.requestline = ''
860 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000861
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800862 handler.send_error(418)
863 self.assertEqual(output.numWrites, 2)
864
865 def test_header_buffering_of_send_response_only(self):
866
867 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
868 output = AuditableBytesIO()
869 handler = SocketlessRequestHandler()
870 handler.rfile = input
871 handler.wfile = output
872 handler.request_version = 'HTTP/1.1'
873
874 handler.send_response_only(418)
875 self.assertEqual(output.numWrites, 0)
876 handler.end_headers()
877 self.assertEqual(output.numWrites, 1)
878
879 def test_header_buffering_of_send_header(self):
880
881 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
882 output = AuditableBytesIO()
883 handler = SocketlessRequestHandler()
884 handler.rfile = input
885 handler.wfile = output
886 handler.request_version = 'HTTP/1.1'
887
888 handler.send_header('Foo', 'foo')
889 handler.send_header('bar', 'bar')
890 self.assertEqual(output.numWrites, 0)
891 handler.end_headers()
892 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
893 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000894
895 def test_header_unbuffered_when_continue(self):
896
897 def _readAndReseek(f):
898 pos = f.tell()
899 f.seek(0)
900 data = f.read()
901 f.seek(pos)
902 return data
903
904 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
905 output = BytesIO()
906 self.handler.rfile = input
907 self.handler.wfile = output
908 self.handler.request_version = 'HTTP/1.1'
909
910 self.handler.handle_one_request()
911 self.assertNotEqual(_readAndReseek(output), b'')
912 result = _readAndReseek(output).split(b'\r\n')
913 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500914 self.assertEqual(result[1], b'')
915 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000916
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000917 def test_with_continue_rejected(self):
918 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
919 self.handler = RejectingSocketlessRequestHandler()
920 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
921 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
922 self.verify_expected_headers(result[1:-1])
923 # The expect handler should short circuit the usual get method by
924 # returning false here, so get_called should be false
925 self.assertFalse(self.handler.get_called)
926 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
927 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
928
Antoine Pitrouc4924372010-12-16 16:48:36 +0000929 def test_request_length(self):
930 # Issue #10714: huge request lines are discarded, to avoid Denial
931 # of Service attacks.
932 result = self.send_typical_request(b'GET ' + b'x' * 65537)
933 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
934 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500935 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000936
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000937 def test_header_length(self):
938 # Issue #6791: same for headers
939 result = self.send_typical_request(
940 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +0000941 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000942 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500943 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
944
Martin Panteracc03192016-04-03 00:45:46 +0000945 def test_too_many_headers(self):
946 result = self.send_typical_request(
947 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
948 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
949 self.assertFalse(self.handler.get_called)
950 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
951
Martin Panterda3bb382016-04-11 00:40:08 +0000952 def test_html_escape_on_error(self):
953 result = self.send_typical_request(
954 b'<script>alert("hello")</script> / HTTP/1.1')
955 result = b''.join(result)
956 text = '<script>alert("hello")</script>'
957 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
958
Benjamin Peterson70e28472015-02-17 21:11:10 -0500959 def test_close_connection(self):
960 # handle_one_request() should be repeatedly called until
961 # it sets close_connection
962 def handle_one_request():
963 self.handler.close_connection = next(close_values)
964 self.handler.handle_one_request = handle_one_request
965
966 close_values = iter((True,))
967 self.handler.handle()
968 self.assertRaises(StopIteration, next, close_values)
969
970 close_values = iter((False, False, True))
971 self.handler.handle()
972 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000973
Berker Peksag04bc5b92016-03-14 06:06:03 +0200974 def test_date_time_string(self):
975 now = time.time()
976 # this is the old code that formats the timestamp
977 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
978 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
979 self.handler.weekdayname[wd],
980 day,
981 self.handler.monthname[month],
982 year, hh, mm, ss
983 )
984 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
985
986
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000987class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
988 """ Test url parsing """
989 def setUp(self):
990 self.translated = os.getcwd()
991 self.translated = os.path.join(self.translated, 'filename')
992 self.handler = SocketlessRequestHandler()
993
994 def test_query_arguments(self):
995 path = self.handler.translate_path('/filename')
996 self.assertEqual(path, self.translated)
997 path = self.handler.translate_path('/filename?foo=bar')
998 self.assertEqual(path, self.translated)
999 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
1000 self.assertEqual(path, self.translated)
1001
1002 def test_start_with_double_slash(self):
1003 path = self.handler.translate_path('//filename')
1004 self.assertEqual(path, self.translated)
1005 path = self.handler.translate_path('//filename?foo=bar')
1006 self.assertEqual(path, self.translated)
1007
Martin Panterd274b3f2016-04-18 03:45:18 +00001008 def test_windows_colon(self):
1009 with support.swap_attr(server.os, 'path', ntpath):
1010 path = self.handler.translate_path('c:c:c:foo/filename')
1011 path = path.replace(ntpath.sep, os.sep)
1012 self.assertEqual(path, self.translated)
1013
1014 path = self.handler.translate_path('\\c:../filename')
1015 path = path.replace(ntpath.sep, os.sep)
1016 self.assertEqual(path, self.translated)
1017
1018 path = self.handler.translate_path('c:\\c:..\\foo/filename')
1019 path = path.replace(ntpath.sep, os.sep)
1020 self.assertEqual(path, self.translated)
1021
1022 path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
1023 path = path.replace(ntpath.sep, os.sep)
1024 self.assertEqual(path, self.translated)
1025
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001026
Berker Peksag366c5702015-02-13 20:48:15 +02001027class MiscTestCase(unittest.TestCase):
1028 def test_all(self):
1029 expected = []
1030 blacklist = {'executable', 'nobody_uid', 'test'}
1031 for name in dir(server):
1032 if name.startswith('_') or name in blacklist:
1033 continue
1034 module_object = getattr(server, name)
1035 if getattr(module_object, '__module__', None) == 'http.server':
1036 expected.append(name)
1037 self.assertCountEqual(server.__all__, expected)
1038
1039
Georg Brandlb533e262008-05-25 18:19:30 +00001040def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001041 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001042 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001043 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001044 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001045 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001046 BaseHTTPServerTestCase,
1047 SimpleHTTPServerTestCase,
1048 CGIHTTPServerTestCase,
1049 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001050 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001051 )
Georg Brandlb533e262008-05-25 18:19:30 +00001052 finally:
1053 os.chdir(cwd)
1054
1055if __name__ == '__main__':
1056 test_main()