blob: 20e6f66766f676f5750401896035d9a2b443e835 [file] [log] [blame]
Georg Brandlb533e262008-05-25 18:19:30 +00001"""Unittests for the various HTTPServer modules.
2
3Written by Cody A.W. Somerville <cody-somerville@ubuntu.com>,
4Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest.
5"""
6
Georg Brandl24420152008-05-26 16:32:26 +00007from http.server import BaseHTTPRequestHandler, HTTPServer, \
8 SimpleHTTPRequestHandler, CGIHTTPRequestHandler
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02009from http import server, HTTPStatus
Georg Brandlb533e262008-05-25 18:19:30 +000010
11import os
12import sys
Senthil Kumaran0f476d42010-09-30 06:09:18 +000013import re
Georg Brandlb533e262008-05-25 18:19:30 +000014import base64
Martin Panterd274b3f2016-04-18 03:45:18 +000015import ntpath
Georg Brandlb533e262008-05-25 18:19:30 +000016import shutil
Pierre Quentel351adda2017-04-02 12:26:12 +020017import email.message
18import email.utils
Serhiy Storchakacb5bc402014-08-17 08:22:11 +030019import html
Georg Brandl24420152008-05-26 16:32:26 +000020import http.client
Pierre Quentel351adda2017-04-02 12:26:12 +020021import urllib.parse
Georg Brandlb533e262008-05-25 18:19:30 +000022import tempfile
Berker Peksag04bc5b92016-03-14 06:06:03 +020023import time
Pierre Quentel351adda2017-04-02 12:26:12 +020024import datetime
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020025import threading
Stéphane Wirtela17a2f52017-05-24 09:29:06 +020026from unittest import mock
Senthil Kumaran0f476d42010-09-30 06:09:18 +000027from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000028
29import unittest
30from test import support
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020031
Georg Brandlb533e262008-05-25 18:19:30 +000032
Georg Brandlb533e262008-05-25 18:19:30 +000033class NoLogRequestHandler:
34 def log_message(self, *args):
35 # don't write log messages to stderr
36 pass
37
Barry Warsaw820c1202008-06-12 04:06:45 +000038 def read(self, n=None):
39 return ''
40
Georg Brandlb533e262008-05-25 18:19:30 +000041
42class TestServerThread(threading.Thread):
43 def __init__(self, test_object, request_handler):
44 threading.Thread.__init__(self)
45 self.request_handler = request_handler
46 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000047
48 def run(self):
Antoine Pitroucb342182011-03-21 00:26:51 +010049 self.server = HTTPServer(('localhost', 0), self.request_handler)
50 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000051 self.test_object.server_started.set()
52 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000053 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000054 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000055 finally:
56 self.server.server_close()
57
58 def stop(self):
59 self.server.shutdown()
Victor Stinner830d7d22017-08-22 18:05:07 +020060 self.join()
Georg Brandlb533e262008-05-25 18:19:30 +000061
62
63class BaseTestCase(unittest.TestCase):
64 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000065 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000066 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000067 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000068 self.thread = TestServerThread(self, self.request_handler)
69 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000070 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000071
72 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000073 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020074 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000075 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000076 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000077
78 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010079 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000080 self.connection.request(method, uri, body, headers)
81 return self.connection.getresponse()
82
83
84class BaseHTTPServerTestCase(BaseTestCase):
85 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
86 protocol_version = 'HTTP/1.1'
87 default_request_version = 'HTTP/1.1'
88
89 def do_TEST(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', 'close')
93 self.end_headers()
94
95 def do_KEEP(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020096 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000097 self.send_header('Content-Type', 'text/html')
98 self.send_header('Connection', 'keep-alive')
99 self.end_headers()
100
101 def do_KEYERROR(self):
102 self.send_error(999)
103
Senthil Kumaran52d27202012-10-10 23:16:21 -0700104 def do_NOTFOUND(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200105 self.send_error(HTTPStatus.NOT_FOUND)
Senthil Kumaran52d27202012-10-10 23:16:21 -0700106
Senthil Kumaran26886442013-03-15 07:53:21 -0700107 def do_EXPLAINERROR(self):
108 self.send_error(999, "Short Message",
Martin Panter46f50722016-05-26 05:35:26 +0000109 "This is a long \n explanation")
Senthil Kumaran26886442013-03-15 07:53:21 -0700110
Georg Brandlb533e262008-05-25 18:19:30 +0000111 def do_CUSTOM(self):
112 self.send_response(999)
113 self.send_header('Content-Type', 'text/html')
114 self.send_header('Connection', 'close')
115 self.end_headers()
116
Armin Ronacher8d96d772011-01-22 13:13:05 +0000117 def do_LATINONEHEADER(self):
118 self.send_response(999)
119 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000120 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000121 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000122 body = self.headers['x-special-incoming'].encode('utf-8')
123 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000124
Martin Pantere42e1292016-06-08 08:29:13 +0000125 def do_SEND_ERROR(self):
126 self.send_error(int(self.path[1:]))
127
128 def do_HEAD(self):
129 self.send_error(int(self.path[1:]))
130
Georg Brandlb533e262008-05-25 18:19:30 +0000131 def setUp(self):
132 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100133 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000134 self.con.connect()
135
136 def test_command(self):
137 self.con.request('GET', '/')
138 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200139 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000140
141 def test_request_line_trimming(self):
142 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400143 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000144 self.con.endheaders()
145 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200146 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000147
148 def test_version_bogus(self):
149 self.con._http_vsn_str = 'FUBAR'
150 self.con.putrequest('GET', '/')
151 self.con.endheaders()
152 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200153 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000154
155 def test_version_digits(self):
156 self.con._http_vsn_str = 'HTTP/9.9.9'
157 self.con.putrequest('GET', '/')
158 self.con.endheaders()
159 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200160 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000161
162 def test_version_none_get(self):
163 self.con._http_vsn_str = ''
164 self.con.putrequest('GET', '/')
165 self.con.endheaders()
166 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200167 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000168
169 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400170 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000171 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400172 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000173 self.con.endheaders()
174 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200175 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000176
177 def test_version_invalid(self):
178 self.con._http_vsn = 99
179 self.con._http_vsn_str = 'HTTP/9.9'
180 self.con.putrequest('GET', '/')
181 self.con.endheaders()
182 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200183 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000184
185 def test_send_blank(self):
186 self.con._http_vsn_str = ''
187 self.con.putrequest('', '')
188 self.con.endheaders()
189 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200190 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000191
192 def test_header_close(self):
193 self.con.putrequest('GET', '/')
194 self.con.putheader('Connection', 'close')
195 self.con.endheaders()
196 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200197 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000198
Berker Peksag20853612016-08-25 01:13:34 +0300199 def test_header_keep_alive(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000200 self.con._http_vsn_str = 'HTTP/1.1'
201 self.con.putrequest('GET', '/')
202 self.con.putheader('Connection', 'keep-alive')
203 self.con.endheaders()
204 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200205 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000206
207 def test_handler(self):
208 self.con.request('TEST', '/')
209 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200210 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000211
212 def test_return_header_keep_alive(self):
213 self.con.request('KEEP', '/')
214 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000215 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000216 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000217 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000218
219 def test_internal_key_error(self):
220 self.con.request('KEYERROR', '/')
221 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000222 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000223
224 def test_return_custom_status(self):
225 self.con.request('CUSTOM', '/')
226 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000227 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000228
Senthil Kumaran26886442013-03-15 07:53:21 -0700229 def test_return_explain_error(self):
230 self.con.request('EXPLAINERROR', '/')
231 res = self.con.getresponse()
232 self.assertEqual(res.status, 999)
233 self.assertTrue(int(res.getheader('Content-Length')))
234
Armin Ronacher8d96d772011-01-22 13:13:05 +0000235 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000236 self.con.request('LATINONEHEADER', '/', headers={
237 'X-Special-Incoming': 'Ärger mit Unicode'
238 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000239 res = self.con.getresponse()
240 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000241 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000242
Senthil Kumaran52d27202012-10-10 23:16:21 -0700243 def test_error_content_length(self):
244 # Issue #16088: standard error responses should have a content-length
245 self.con.request('NOTFOUND', '/')
246 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200247 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
248
Senthil Kumaran52d27202012-10-10 23:16:21 -0700249 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700250 self.assertEqual(int(res.getheader('Content-Length')), len(data))
251
Martin Pantere42e1292016-06-08 08:29:13 +0000252 def test_send_error(self):
253 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
254 HTTPStatus.RESET_CONTENT)
255 for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
256 HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
257 HTTPStatus.SWITCHING_PROTOCOLS):
258 self.con.request('SEND_ERROR', '/{}'.format(code))
259 res = self.con.getresponse()
260 self.assertEqual(code, res.status)
261 self.assertEqual(None, res.getheader('Content-Length'))
262 self.assertEqual(None, res.getheader('Content-Type'))
263 if code not in allow_transfer_encoding_codes:
264 self.assertEqual(None, res.getheader('Transfer-Encoding'))
265
266 data = res.read()
267 self.assertEqual(b'', data)
268
269 def test_head_via_send_error(self):
270 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
271 HTTPStatus.RESET_CONTENT)
272 for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
273 HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
274 HTTPStatus.SWITCHING_PROTOCOLS):
275 self.con.request('HEAD', '/{}'.format(code))
276 res = self.con.getresponse()
277 self.assertEqual(code, res.status)
278 if code == HTTPStatus.OK:
279 self.assertTrue(int(res.getheader('Content-Length')) > 0)
280 self.assertIn('text/html', res.getheader('Content-Type'))
281 else:
282 self.assertEqual(None, res.getheader('Content-Length'))
283 self.assertEqual(None, res.getheader('Content-Type'))
284 if code not in allow_transfer_encoding_codes:
285 self.assertEqual(None, res.getheader('Transfer-Encoding'))
286
287 data = res.read()
288 self.assertEqual(b'', data)
289
Georg Brandlb533e262008-05-25 18:19:30 +0000290
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200291class RequestHandlerLoggingTestCase(BaseTestCase):
292 class request_handler(BaseHTTPRequestHandler):
293 protocol_version = 'HTTP/1.1'
294 default_request_version = 'HTTP/1.1'
295
296 def do_GET(self):
297 self.send_response(HTTPStatus.OK)
298 self.end_headers()
299
300 def do_ERROR(self):
301 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
302
303 def test_get(self):
304 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
305 self.con.connect()
306
307 with support.captured_stderr() as err:
308 self.con.request('GET', '/')
309 self.con.getresponse()
310
311 self.assertTrue(
312 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
313
314 def test_err(self):
315 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
316 self.con.connect()
317
318 with support.captured_stderr() as err:
319 self.con.request('ERROR', '/')
320 self.con.getresponse()
321
322 lines = err.getvalue().split('\n')
323 self.assertTrue(lines[0].endswith('code 404, message File not found'))
324 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
325
326
Georg Brandlb533e262008-05-25 18:19:30 +0000327class SimpleHTTPServerTestCase(BaseTestCase):
328 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
329 pass
330
331 def setUp(self):
332 BaseTestCase.setUp(self)
333 self.cwd = os.getcwd()
334 basetempdir = tempfile.gettempdir()
335 os.chdir(basetempdir)
336 self.data = b'We are the knights who say Ni!'
337 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
338 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panterfc475a92016-04-09 04:56:10 +0000339 self.base_url = '/' + self.tempdir_name
Victor Stinner28ce07a2017-07-28 18:15:02 +0200340 tempname = os.path.join(self.tempdir, 'test')
341 with open(tempname, 'wb') as temp:
Brett Cannon105df5d2010-10-29 23:43:42 +0000342 temp.write(self.data)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200343 temp.flush()
344 mtime = os.stat(tempname).st_mtime
Pierre Quentel351adda2017-04-02 12:26:12 +0200345 # compute last modification datetime for browser cache tests
346 last_modif = datetime.datetime.fromtimestamp(mtime,
347 datetime.timezone.utc)
348 self.last_modif_datetime = last_modif.replace(microsecond=0)
349 self.last_modif_header = email.utils.formatdate(
350 last_modif.timestamp(), usegmt=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000351
352 def tearDown(self):
353 try:
354 os.chdir(self.cwd)
355 try:
356 shutil.rmtree(self.tempdir)
357 except:
358 pass
359 finally:
360 BaseTestCase.tearDown(self)
361
362 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300363 def close_conn():
364 """Don't close reader yet so we can check if there was leftover
365 buffered input"""
366 nonlocal reader
367 reader = response.fp
368 response.fp = None
369 reader = None
370 response._close_conn = close_conn
371
Georg Brandlb533e262008-05-25 18:19:30 +0000372 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000373 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000374 self.assertEqual(response.status, status)
375 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000376 if data:
377 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300378 # Ensure the server has not set up a persistent connection, and has
379 # not sent any extra data
380 self.assertEqual(response.version, 10)
381 self.assertEqual(response.msg.get("Connection", "close"), "close")
382 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
383
384 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300385 return body
386
Ned Deily14183202015-01-05 01:02:30 -0800387 @support.requires_mac_ver(10, 5)
Steve Dowere58571b2016-09-08 11:11:13 -0700388 @unittest.skipIf(sys.platform == 'win32',
389 'undecodable name cannot be decoded on win32')
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300390 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
391 'need support.TESTFN_UNDECODABLE')
392 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300393 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300394 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
395 with open(os.path.join(self.tempdir, filename), 'wb') as f:
396 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000397 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300398 if sys.platform == 'darwin':
399 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
400 # UTF-8 into a percent-encoded value.
401 for name in os.listdir(self.tempdir):
402 if name != 'test': # Ignore a filename created in setUp().
403 filename = name
404 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200405 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300406 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
407 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300408 .encode(enc, 'surrogateescape'), body)
Martin Panterda3bb382016-04-11 00:40:08 +0000409 self.assertIn(('>%s<' % html.escape(filename, quote=False))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300410 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000411 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200412 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300413 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000414
415 def test_get(self):
416 #constructs the path relative to the root directory of the HTTPServer
Martin Panterfc475a92016-04-09 04:56:10 +0000417 response = self.request(self.base_url + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200418 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700419 # check for trailing "/" which should return 404. See Issue17324
Martin Panterfc475a92016-04-09 04:56:10 +0000420 response = self.request(self.base_url + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200421 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Martin Panterfc475a92016-04-09 04:56:10 +0000422 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200423 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000424 response = self.request(self.base_url)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200425 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000426 response = self.request(self.base_url + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200427 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000428 response = self.request(self.base_url + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200429 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600430 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000431 self.base_url + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000432 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200433 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000434 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200435 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300436
437 data = b"Dummy index file\r\n"
438 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
439 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000440 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300441 self.check_status_and_reason(response, HTTPStatus.OK, data)
442
443 # chmod() doesn't work as expected on Windows, and filesystem
444 # permissions are ignored by root on Unix.
445 if os.name == 'posix' and os.geteuid() != 0:
446 os.chmod(self.tempdir, 0)
447 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000448 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200449 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300450 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000451 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000452
453 def test_head(self):
454 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000455 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200456 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000457 self.assertEqual(response.getheader('content-length'),
458 str(len(self.data)))
459 self.assertEqual(response.getheader('content-type'),
460 'application/octet-stream')
461
Pierre Quentel351adda2017-04-02 12:26:12 +0200462 def test_browser_cache(self):
463 """Check that when a request to /test is sent with the request header
464 If-Modified-Since set to date of last modification, the server returns
465 status code 304, not 200
466 """
467 headers = email.message.Message()
468 headers['If-Modified-Since'] = self.last_modif_header
469 response = self.request(self.base_url + '/test', headers=headers)
470 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
471
472 # one hour after last modification : must return 304
473 new_dt = self.last_modif_datetime + datetime.timedelta(hours=1)
474 headers = email.message.Message()
475 headers['If-Modified-Since'] = email.utils.format_datetime(new_dt,
476 usegmt=True)
477 response = self.request(self.base_url + '/test', headers=headers)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200478 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
Pierre Quentel351adda2017-04-02 12:26:12 +0200479
480 def test_browser_cache_file_changed(self):
481 # with If-Modified-Since earlier than Last-Modified, must return 200
482 dt = self.last_modif_datetime
483 # build datetime object : 365 days before last modification
484 old_dt = dt - datetime.timedelta(days=365)
485 headers = email.message.Message()
486 headers['If-Modified-Since'] = email.utils.format_datetime(old_dt,
487 usegmt=True)
488 response = self.request(self.base_url + '/test', headers=headers)
489 self.check_status_and_reason(response, HTTPStatus.OK)
490
491 def test_browser_cache_with_If_None_Match_header(self):
492 # if If-None-Match header is present, ignore If-Modified-Since
493
494 headers = email.message.Message()
495 headers['If-Modified-Since'] = self.last_modif_header
496 headers['If-None-Match'] = "*"
497 response = self.request(self.base_url + '/test', headers=headers)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200498 self.check_status_and_reason(response, HTTPStatus.OK)
Pierre Quentel351adda2017-04-02 12:26:12 +0200499
Georg Brandlb533e262008-05-25 18:19:30 +0000500 def test_invalid_requests(self):
501 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200502 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000503 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400504 response = self.request('/', method='custom')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200505 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000506 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200507 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000508
Pierre Quentel351adda2017-04-02 12:26:12 +0200509 def test_last_modified(self):
510 """Checks that the datetime returned in Last-Modified response header
511 is the actual datetime of last modification, rounded to the second
512 """
513 response = self.request(self.base_url + '/test')
514 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
515 last_modif_header = response.headers['Last-modified']
516 self.assertEqual(last_modif_header, self.last_modif_header)
517
Martin Panterfc475a92016-04-09 04:56:10 +0000518 def test_path_without_leading_slash(self):
519 response = self.request(self.tempdir_name + '/test')
520 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
521 response = self.request(self.tempdir_name + '/test/')
522 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
523 response = self.request(self.tempdir_name + '/')
524 self.check_status_and_reason(response, HTTPStatus.OK)
525 response = self.request(self.tempdir_name)
526 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
527 response = self.request(self.tempdir_name + '/?hi=2')
528 self.check_status_and_reason(response, HTTPStatus.OK)
529 response = self.request(self.tempdir_name + '?hi=1')
530 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
531 self.assertEqual(response.getheader("Location"),
532 self.tempdir_name + "/?hi=1")
533
Martin Panterda3bb382016-04-11 00:40:08 +0000534 def test_html_escape_filename(self):
535 filename = '<test&>.txt'
536 fullpath = os.path.join(self.tempdir, filename)
537
538 try:
539 open(fullpath, 'w').close()
540 except OSError:
541 raise unittest.SkipTest('Can not create file %s on current file '
542 'system' % filename)
543
544 try:
545 response = self.request(self.base_url + '/')
546 body = self.check_status_and_reason(response, HTTPStatus.OK)
547 enc = response.headers.get_content_charset()
548 finally:
549 os.unlink(fullpath) # avoid affecting test_undecodable_filename
550
551 self.assertIsNotNone(enc)
552 html_text = '>%s<' % html.escape(filename, quote=False)
553 self.assertIn(html_text.encode(enc), body)
554
Georg Brandlb533e262008-05-25 18:19:30 +0000555
556cgi_file1 = """\
557#!%s
558
559print("Content-type: text/html")
560print()
561print("Hello World")
562"""
563
564cgi_file2 = """\
565#!%s
566import cgi
567
568print("Content-type: text/html")
569print()
570
571form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000572print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
573 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000574"""
575
Martin Pantera02e18a2015-10-03 05:38:07 +0000576cgi_file4 = """\
577#!%s
578import os
579
580print("Content-type: text/html")
581print()
582
583print(os.environ["%s"])
584"""
585
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100586
587@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
588 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000589class CGIHTTPServerTestCase(BaseTestCase):
590 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
591 pass
592
Antoine Pitroue768c392012-08-05 14:52:45 +0200593 linesep = os.linesep.encode('ascii')
594
Georg Brandlb533e262008-05-25 18:19:30 +0000595 def setUp(self):
596 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000597 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000598 self.parent_dir = tempfile.mkdtemp()
599 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700600 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000601 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700602 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400603 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000604 self.file1_path = None
605 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700606 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000607 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000608
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000609 # The shebang line should be pure ASCII: use symlink if possible.
610 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000611 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000612 self.pythonexe = os.path.join(self.parent_dir, 'python')
613 os.symlink(sys.executable, self.pythonexe)
614 else:
615 self.pythonexe = sys.executable
616
Victor Stinner3218c312010-10-17 20:13:36 +0000617 try:
618 # The python executable path is written as the first line of the
619 # CGI Python script. The encoding cookie cannot be used, and so the
620 # path should be encodable to the default script encoding (utf-8)
621 self.pythonexe.encode('utf-8')
622 except UnicodeEncodeError:
623 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200624 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000625
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400626 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
627 with open(self.nocgi_path, 'w') as fp:
628 fp.write(cgi_file1 % self.pythonexe)
629 os.chmod(self.nocgi_path, 0o777)
630
Georg Brandlb533e262008-05-25 18:19:30 +0000631 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000632 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000633 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000634 os.chmod(self.file1_path, 0o777)
635
636 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000637 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000638 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000639 os.chmod(self.file2_path, 0o777)
640
Ned Deily915a30f2014-07-12 22:06:26 -0700641 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
642 with open(self.file3_path, 'w', encoding='utf-8') as file3:
643 file3.write(cgi_file1 % self.pythonexe)
644 os.chmod(self.file3_path, 0o777)
645
Martin Pantera02e18a2015-10-03 05:38:07 +0000646 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
647 with open(self.file4_path, 'w', encoding='utf-8') as file4:
648 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
649 os.chmod(self.file4_path, 0o777)
650
Georg Brandlb533e262008-05-25 18:19:30 +0000651 os.chdir(self.parent_dir)
652
653 def tearDown(self):
654 try:
655 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000656 if self.pythonexe != sys.executable:
657 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400658 if self.nocgi_path:
659 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000660 if self.file1_path:
661 os.remove(self.file1_path)
662 if self.file2_path:
663 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700664 if self.file3_path:
665 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000666 if self.file4_path:
667 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700668 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000669 os.rmdir(self.cgi_dir)
670 os.rmdir(self.parent_dir)
671 finally:
672 BaseTestCase.tearDown(self)
673
Senthil Kumarand70846b2012-04-12 02:34:32 +0800674 def test_url_collapse_path(self):
675 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000676 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800677 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000678 '..': IndexError,
679 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800680 '/': '//',
681 '//': '//',
682 '/\\': '//\\',
683 '/.//': '//',
684 'cgi-bin/file1.py': '/cgi-bin/file1.py',
685 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
686 'a': '//a',
687 '/a': '//a',
688 '//a': '//a',
689 './a': '//a',
690 './C:/': '/C:/',
691 '/a/b': '/a/b',
692 '/a/b/': '/a/b/',
693 '/a/b/.': '/a/b/',
694 '/a/b/c/..': '/a/b/',
695 '/a/b/c/../d': '/a/b/d',
696 '/a/b/c/../d/e/../f': '/a/b/d/f',
697 '/a/b/c/../d/e/../../f': '/a/b/f',
698 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000699 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800700 '/a/b/c/../d/e/../../../f': '/a/f',
701 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000702 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800703 '/a/b/c/../d/e/../../../../f/..': '//',
704 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000705 }
706 for path, expected in test_vectors.items():
707 if isinstance(expected, type) and issubclass(expected, Exception):
708 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800709 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000710 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800711 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000712 self.assertEqual(expected, actual,
713 msg='path = %r\nGot: %r\nWanted: %r' %
714 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000715
Georg Brandlb533e262008-05-25 18:19:30 +0000716 def test_headers_and_content(self):
717 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200718 self.assertEqual(
719 (res.read(), res.getheader('Content-type'), res.status),
720 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000721
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400722 def test_issue19435(self):
723 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200724 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400725
Georg Brandlb533e262008-05-25 18:19:30 +0000726 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000727 params = urllib.parse.urlencode(
728 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000729 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
730 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
731
Antoine Pitroue768c392012-08-05 14:52:45 +0200732 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000733
734 def test_invaliduri(self):
735 res = self.request('/cgi-bin/invalid')
736 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200737 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000738
739 def test_authorization(self):
740 headers = {b'Authorization' : b'Basic ' +
741 base64.b64encode(b'username:pass')}
742 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200743 self.assertEqual(
744 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
745 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000746
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000747 def test_no_leading_slash(self):
748 # http://bugs.python.org/issue2254
749 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200750 self.assertEqual(
751 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
752 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000753
Senthil Kumaran42713722010-10-03 17:55:45 +0000754 def test_os_environ_is_not_altered(self):
755 signature = "Test CGI Server"
756 os.environ['SERVER_SOFTWARE'] = signature
757 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200758 self.assertEqual(
759 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
760 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000761 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
762
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700763 def test_urlquote_decoding_in_cgi_check(self):
764 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200765 self.assertEqual(
766 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
767 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700768
Ned Deily915a30f2014-07-12 22:06:26 -0700769 def test_nested_cgi_path_issue21323(self):
770 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200771 self.assertEqual(
772 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
773 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700774
Martin Pantera02e18a2015-10-03 05:38:07 +0000775 def test_query_with_multiple_question_mark(self):
776 res = self.request('/cgi-bin/file4.py?a=b?c=d')
777 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000778 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000779 (res.read(), res.getheader('Content-type'), res.status))
780
Martin Pantercb29e8c2015-10-03 05:55:46 +0000781 def test_query_with_continuous_slashes(self):
782 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
783 self.assertEqual(
784 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000785 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000786 (res.read(), res.getheader('Content-type'), res.status))
787
Georg Brandlb533e262008-05-25 18:19:30 +0000788
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000789class SocketlessRequestHandler(SimpleHTTPRequestHandler):
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200790 def __init__(self, *args, **kwargs):
791 request = mock.Mock()
792 request.makefile.return_value = BytesIO()
793 super().__init__(request, None, None)
794
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000795 self.get_called = False
796 self.protocol_version = "HTTP/1.1"
797
798 def do_GET(self):
799 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200800 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000801 self.send_header('Content-Type', 'text/html')
802 self.end_headers()
803 self.wfile.write(b'<html><body>Data</body></html>\r\n')
804
805 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000806 pass
807
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000808class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
809 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200810 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000811 return False
812
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800813
814class AuditableBytesIO:
815
816 def __init__(self):
817 self.datas = []
818
819 def write(self, data):
820 self.datas.append(data)
821
822 def getData(self):
823 return b''.join(self.datas)
824
825 @property
826 def numWrites(self):
827 return len(self.datas)
828
829
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000830class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200831 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000832
833 Test the support for the Expect 100-continue header.
834 """
835
836 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
837
838 def setUp (self):
839 self.handler = SocketlessRequestHandler()
840
841 def send_typical_request(self, message):
842 input = BytesIO(message)
843 output = BytesIO()
844 self.handler.rfile = input
845 self.handler.wfile = output
846 self.handler.handle_one_request()
847 output.seek(0)
848 return output.readlines()
849
850 def verify_get_called(self):
851 self.assertTrue(self.handler.get_called)
852
853 def verify_expected_headers(self, headers):
854 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
855 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
856
857 def verify_http_server_response(self, response):
858 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200859 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000860
861 def test_http_1_1(self):
862 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
863 self.verify_http_server_response(result[0])
864 self.verify_expected_headers(result[1:-1])
865 self.verify_get_called()
866 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500867 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
868 self.assertEqual(self.handler.command, 'GET')
869 self.assertEqual(self.handler.path, '/')
870 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
871 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000872
873 def test_http_1_0(self):
874 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
875 self.verify_http_server_response(result[0])
876 self.verify_expected_headers(result[1:-1])
877 self.verify_get_called()
878 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500879 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
880 self.assertEqual(self.handler.command, 'GET')
881 self.assertEqual(self.handler.path, '/')
882 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
883 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000884
885 def test_http_0_9(self):
886 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
887 self.assertEqual(len(result), 1)
888 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
889 self.verify_get_called()
890
Martin Pantere82338d2016-11-19 01:06:37 +0000891 def test_extra_space(self):
892 result = self.send_typical_request(
893 b'GET /spaced out HTTP/1.1\r\n'
894 b'Host: dummy\r\n'
895 b'\r\n'
896 )
897 self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
898 self.verify_expected_headers(result[1:result.index(b'\r\n')])
899 self.assertFalse(self.handler.get_called)
900
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000901 def test_with_continue_1_0(self):
902 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
903 self.verify_http_server_response(result[0])
904 self.verify_expected_headers(result[1:-1])
905 self.verify_get_called()
906 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500907 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
908 self.assertEqual(self.handler.command, 'GET')
909 self.assertEqual(self.handler.path, '/')
910 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
911 headers = (("Expect", "100-continue"),)
912 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000913
914 def test_with_continue_1_1(self):
915 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
916 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500917 self.assertEqual(result[1], b'\r\n')
918 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000919 self.verify_expected_headers(result[2:-1])
920 self.verify_get_called()
921 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500922 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
923 self.assertEqual(self.handler.command, 'GET')
924 self.assertEqual(self.handler.path, '/')
925 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
926 headers = (("Expect", "100-continue"),)
927 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000928
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800929 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000930
931 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800932 output = AuditableBytesIO()
933 handler = SocketlessRequestHandler()
934 handler.rfile = input
935 handler.wfile = output
936 handler.request_version = 'HTTP/1.1'
937 handler.requestline = ''
938 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000939
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800940 handler.send_error(418)
941 self.assertEqual(output.numWrites, 2)
942
943 def test_header_buffering_of_send_response_only(self):
944
945 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
946 output = AuditableBytesIO()
947 handler = SocketlessRequestHandler()
948 handler.rfile = input
949 handler.wfile = output
950 handler.request_version = 'HTTP/1.1'
951
952 handler.send_response_only(418)
953 self.assertEqual(output.numWrites, 0)
954 handler.end_headers()
955 self.assertEqual(output.numWrites, 1)
956
957 def test_header_buffering_of_send_header(self):
958
959 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
960 output = AuditableBytesIO()
961 handler = SocketlessRequestHandler()
962 handler.rfile = input
963 handler.wfile = output
964 handler.request_version = 'HTTP/1.1'
965
966 handler.send_header('Foo', 'foo')
967 handler.send_header('bar', 'bar')
968 self.assertEqual(output.numWrites, 0)
969 handler.end_headers()
970 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
971 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000972
973 def test_header_unbuffered_when_continue(self):
974
975 def _readAndReseek(f):
976 pos = f.tell()
977 f.seek(0)
978 data = f.read()
979 f.seek(pos)
980 return data
981
982 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
983 output = BytesIO()
984 self.handler.rfile = input
985 self.handler.wfile = output
986 self.handler.request_version = 'HTTP/1.1'
987
988 self.handler.handle_one_request()
989 self.assertNotEqual(_readAndReseek(output), b'')
990 result = _readAndReseek(output).split(b'\r\n')
991 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500992 self.assertEqual(result[1], b'')
993 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000994
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000995 def test_with_continue_rejected(self):
996 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
997 self.handler = RejectingSocketlessRequestHandler()
998 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
999 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
1000 self.verify_expected_headers(result[1:-1])
1001 # The expect handler should short circuit the usual get method by
1002 # returning false here, so get_called should be false
1003 self.assertFalse(self.handler.get_called)
1004 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
1005 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
1006
Antoine Pitrouc4924372010-12-16 16:48:36 +00001007 def test_request_length(self):
1008 # Issue #10714: huge request lines are discarded, to avoid Denial
1009 # of Service attacks.
1010 result = self.send_typical_request(b'GET ' + b'x' * 65537)
1011 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
1012 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001013 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001014
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001015 def test_header_length(self):
1016 # Issue #6791: same for headers
1017 result = self.send_typical_request(
1018 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +00001019 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001020 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001021 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1022
Martin Panteracc03192016-04-03 00:45:46 +00001023 def test_too_many_headers(self):
1024 result = self.send_typical_request(
1025 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
1026 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
1027 self.assertFalse(self.handler.get_called)
1028 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1029
Martin Panterda3bb382016-04-11 00:40:08 +00001030 def test_html_escape_on_error(self):
1031 result = self.send_typical_request(
1032 b'<script>alert("hello")</script> / HTTP/1.1')
1033 result = b''.join(result)
1034 text = '<script>alert("hello")</script>'
1035 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
1036
Benjamin Peterson70e28472015-02-17 21:11:10 -05001037 def test_close_connection(self):
1038 # handle_one_request() should be repeatedly called until
1039 # it sets close_connection
1040 def handle_one_request():
1041 self.handler.close_connection = next(close_values)
1042 self.handler.handle_one_request = handle_one_request
1043
1044 close_values = iter((True,))
1045 self.handler.handle()
1046 self.assertRaises(StopIteration, next, close_values)
1047
1048 close_values = iter((False, False, True))
1049 self.handler.handle()
1050 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001051
Berker Peksag04bc5b92016-03-14 06:06:03 +02001052 def test_date_time_string(self):
1053 now = time.time()
1054 # this is the old code that formats the timestamp
1055 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
1056 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
1057 self.handler.weekdayname[wd],
1058 day,
1059 self.handler.monthname[month],
1060 year, hh, mm, ss
1061 )
1062 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
1063
1064
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001065class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
1066 """ Test url parsing """
1067 def setUp(self):
1068 self.translated = os.getcwd()
1069 self.translated = os.path.join(self.translated, 'filename')
1070 self.handler = SocketlessRequestHandler()
1071
1072 def test_query_arguments(self):
1073 path = self.handler.translate_path('/filename')
1074 self.assertEqual(path, self.translated)
1075 path = self.handler.translate_path('/filename?foo=bar')
1076 self.assertEqual(path, self.translated)
1077 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
1078 self.assertEqual(path, self.translated)
1079
1080 def test_start_with_double_slash(self):
1081 path = self.handler.translate_path('//filename')
1082 self.assertEqual(path, self.translated)
1083 path = self.handler.translate_path('//filename?foo=bar')
1084 self.assertEqual(path, self.translated)
1085
Martin Panterd274b3f2016-04-18 03:45:18 +00001086 def test_windows_colon(self):
1087 with support.swap_attr(server.os, 'path', ntpath):
1088 path = self.handler.translate_path('c:c:c:foo/filename')
1089 path = path.replace(ntpath.sep, os.sep)
1090 self.assertEqual(path, self.translated)
1091
1092 path = self.handler.translate_path('\\c:../filename')
1093 path = path.replace(ntpath.sep, os.sep)
1094 self.assertEqual(path, self.translated)
1095
1096 path = self.handler.translate_path('c:\\c:..\\foo/filename')
1097 path = path.replace(ntpath.sep, os.sep)
1098 self.assertEqual(path, self.translated)
1099
1100 path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
1101 path = path.replace(ntpath.sep, os.sep)
1102 self.assertEqual(path, self.translated)
1103
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001104
Berker Peksag366c5702015-02-13 20:48:15 +02001105class MiscTestCase(unittest.TestCase):
1106 def test_all(self):
1107 expected = []
1108 blacklist = {'executable', 'nobody_uid', 'test'}
1109 for name in dir(server):
1110 if name.startswith('_') or name in blacklist:
1111 continue
1112 module_object = getattr(server, name)
1113 if getattr(module_object, '__module__', None) == 'http.server':
1114 expected.append(name)
1115 self.assertCountEqual(server.__all__, expected)
1116
1117
Georg Brandlb533e262008-05-25 18:19:30 +00001118def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001119 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001120 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001121 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001122 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001123 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001124 BaseHTTPServerTestCase,
1125 SimpleHTTPServerTestCase,
1126 CGIHTTPServerTestCase,
1127 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001128 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001129 )
Georg Brandlb533e262008-05-25 18:19:30 +00001130 finally:
1131 os.chdir(cwd)
1132
1133if __name__ == '__main__':
1134 test_main()