blob: cdc52021013370fa8803159c910eb79ab7b967fa [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
Stéphane Wirtela17a2f52017-05-24 09:29:06 +020025from unittest import mock
Senthil Kumaran0f476d42010-09-30 06:09:18 +000026from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000027
28import unittest
29from test import support
Victor Stinner45df8202010-04-28 22:31:17 +000030threading = support.import_module('threading')
Georg Brandlb533e262008-05-25 18:19:30 +000031
Georg Brandlb533e262008-05-25 18:19:30 +000032class NoLogRequestHandler:
33 def log_message(self, *args):
34 # don't write log messages to stderr
35 pass
36
Barry Warsaw820c1202008-06-12 04:06:45 +000037 def read(self, n=None):
38 return ''
39
Georg Brandlb533e262008-05-25 18:19:30 +000040
41class TestServerThread(threading.Thread):
42 def __init__(self, test_object, request_handler):
43 threading.Thread.__init__(self)
44 self.request_handler = request_handler
45 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000046
47 def run(self):
Antoine Pitroucb342182011-03-21 00:26:51 +010048 self.server = HTTPServer(('localhost', 0), self.request_handler)
49 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000050 self.test_object.server_started.set()
51 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000052 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000053 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000054 finally:
55 self.server.server_close()
56
57 def stop(self):
58 self.server.shutdown()
59
60
61class BaseTestCase(unittest.TestCase):
62 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000063 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000064 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000065 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000066 self.thread = TestServerThread(self, self.request_handler)
67 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000068 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000069
70 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000071 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020072 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000073 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000074 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000075
76 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010077 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000078 self.connection.request(method, uri, body, headers)
79 return self.connection.getresponse()
80
81
82class BaseHTTPServerTestCase(BaseTestCase):
83 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
84 protocol_version = 'HTTP/1.1'
85 default_request_version = 'HTTP/1.1'
86
87 def do_TEST(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020088 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000089 self.send_header('Content-Type', 'text/html')
90 self.send_header('Connection', 'close')
91 self.end_headers()
92
93 def do_KEEP(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020094 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000095 self.send_header('Content-Type', 'text/html')
96 self.send_header('Connection', 'keep-alive')
97 self.end_headers()
98
99 def do_KEYERROR(self):
100 self.send_error(999)
101
Senthil Kumaran52d27202012-10-10 23:16:21 -0700102 def do_NOTFOUND(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200103 self.send_error(HTTPStatus.NOT_FOUND)
Senthil Kumaran52d27202012-10-10 23:16:21 -0700104
Senthil Kumaran26886442013-03-15 07:53:21 -0700105 def do_EXPLAINERROR(self):
106 self.send_error(999, "Short Message",
Martin Panter46f50722016-05-26 05:35:26 +0000107 "This is a long \n explanation")
Senthil Kumaran26886442013-03-15 07:53:21 -0700108
Georg Brandlb533e262008-05-25 18:19:30 +0000109 def do_CUSTOM(self):
110 self.send_response(999)
111 self.send_header('Content-Type', 'text/html')
112 self.send_header('Connection', 'close')
113 self.end_headers()
114
Armin Ronacher8d96d772011-01-22 13:13:05 +0000115 def do_LATINONEHEADER(self):
116 self.send_response(999)
117 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000118 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000119 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000120 body = self.headers['x-special-incoming'].encode('utf-8')
121 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000122
Martin Pantere42e1292016-06-08 08:29:13 +0000123 def do_SEND_ERROR(self):
124 self.send_error(int(self.path[1:]))
125
126 def do_HEAD(self):
127 self.send_error(int(self.path[1:]))
128
Georg Brandlb533e262008-05-25 18:19:30 +0000129 def setUp(self):
130 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100131 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000132 self.con.connect()
133
134 def test_command(self):
135 self.con.request('GET', '/')
136 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200137 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000138
139 def test_request_line_trimming(self):
140 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400141 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000142 self.con.endheaders()
143 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200144 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000145
146 def test_version_bogus(self):
147 self.con._http_vsn_str = 'FUBAR'
148 self.con.putrequest('GET', '/')
149 self.con.endheaders()
150 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200151 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000152
153 def test_version_digits(self):
154 self.con._http_vsn_str = 'HTTP/9.9.9'
155 self.con.putrequest('GET', '/')
156 self.con.endheaders()
157 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200158 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000159
160 def test_version_none_get(self):
161 self.con._http_vsn_str = ''
162 self.con.putrequest('GET', '/')
163 self.con.endheaders()
164 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200165 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000166
167 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400168 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000169 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400170 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000171 self.con.endheaders()
172 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200173 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000174
175 def test_version_invalid(self):
176 self.con._http_vsn = 99
177 self.con._http_vsn_str = 'HTTP/9.9'
178 self.con.putrequest('GET', '/')
179 self.con.endheaders()
180 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200181 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000182
183 def test_send_blank(self):
184 self.con._http_vsn_str = ''
185 self.con.putrequest('', '')
186 self.con.endheaders()
187 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200188 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000189
190 def test_header_close(self):
191 self.con.putrequest('GET', '/')
192 self.con.putheader('Connection', 'close')
193 self.con.endheaders()
194 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200195 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000196
Berker Peksag20853612016-08-25 01:13:34 +0300197 def test_header_keep_alive(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000198 self.con._http_vsn_str = 'HTTP/1.1'
199 self.con.putrequest('GET', '/')
200 self.con.putheader('Connection', 'keep-alive')
201 self.con.endheaders()
202 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200203 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000204
205 def test_handler(self):
206 self.con.request('TEST', '/')
207 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200208 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000209
210 def test_return_header_keep_alive(self):
211 self.con.request('KEEP', '/')
212 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000213 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000214 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000215 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000216
217 def test_internal_key_error(self):
218 self.con.request('KEYERROR', '/')
219 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000220 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000221
222 def test_return_custom_status(self):
223 self.con.request('CUSTOM', '/')
224 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000225 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000226
Senthil Kumaran26886442013-03-15 07:53:21 -0700227 def test_return_explain_error(self):
228 self.con.request('EXPLAINERROR', '/')
229 res = self.con.getresponse()
230 self.assertEqual(res.status, 999)
231 self.assertTrue(int(res.getheader('Content-Length')))
232
Armin Ronacher8d96d772011-01-22 13:13:05 +0000233 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000234 self.con.request('LATINONEHEADER', '/', headers={
235 'X-Special-Incoming': 'Ärger mit Unicode'
236 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000237 res = self.con.getresponse()
238 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000239 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000240
Senthil Kumaran52d27202012-10-10 23:16:21 -0700241 def test_error_content_length(self):
242 # Issue #16088: standard error responses should have a content-length
243 self.con.request('NOTFOUND', '/')
244 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200245 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
246
Senthil Kumaran52d27202012-10-10 23:16:21 -0700247 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700248 self.assertEqual(int(res.getheader('Content-Length')), len(data))
249
Martin Pantere42e1292016-06-08 08:29:13 +0000250 def test_send_error(self):
251 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
252 HTTPStatus.RESET_CONTENT)
253 for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
254 HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
255 HTTPStatus.SWITCHING_PROTOCOLS):
256 self.con.request('SEND_ERROR', '/{}'.format(code))
257 res = self.con.getresponse()
258 self.assertEqual(code, res.status)
259 self.assertEqual(None, res.getheader('Content-Length'))
260 self.assertEqual(None, res.getheader('Content-Type'))
261 if code not in allow_transfer_encoding_codes:
262 self.assertEqual(None, res.getheader('Transfer-Encoding'))
263
264 data = res.read()
265 self.assertEqual(b'', data)
266
267 def test_head_via_send_error(self):
268 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
269 HTTPStatus.RESET_CONTENT)
270 for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
271 HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
272 HTTPStatus.SWITCHING_PROTOCOLS):
273 self.con.request('HEAD', '/{}'.format(code))
274 res = self.con.getresponse()
275 self.assertEqual(code, res.status)
276 if code == HTTPStatus.OK:
277 self.assertTrue(int(res.getheader('Content-Length')) > 0)
278 self.assertIn('text/html', res.getheader('Content-Type'))
279 else:
280 self.assertEqual(None, res.getheader('Content-Length'))
281 self.assertEqual(None, res.getheader('Content-Type'))
282 if code not in allow_transfer_encoding_codes:
283 self.assertEqual(None, res.getheader('Transfer-Encoding'))
284
285 data = res.read()
286 self.assertEqual(b'', data)
287
Georg Brandlb533e262008-05-25 18:19:30 +0000288
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200289class RequestHandlerLoggingTestCase(BaseTestCase):
290 class request_handler(BaseHTTPRequestHandler):
291 protocol_version = 'HTTP/1.1'
292 default_request_version = 'HTTP/1.1'
293
294 def do_GET(self):
295 self.send_response(HTTPStatus.OK)
296 self.end_headers()
297
298 def do_ERROR(self):
299 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
300
301 def test_get(self):
302 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
303 self.con.connect()
304
305 with support.captured_stderr() as err:
306 self.con.request('GET', '/')
307 self.con.getresponse()
308
309 self.assertTrue(
310 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
311
312 def test_err(self):
313 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
314 self.con.connect()
315
316 with support.captured_stderr() as err:
317 self.con.request('ERROR', '/')
318 self.con.getresponse()
319
320 lines = err.getvalue().split('\n')
321 self.assertTrue(lines[0].endswith('code 404, message File not found'))
322 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
323
324
Georg Brandlb533e262008-05-25 18:19:30 +0000325class SimpleHTTPServerTestCase(BaseTestCase):
326 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
327 pass
328
329 def setUp(self):
330 BaseTestCase.setUp(self)
331 self.cwd = os.getcwd()
332 basetempdir = tempfile.gettempdir()
333 os.chdir(basetempdir)
334 self.data = b'We are the knights who say Ni!'
335 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
336 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panterfc475a92016-04-09 04:56:10 +0000337 self.base_url = '/' + self.tempdir_name
Brett Cannon105df5d2010-10-29 23:43:42 +0000338 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
339 temp.write(self.data)
Pierre Quentel351adda2017-04-02 12:26:12 +0200340 mtime = os.fstat(temp.fileno()).st_mtime
341 # compute last modification datetime for browser cache tests
342 last_modif = datetime.datetime.fromtimestamp(mtime,
343 datetime.timezone.utc)
344 self.last_modif_datetime = last_modif.replace(microsecond=0)
345 self.last_modif_header = email.utils.formatdate(
346 last_modif.timestamp(), usegmt=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000347
348 def tearDown(self):
349 try:
350 os.chdir(self.cwd)
351 try:
352 shutil.rmtree(self.tempdir)
353 except:
354 pass
355 finally:
356 BaseTestCase.tearDown(self)
357
358 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300359 def close_conn():
360 """Don't close reader yet so we can check if there was leftover
361 buffered input"""
362 nonlocal reader
363 reader = response.fp
364 response.fp = None
365 reader = None
366 response._close_conn = close_conn
367
Georg Brandlb533e262008-05-25 18:19:30 +0000368 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000369 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000370 self.assertEqual(response.status, status)
371 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000372 if data:
373 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300374 # Ensure the server has not set up a persistent connection, and has
375 # not sent any extra data
376 self.assertEqual(response.version, 10)
377 self.assertEqual(response.msg.get("Connection", "close"), "close")
378 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
379
380 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300381 return body
382
Ned Deily14183202015-01-05 01:02:30 -0800383 @support.requires_mac_ver(10, 5)
Steve Dowere58571b2016-09-08 11:11:13 -0700384 @unittest.skipIf(sys.platform == 'win32',
385 'undecodable name cannot be decoded on win32')
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300386 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
387 'need support.TESTFN_UNDECODABLE')
388 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300389 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300390 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
391 with open(os.path.join(self.tempdir, filename), 'wb') as f:
392 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000393 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300394 if sys.platform == 'darwin':
395 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
396 # UTF-8 into a percent-encoded value.
397 for name in os.listdir(self.tempdir):
398 if name != 'test': # Ignore a filename created in setUp().
399 filename = name
400 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200401 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300402 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
403 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300404 .encode(enc, 'surrogateescape'), body)
Martin Panterda3bb382016-04-11 00:40:08 +0000405 self.assertIn(('>%s<' % html.escape(filename, quote=False))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300406 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000407 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200408 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300409 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000410
411 def test_get(self):
412 #constructs the path relative to the root directory of the HTTPServer
Martin Panterfc475a92016-04-09 04:56:10 +0000413 response = self.request(self.base_url + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200414 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700415 # check for trailing "/" which should return 404. See Issue17324
Martin Panterfc475a92016-04-09 04:56:10 +0000416 response = self.request(self.base_url + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200417 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Martin Panterfc475a92016-04-09 04:56:10 +0000418 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200419 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000420 response = self.request(self.base_url)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200421 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000422 response = self.request(self.base_url + '/?hi=2')
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 + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200425 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600426 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000427 self.base_url + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000428 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200429 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000430 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200431 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300432
433 data = b"Dummy index file\r\n"
434 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
435 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000436 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300437 self.check_status_and_reason(response, HTTPStatus.OK, data)
438
439 # chmod() doesn't work as expected on Windows, and filesystem
440 # permissions are ignored by root on Unix.
441 if os.name == 'posix' and os.geteuid() != 0:
442 os.chmod(self.tempdir, 0)
443 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000444 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200445 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300446 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000447 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000448
449 def test_head(self):
450 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000451 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200452 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000453 self.assertEqual(response.getheader('content-length'),
454 str(len(self.data)))
455 self.assertEqual(response.getheader('content-type'),
456 'application/octet-stream')
457
Pierre Quentel351adda2017-04-02 12:26:12 +0200458 def test_browser_cache(self):
459 """Check that when a request to /test is sent with the request header
460 If-Modified-Since set to date of last modification, the server returns
461 status code 304, not 200
462 """
463 headers = email.message.Message()
464 headers['If-Modified-Since'] = self.last_modif_header
465 response = self.request(self.base_url + '/test', headers=headers)
466 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
467
468 # one hour after last modification : must return 304
469 new_dt = self.last_modif_datetime + datetime.timedelta(hours=1)
470 headers = email.message.Message()
471 headers['If-Modified-Since'] = email.utils.format_datetime(new_dt,
472 usegmt=True)
473 response = self.request(self.base_url + '/test', headers=headers)
474 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
475
476 def test_browser_cache_file_changed(self):
477 # with If-Modified-Since earlier than Last-Modified, must return 200
478 dt = self.last_modif_datetime
479 # build datetime object : 365 days before last modification
480 old_dt = dt - datetime.timedelta(days=365)
481 headers = email.message.Message()
482 headers['If-Modified-Since'] = email.utils.format_datetime(old_dt,
483 usegmt=True)
484 response = self.request(self.base_url + '/test', headers=headers)
485 self.check_status_and_reason(response, HTTPStatus.OK)
486
487 def test_browser_cache_with_If_None_Match_header(self):
488 # if If-None-Match header is present, ignore If-Modified-Since
489
490 headers = email.message.Message()
491 headers['If-Modified-Since'] = self.last_modif_header
492 headers['If-None-Match'] = "*"
493 response = self.request(self.base_url + '/test', headers=headers)
494 self.check_status_and_reason(response, HTTPStatus.OK)
495
Georg Brandlb533e262008-05-25 18:19:30 +0000496 def test_invalid_requests(self):
497 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200498 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000499 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400500 response = self.request('/', method='custom')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200501 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000502 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200503 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000504
Pierre Quentel351adda2017-04-02 12:26:12 +0200505 def test_last_modified(self):
506 """Checks that the datetime returned in Last-Modified response header
507 is the actual datetime of last modification, rounded to the second
508 """
509 response = self.request(self.base_url + '/test')
510 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
511 last_modif_header = response.headers['Last-modified']
512 self.assertEqual(last_modif_header, self.last_modif_header)
513
Martin Panterfc475a92016-04-09 04:56:10 +0000514 def test_path_without_leading_slash(self):
515 response = self.request(self.tempdir_name + '/test')
516 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
517 response = self.request(self.tempdir_name + '/test/')
518 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
519 response = self.request(self.tempdir_name + '/')
520 self.check_status_and_reason(response, HTTPStatus.OK)
521 response = self.request(self.tempdir_name)
522 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
523 response = self.request(self.tempdir_name + '/?hi=2')
524 self.check_status_and_reason(response, HTTPStatus.OK)
525 response = self.request(self.tempdir_name + '?hi=1')
526 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
527 self.assertEqual(response.getheader("Location"),
528 self.tempdir_name + "/?hi=1")
529
Martin Panterda3bb382016-04-11 00:40:08 +0000530 def test_html_escape_filename(self):
531 filename = '<test&>.txt'
532 fullpath = os.path.join(self.tempdir, filename)
533
534 try:
535 open(fullpath, 'w').close()
536 except OSError:
537 raise unittest.SkipTest('Can not create file %s on current file '
538 'system' % filename)
539
540 try:
541 response = self.request(self.base_url + '/')
542 body = self.check_status_and_reason(response, HTTPStatus.OK)
543 enc = response.headers.get_content_charset()
544 finally:
545 os.unlink(fullpath) # avoid affecting test_undecodable_filename
546
547 self.assertIsNotNone(enc)
548 html_text = '>%s<' % html.escape(filename, quote=False)
549 self.assertIn(html_text.encode(enc), body)
550
Georg Brandlb533e262008-05-25 18:19:30 +0000551
552cgi_file1 = """\
553#!%s
554
555print("Content-type: text/html")
556print()
557print("Hello World")
558"""
559
560cgi_file2 = """\
561#!%s
562import cgi
563
564print("Content-type: text/html")
565print()
566
567form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000568print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
569 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000570"""
571
Martin Pantera02e18a2015-10-03 05:38:07 +0000572cgi_file4 = """\
573#!%s
574import os
575
576print("Content-type: text/html")
577print()
578
579print(os.environ["%s"])
580"""
581
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100582
583@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
584 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000585class CGIHTTPServerTestCase(BaseTestCase):
586 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
587 pass
588
Antoine Pitroue768c392012-08-05 14:52:45 +0200589 linesep = os.linesep.encode('ascii')
590
Georg Brandlb533e262008-05-25 18:19:30 +0000591 def setUp(self):
592 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000593 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000594 self.parent_dir = tempfile.mkdtemp()
595 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700596 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000597 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700598 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400599 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000600 self.file1_path = None
601 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700602 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000603 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000604
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000605 # The shebang line should be pure ASCII: use symlink if possible.
606 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000607 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000608 self.pythonexe = os.path.join(self.parent_dir, 'python')
609 os.symlink(sys.executable, self.pythonexe)
610 else:
611 self.pythonexe = sys.executable
612
Victor Stinner3218c312010-10-17 20:13:36 +0000613 try:
614 # The python executable path is written as the first line of the
615 # CGI Python script. The encoding cookie cannot be used, and so the
616 # path should be encodable to the default script encoding (utf-8)
617 self.pythonexe.encode('utf-8')
618 except UnicodeEncodeError:
619 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200620 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000621
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400622 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
623 with open(self.nocgi_path, 'w') as fp:
624 fp.write(cgi_file1 % self.pythonexe)
625 os.chmod(self.nocgi_path, 0o777)
626
Georg Brandlb533e262008-05-25 18:19:30 +0000627 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000628 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000629 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000630 os.chmod(self.file1_path, 0o777)
631
632 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000633 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000634 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000635 os.chmod(self.file2_path, 0o777)
636
Ned Deily915a30f2014-07-12 22:06:26 -0700637 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
638 with open(self.file3_path, 'w', encoding='utf-8') as file3:
639 file3.write(cgi_file1 % self.pythonexe)
640 os.chmod(self.file3_path, 0o777)
641
Martin Pantera02e18a2015-10-03 05:38:07 +0000642 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
643 with open(self.file4_path, 'w', encoding='utf-8') as file4:
644 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
645 os.chmod(self.file4_path, 0o777)
646
Georg Brandlb533e262008-05-25 18:19:30 +0000647 os.chdir(self.parent_dir)
648
649 def tearDown(self):
650 try:
651 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000652 if self.pythonexe != sys.executable:
653 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400654 if self.nocgi_path:
655 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000656 if self.file1_path:
657 os.remove(self.file1_path)
658 if self.file2_path:
659 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700660 if self.file3_path:
661 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000662 if self.file4_path:
663 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700664 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000665 os.rmdir(self.cgi_dir)
666 os.rmdir(self.parent_dir)
667 finally:
668 BaseTestCase.tearDown(self)
669
Senthil Kumarand70846b2012-04-12 02:34:32 +0800670 def test_url_collapse_path(self):
671 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000672 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800673 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000674 '..': IndexError,
675 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800676 '/': '//',
677 '//': '//',
678 '/\\': '//\\',
679 '/.//': '//',
680 'cgi-bin/file1.py': '/cgi-bin/file1.py',
681 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
682 'a': '//a',
683 '/a': '//a',
684 '//a': '//a',
685 './a': '//a',
686 './C:/': '/C:/',
687 '/a/b': '/a/b',
688 '/a/b/': '/a/b/',
689 '/a/b/.': '/a/b/',
690 '/a/b/c/..': '/a/b/',
691 '/a/b/c/../d': '/a/b/d',
692 '/a/b/c/../d/e/../f': '/a/b/d/f',
693 '/a/b/c/../d/e/../../f': '/a/b/f',
694 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000695 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800696 '/a/b/c/../d/e/../../../f': '/a/f',
697 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000698 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800699 '/a/b/c/../d/e/../../../../f/..': '//',
700 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000701 }
702 for path, expected in test_vectors.items():
703 if isinstance(expected, type) and issubclass(expected, Exception):
704 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800705 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000706 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800707 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000708 self.assertEqual(expected, actual,
709 msg='path = %r\nGot: %r\nWanted: %r' %
710 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000711
Georg Brandlb533e262008-05-25 18:19:30 +0000712 def test_headers_and_content(self):
713 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200714 self.assertEqual(
715 (res.read(), res.getheader('Content-type'), res.status),
716 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000717
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400718 def test_issue19435(self):
719 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200720 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400721
Georg Brandlb533e262008-05-25 18:19:30 +0000722 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000723 params = urllib.parse.urlencode(
724 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000725 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
726 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
727
Antoine Pitroue768c392012-08-05 14:52:45 +0200728 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000729
730 def test_invaliduri(self):
731 res = self.request('/cgi-bin/invalid')
732 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200733 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000734
735 def test_authorization(self):
736 headers = {b'Authorization' : b'Basic ' +
737 base64.b64encode(b'username:pass')}
738 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200739 self.assertEqual(
740 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
741 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000742
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000743 def test_no_leading_slash(self):
744 # http://bugs.python.org/issue2254
745 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200746 self.assertEqual(
747 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
748 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000749
Senthil Kumaran42713722010-10-03 17:55:45 +0000750 def test_os_environ_is_not_altered(self):
751 signature = "Test CGI Server"
752 os.environ['SERVER_SOFTWARE'] = signature
753 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200754 self.assertEqual(
755 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
756 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000757 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
758
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700759 def test_urlquote_decoding_in_cgi_check(self):
760 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200761 self.assertEqual(
762 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
763 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700764
Ned Deily915a30f2014-07-12 22:06:26 -0700765 def test_nested_cgi_path_issue21323(self):
766 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200767 self.assertEqual(
768 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
769 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700770
Martin Pantera02e18a2015-10-03 05:38:07 +0000771 def test_query_with_multiple_question_mark(self):
772 res = self.request('/cgi-bin/file4.py?a=b?c=d')
773 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000774 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000775 (res.read(), res.getheader('Content-type'), res.status))
776
Martin Pantercb29e8c2015-10-03 05:55:46 +0000777 def test_query_with_continuous_slashes(self):
778 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
779 self.assertEqual(
780 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000781 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000782 (res.read(), res.getheader('Content-type'), res.status))
783
Georg Brandlb533e262008-05-25 18:19:30 +0000784
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000785class SocketlessRequestHandler(SimpleHTTPRequestHandler):
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200786 def __init__(self, *args, **kwargs):
787 request = mock.Mock()
788 request.makefile.return_value = BytesIO()
789 super().__init__(request, None, None)
790
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000791 self.get_called = False
792 self.protocol_version = "HTTP/1.1"
793
794 def do_GET(self):
795 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200796 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000797 self.send_header('Content-Type', 'text/html')
798 self.end_headers()
799 self.wfile.write(b'<html><body>Data</body></html>\r\n')
800
801 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000802 pass
803
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000804class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
805 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200806 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000807 return False
808
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800809
810class AuditableBytesIO:
811
812 def __init__(self):
813 self.datas = []
814
815 def write(self, data):
816 self.datas.append(data)
817
818 def getData(self):
819 return b''.join(self.datas)
820
821 @property
822 def numWrites(self):
823 return len(self.datas)
824
825
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000826class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200827 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000828
829 Test the support for the Expect 100-continue header.
830 """
831
832 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
833
834 def setUp (self):
835 self.handler = SocketlessRequestHandler()
836
837 def send_typical_request(self, message):
838 input = BytesIO(message)
839 output = BytesIO()
840 self.handler.rfile = input
841 self.handler.wfile = output
842 self.handler.handle_one_request()
843 output.seek(0)
844 return output.readlines()
845
846 def verify_get_called(self):
847 self.assertTrue(self.handler.get_called)
848
849 def verify_expected_headers(self, headers):
850 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
851 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
852
853 def verify_http_server_response(self, response):
854 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200855 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000856
857 def test_http_1_1(self):
858 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
859 self.verify_http_server_response(result[0])
860 self.verify_expected_headers(result[1:-1])
861 self.verify_get_called()
862 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500863 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
864 self.assertEqual(self.handler.command, 'GET')
865 self.assertEqual(self.handler.path, '/')
866 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
867 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000868
869 def test_http_1_0(self):
870 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
871 self.verify_http_server_response(result[0])
872 self.verify_expected_headers(result[1:-1])
873 self.verify_get_called()
874 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500875 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
876 self.assertEqual(self.handler.command, 'GET')
877 self.assertEqual(self.handler.path, '/')
878 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
879 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000880
881 def test_http_0_9(self):
882 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
883 self.assertEqual(len(result), 1)
884 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
885 self.verify_get_called()
886
Martin Pantere82338d2016-11-19 01:06:37 +0000887 def test_extra_space(self):
888 result = self.send_typical_request(
889 b'GET /spaced out HTTP/1.1\r\n'
890 b'Host: dummy\r\n'
891 b'\r\n'
892 )
893 self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
894 self.verify_expected_headers(result[1:result.index(b'\r\n')])
895 self.assertFalse(self.handler.get_called)
896
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000897 def test_with_continue_1_0(self):
898 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
899 self.verify_http_server_response(result[0])
900 self.verify_expected_headers(result[1:-1])
901 self.verify_get_called()
902 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500903 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
904 self.assertEqual(self.handler.command, 'GET')
905 self.assertEqual(self.handler.path, '/')
906 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
907 headers = (("Expect", "100-continue"),)
908 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000909
910 def test_with_continue_1_1(self):
911 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
912 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500913 self.assertEqual(result[1], b'\r\n')
914 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000915 self.verify_expected_headers(result[2:-1])
916 self.verify_get_called()
917 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500918 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
919 self.assertEqual(self.handler.command, 'GET')
920 self.assertEqual(self.handler.path, '/')
921 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
922 headers = (("Expect", "100-continue"),)
923 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000924
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800925 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000926
927 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800928 output = AuditableBytesIO()
929 handler = SocketlessRequestHandler()
930 handler.rfile = input
931 handler.wfile = output
932 handler.request_version = 'HTTP/1.1'
933 handler.requestline = ''
934 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000935
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800936 handler.send_error(418)
937 self.assertEqual(output.numWrites, 2)
938
939 def test_header_buffering_of_send_response_only(self):
940
941 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
942 output = AuditableBytesIO()
943 handler = SocketlessRequestHandler()
944 handler.rfile = input
945 handler.wfile = output
946 handler.request_version = 'HTTP/1.1'
947
948 handler.send_response_only(418)
949 self.assertEqual(output.numWrites, 0)
950 handler.end_headers()
951 self.assertEqual(output.numWrites, 1)
952
953 def test_header_buffering_of_send_header(self):
954
955 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
956 output = AuditableBytesIO()
957 handler = SocketlessRequestHandler()
958 handler.rfile = input
959 handler.wfile = output
960 handler.request_version = 'HTTP/1.1'
961
962 handler.send_header('Foo', 'foo')
963 handler.send_header('bar', 'bar')
964 self.assertEqual(output.numWrites, 0)
965 handler.end_headers()
966 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
967 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000968
969 def test_header_unbuffered_when_continue(self):
970
971 def _readAndReseek(f):
972 pos = f.tell()
973 f.seek(0)
974 data = f.read()
975 f.seek(pos)
976 return data
977
978 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
979 output = BytesIO()
980 self.handler.rfile = input
981 self.handler.wfile = output
982 self.handler.request_version = 'HTTP/1.1'
983
984 self.handler.handle_one_request()
985 self.assertNotEqual(_readAndReseek(output), b'')
986 result = _readAndReseek(output).split(b'\r\n')
987 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500988 self.assertEqual(result[1], b'')
989 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000990
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000991 def test_with_continue_rejected(self):
992 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
993 self.handler = RejectingSocketlessRequestHandler()
994 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
995 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
996 self.verify_expected_headers(result[1:-1])
997 # The expect handler should short circuit the usual get method by
998 # returning false here, so get_called should be false
999 self.assertFalse(self.handler.get_called)
1000 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
1001 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
1002
Antoine Pitrouc4924372010-12-16 16:48:36 +00001003 def test_request_length(self):
1004 # Issue #10714: huge request lines are discarded, to avoid Denial
1005 # of Service attacks.
1006 result = self.send_typical_request(b'GET ' + b'x' * 65537)
1007 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
1008 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001009 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001010
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001011 def test_header_length(self):
1012 # Issue #6791: same for headers
1013 result = self.send_typical_request(
1014 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +00001015 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001016 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001017 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1018
Martin Panteracc03192016-04-03 00:45:46 +00001019 def test_too_many_headers(self):
1020 result = self.send_typical_request(
1021 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
1022 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
1023 self.assertFalse(self.handler.get_called)
1024 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1025
Martin Panterda3bb382016-04-11 00:40:08 +00001026 def test_html_escape_on_error(self):
1027 result = self.send_typical_request(
1028 b'<script>alert("hello")</script> / HTTP/1.1')
1029 result = b''.join(result)
1030 text = '<script>alert("hello")</script>'
1031 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
1032
Benjamin Peterson70e28472015-02-17 21:11:10 -05001033 def test_close_connection(self):
1034 # handle_one_request() should be repeatedly called until
1035 # it sets close_connection
1036 def handle_one_request():
1037 self.handler.close_connection = next(close_values)
1038 self.handler.handle_one_request = handle_one_request
1039
1040 close_values = iter((True,))
1041 self.handler.handle()
1042 self.assertRaises(StopIteration, next, close_values)
1043
1044 close_values = iter((False, False, True))
1045 self.handler.handle()
1046 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001047
Berker Peksag04bc5b92016-03-14 06:06:03 +02001048 def test_date_time_string(self):
1049 now = time.time()
1050 # this is the old code that formats the timestamp
1051 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
1052 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
1053 self.handler.weekdayname[wd],
1054 day,
1055 self.handler.monthname[month],
1056 year, hh, mm, ss
1057 )
1058 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
1059
1060
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001061class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
1062 """ Test url parsing """
1063 def setUp(self):
1064 self.translated = os.getcwd()
1065 self.translated = os.path.join(self.translated, 'filename')
1066 self.handler = SocketlessRequestHandler()
1067
1068 def test_query_arguments(self):
1069 path = self.handler.translate_path('/filename')
1070 self.assertEqual(path, self.translated)
1071 path = self.handler.translate_path('/filename?foo=bar')
1072 self.assertEqual(path, self.translated)
1073 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
1074 self.assertEqual(path, self.translated)
1075
1076 def test_start_with_double_slash(self):
1077 path = self.handler.translate_path('//filename')
1078 self.assertEqual(path, self.translated)
1079 path = self.handler.translate_path('//filename?foo=bar')
1080 self.assertEqual(path, self.translated)
1081
Martin Panterd274b3f2016-04-18 03:45:18 +00001082 def test_windows_colon(self):
1083 with support.swap_attr(server.os, 'path', ntpath):
1084 path = self.handler.translate_path('c:c:c:foo/filename')
1085 path = path.replace(ntpath.sep, os.sep)
1086 self.assertEqual(path, self.translated)
1087
1088 path = self.handler.translate_path('\\c:../filename')
1089 path = path.replace(ntpath.sep, os.sep)
1090 self.assertEqual(path, self.translated)
1091
1092 path = self.handler.translate_path('c:\\c:..\\foo/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\\c:c:bar/filename')
1097 path = path.replace(ntpath.sep, os.sep)
1098 self.assertEqual(path, self.translated)
1099
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001100
Berker Peksag366c5702015-02-13 20:48:15 +02001101class MiscTestCase(unittest.TestCase):
1102 def test_all(self):
1103 expected = []
1104 blacklist = {'executable', 'nobody_uid', 'test'}
1105 for name in dir(server):
1106 if name.startswith('_') or name in blacklist:
1107 continue
1108 module_object = getattr(server, name)
1109 if getattr(module_object, '__module__', None) == 'http.server':
1110 expected.append(name)
1111 self.assertCountEqual(server.__all__, expected)
1112
1113
Georg Brandlb533e262008-05-25 18:19:30 +00001114def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001115 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001116 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001117 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001118 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001119 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001120 BaseHTTPServerTestCase,
1121 SimpleHTTPServerTestCase,
1122 CGIHTTPServerTestCase,
1123 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001124 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001125 )
Georg Brandlb533e262008-05-25 18:19:30 +00001126 finally:
1127 os.chdir(cwd)
1128
1129if __name__ == '__main__':
1130 test_main()