blob: 8357ee9145d7e5b17086592476be79e540e9a18c [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
Lisa Roach433433f2018-11-26 10:43:38 -080012import socket
Georg Brandlb533e262008-05-25 18:19:30 +000013import sys
Senthil Kumaran0f476d42010-09-30 06:09:18 +000014import re
Georg Brandlb533e262008-05-25 18:19:30 +000015import base64
Martin Panterd274b3f2016-04-18 03:45:18 +000016import ntpath
Georg Brandlb533e262008-05-25 18:19:30 +000017import shutil
Pierre Quentel351adda2017-04-02 12:26:12 +020018import email.message
19import email.utils
Serhiy Storchakacb5bc402014-08-17 08:22:11 +030020import html
Georg Brandl24420152008-05-26 16:32:26 +000021import http.client
Pierre Quentel351adda2017-04-02 12:26:12 +020022import urllib.parse
Georg Brandlb533e262008-05-25 18:19:30 +000023import tempfile
Berker Peksag04bc5b92016-03-14 06:06:03 +020024import time
Pierre Quentel351adda2017-04-02 12:26:12 +020025import datetime
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020026import threading
Stéphane Wirtela17a2f52017-05-24 09:29:06 +020027from unittest import mock
Senthil Kumaran0f476d42010-09-30 06:09:18 +000028from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000029
30import unittest
31from test import support
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020032
Georg Brandlb533e262008-05-25 18:19:30 +000033
Georg Brandlb533e262008-05-25 18:19:30 +000034class NoLogRequestHandler:
35 def log_message(self, *args):
36 # don't write log messages to stderr
37 pass
38
Barry Warsaw820c1202008-06-12 04:06:45 +000039 def read(self, n=None):
40 return ''
41
Georg Brandlb533e262008-05-25 18:19:30 +000042
43class TestServerThread(threading.Thread):
44 def __init__(self, test_object, request_handler):
45 threading.Thread.__init__(self)
46 self.request_handler = request_handler
47 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000048
49 def run(self):
Antoine Pitroucb342182011-03-21 00:26:51 +010050 self.server = HTTPServer(('localhost', 0), self.request_handler)
51 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000052 self.test_object.server_started.set()
53 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000054 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000055 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000056 finally:
57 self.server.server_close()
58
59 def stop(self):
60 self.server.shutdown()
Victor Stinner830d7d22017-08-22 18:05:07 +020061 self.join()
Georg Brandlb533e262008-05-25 18:19:30 +000062
63
64class BaseTestCase(unittest.TestCase):
65 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000066 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000067 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000068 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000069 self.thread = TestServerThread(self, self.request_handler)
70 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000071 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000072
73 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000074 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020075 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000076 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000077 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000078
79 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010080 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000081 self.connection.request(method, uri, body, headers)
82 return self.connection.getresponse()
83
84
85class BaseHTTPServerTestCase(BaseTestCase):
86 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
87 protocol_version = 'HTTP/1.1'
88 default_request_version = 'HTTP/1.1'
89
90 def do_TEST(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020091 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000092 self.send_header('Content-Type', 'text/html')
93 self.send_header('Connection', 'close')
94 self.end_headers()
95
96 def do_KEEP(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020097 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000098 self.send_header('Content-Type', 'text/html')
99 self.send_header('Connection', 'keep-alive')
100 self.end_headers()
101
102 def do_KEYERROR(self):
103 self.send_error(999)
104
Senthil Kumaran52d27202012-10-10 23:16:21 -0700105 def do_NOTFOUND(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200106 self.send_error(HTTPStatus.NOT_FOUND)
Senthil Kumaran52d27202012-10-10 23:16:21 -0700107
Senthil Kumaran26886442013-03-15 07:53:21 -0700108 def do_EXPLAINERROR(self):
109 self.send_error(999, "Short Message",
Martin Panter46f50722016-05-26 05:35:26 +0000110 "This is a long \n explanation")
Senthil Kumaran26886442013-03-15 07:53:21 -0700111
Georg Brandlb533e262008-05-25 18:19:30 +0000112 def do_CUSTOM(self):
113 self.send_response(999)
114 self.send_header('Content-Type', 'text/html')
115 self.send_header('Connection', 'close')
116 self.end_headers()
117
Armin Ronacher8d96d772011-01-22 13:13:05 +0000118 def do_LATINONEHEADER(self):
119 self.send_response(999)
120 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000121 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000122 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000123 body = self.headers['x-special-incoming'].encode('utf-8')
124 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000125
Martin Pantere42e1292016-06-08 08:29:13 +0000126 def do_SEND_ERROR(self):
127 self.send_error(int(self.path[1:]))
128
129 def do_HEAD(self):
130 self.send_error(int(self.path[1:]))
131
Georg Brandlb533e262008-05-25 18:19:30 +0000132 def setUp(self):
133 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100134 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000135 self.con.connect()
136
137 def test_command(self):
138 self.con.request('GET', '/')
139 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200140 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000141
142 def test_request_line_trimming(self):
143 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400144 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000145 self.con.endheaders()
146 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200147 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000148
149 def test_version_bogus(self):
150 self.con._http_vsn_str = 'FUBAR'
151 self.con.putrequest('GET', '/')
152 self.con.endheaders()
153 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200154 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000155
156 def test_version_digits(self):
157 self.con._http_vsn_str = 'HTTP/9.9.9'
158 self.con.putrequest('GET', '/')
159 self.con.endheaders()
160 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200161 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000162
163 def test_version_none_get(self):
164 self.con._http_vsn_str = ''
165 self.con.putrequest('GET', '/')
166 self.con.endheaders()
167 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200168 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000169
170 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400171 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000172 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400173 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000174 self.con.endheaders()
175 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200176 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000177
178 def test_version_invalid(self):
179 self.con._http_vsn = 99
180 self.con._http_vsn_str = 'HTTP/9.9'
181 self.con.putrequest('GET', '/')
182 self.con.endheaders()
183 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200184 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000185
186 def test_send_blank(self):
187 self.con._http_vsn_str = ''
188 self.con.putrequest('', '')
189 self.con.endheaders()
190 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200191 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000192
193 def test_header_close(self):
194 self.con.putrequest('GET', '/')
195 self.con.putheader('Connection', 'close')
196 self.con.endheaders()
197 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200198 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000199
Berker Peksag20853612016-08-25 01:13:34 +0300200 def test_header_keep_alive(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000201 self.con._http_vsn_str = 'HTTP/1.1'
202 self.con.putrequest('GET', '/')
203 self.con.putheader('Connection', 'keep-alive')
204 self.con.endheaders()
205 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200206 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000207
208 def test_handler(self):
209 self.con.request('TEST', '/')
210 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200211 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000212
213 def test_return_header_keep_alive(self):
214 self.con.request('KEEP', '/')
215 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000216 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000217 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000218 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000219
220 def test_internal_key_error(self):
221 self.con.request('KEYERROR', '/')
222 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000223 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000224
225 def test_return_custom_status(self):
226 self.con.request('CUSTOM', '/')
227 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000228 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000229
Senthil Kumaran26886442013-03-15 07:53:21 -0700230 def test_return_explain_error(self):
231 self.con.request('EXPLAINERROR', '/')
232 res = self.con.getresponse()
233 self.assertEqual(res.status, 999)
234 self.assertTrue(int(res.getheader('Content-Length')))
235
Armin Ronacher8d96d772011-01-22 13:13:05 +0000236 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000237 self.con.request('LATINONEHEADER', '/', headers={
238 'X-Special-Incoming': 'Ärger mit Unicode'
239 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000240 res = self.con.getresponse()
241 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000242 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000243
Senthil Kumaran52d27202012-10-10 23:16:21 -0700244 def test_error_content_length(self):
245 # Issue #16088: standard error responses should have a content-length
246 self.con.request('NOTFOUND', '/')
247 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200248 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
249
Senthil Kumaran52d27202012-10-10 23:16:21 -0700250 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700251 self.assertEqual(int(res.getheader('Content-Length')), len(data))
252
Martin Pantere42e1292016-06-08 08:29:13 +0000253 def test_send_error(self):
254 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
255 HTTPStatus.RESET_CONTENT)
256 for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
257 HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
258 HTTPStatus.SWITCHING_PROTOCOLS):
259 self.con.request('SEND_ERROR', '/{}'.format(code))
260 res = self.con.getresponse()
261 self.assertEqual(code, res.status)
262 self.assertEqual(None, res.getheader('Content-Length'))
263 self.assertEqual(None, res.getheader('Content-Type'))
264 if code not in allow_transfer_encoding_codes:
265 self.assertEqual(None, res.getheader('Transfer-Encoding'))
266
267 data = res.read()
268 self.assertEqual(b'', data)
269
270 def test_head_via_send_error(self):
271 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
272 HTTPStatus.RESET_CONTENT)
273 for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
274 HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
275 HTTPStatus.SWITCHING_PROTOCOLS):
276 self.con.request('HEAD', '/{}'.format(code))
277 res = self.con.getresponse()
278 self.assertEqual(code, res.status)
279 if code == HTTPStatus.OK:
280 self.assertTrue(int(res.getheader('Content-Length')) > 0)
281 self.assertIn('text/html', res.getheader('Content-Type'))
282 else:
283 self.assertEqual(None, res.getheader('Content-Length'))
284 self.assertEqual(None, res.getheader('Content-Type'))
285 if code not in allow_transfer_encoding_codes:
286 self.assertEqual(None, res.getheader('Transfer-Encoding'))
287
288 data = res.read()
289 self.assertEqual(b'', data)
290
Georg Brandlb533e262008-05-25 18:19:30 +0000291
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200292class RequestHandlerLoggingTestCase(BaseTestCase):
293 class request_handler(BaseHTTPRequestHandler):
294 protocol_version = 'HTTP/1.1'
295 default_request_version = 'HTTP/1.1'
296
297 def do_GET(self):
298 self.send_response(HTTPStatus.OK)
299 self.end_headers()
300
301 def do_ERROR(self):
302 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
303
304 def test_get(self):
305 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
306 self.con.connect()
307
308 with support.captured_stderr() as err:
309 self.con.request('GET', '/')
310 self.con.getresponse()
311
312 self.assertTrue(
313 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
314
315 def test_err(self):
316 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
317 self.con.connect()
318
319 with support.captured_stderr() as err:
320 self.con.request('ERROR', '/')
321 self.con.getresponse()
322
323 lines = err.getvalue().split('\n')
324 self.assertTrue(lines[0].endswith('code 404, message File not found'))
325 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
326
327
Georg Brandlb533e262008-05-25 18:19:30 +0000328class SimpleHTTPServerTestCase(BaseTestCase):
329 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
330 pass
331
332 def setUp(self):
333 BaseTestCase.setUp(self)
334 self.cwd = os.getcwd()
335 basetempdir = tempfile.gettempdir()
336 os.chdir(basetempdir)
337 self.data = b'We are the knights who say Ni!'
338 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
339 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panterfc475a92016-04-09 04:56:10 +0000340 self.base_url = '/' + self.tempdir_name
Victor Stinner28ce07a2017-07-28 18:15:02 +0200341 tempname = os.path.join(self.tempdir, 'test')
342 with open(tempname, 'wb') as temp:
Brett Cannon105df5d2010-10-29 23:43:42 +0000343 temp.write(self.data)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200344 temp.flush()
345 mtime = os.stat(tempname).st_mtime
Pierre Quentel351adda2017-04-02 12:26:12 +0200346 # compute last modification datetime for browser cache tests
347 last_modif = datetime.datetime.fromtimestamp(mtime,
348 datetime.timezone.utc)
349 self.last_modif_datetime = last_modif.replace(microsecond=0)
350 self.last_modif_header = email.utils.formatdate(
351 last_modif.timestamp(), usegmt=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000352
353 def tearDown(self):
354 try:
355 os.chdir(self.cwd)
356 try:
357 shutil.rmtree(self.tempdir)
358 except:
359 pass
360 finally:
361 BaseTestCase.tearDown(self)
362
363 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300364 def close_conn():
365 """Don't close reader yet so we can check if there was leftover
366 buffered input"""
367 nonlocal reader
368 reader = response.fp
369 response.fp = None
370 reader = None
371 response._close_conn = close_conn
372
Georg Brandlb533e262008-05-25 18:19:30 +0000373 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000374 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000375 self.assertEqual(response.status, status)
376 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000377 if data:
378 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300379 # Ensure the server has not set up a persistent connection, and has
380 # not sent any extra data
381 self.assertEqual(response.version, 10)
382 self.assertEqual(response.msg.get("Connection", "close"), "close")
383 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
384
385 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300386 return body
387
Ned Deilyb3edde82017-12-04 23:42:02 -0500388 @unittest.skipIf(sys.platform == 'darwin',
389 'undecodable name cannot always be decoded on macOS')
Steve Dowere58571b2016-09-08 11:11:13 -0700390 @unittest.skipIf(sys.platform == 'win32',
391 'undecodable name cannot be decoded on win32')
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300392 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
393 'need support.TESTFN_UNDECODABLE')
394 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300395 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300396 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
397 with open(os.path.join(self.tempdir, filename), 'wb') as f:
398 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000399 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300400 if sys.platform == 'darwin':
401 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
402 # UTF-8 into a percent-encoded value.
403 for name in os.listdir(self.tempdir):
404 if name != 'test': # Ignore a filename created in setUp().
405 filename = name
406 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200407 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300408 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
409 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300410 .encode(enc, 'surrogateescape'), body)
Martin Panterda3bb382016-04-11 00:40:08 +0000411 self.assertIn(('>%s<' % html.escape(filename, quote=False))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300412 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000413 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200414 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300415 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000416
417 def test_get(self):
418 #constructs the path relative to the root directory of the HTTPServer
Martin Panterfc475a92016-04-09 04:56:10 +0000419 response = self.request(self.base_url + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200420 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700421 # check for trailing "/" which should return 404. See Issue17324
Martin Panterfc475a92016-04-09 04:56:10 +0000422 response = self.request(self.base_url + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200423 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
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.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000426 response = self.request(self.base_url)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200427 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000428 response = self.request(self.base_url + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200429 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000430 response = self.request(self.base_url + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200431 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600432 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000433 self.base_url + "/?hi=1")
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)
Georg Brandlb533e262008-05-25 18:19:30 +0000436 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200437 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300438
439 data = b"Dummy index file\r\n"
440 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
441 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000442 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300443 self.check_status_and_reason(response, HTTPStatus.OK, data)
444
445 # chmod() doesn't work as expected on Windows, and filesystem
446 # permissions are ignored by root on Unix.
447 if os.name == 'posix' and os.geteuid() != 0:
448 os.chmod(self.tempdir, 0)
449 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000450 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200451 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300452 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000453 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000454
455 def test_head(self):
456 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000457 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200458 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000459 self.assertEqual(response.getheader('content-length'),
460 str(len(self.data)))
461 self.assertEqual(response.getheader('content-type'),
462 'application/octet-stream')
463
Pierre Quentel351adda2017-04-02 12:26:12 +0200464 def test_browser_cache(self):
465 """Check that when a request to /test is sent with the request header
466 If-Modified-Since set to date of last modification, the server returns
467 status code 304, not 200
468 """
469 headers = email.message.Message()
470 headers['If-Modified-Since'] = self.last_modif_header
471 response = self.request(self.base_url + '/test', headers=headers)
472 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
473
474 # one hour after last modification : must return 304
475 new_dt = self.last_modif_datetime + datetime.timedelta(hours=1)
476 headers = email.message.Message()
477 headers['If-Modified-Since'] = email.utils.format_datetime(new_dt,
478 usegmt=True)
479 response = self.request(self.base_url + '/test', headers=headers)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200480 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
Pierre Quentel351adda2017-04-02 12:26:12 +0200481
482 def test_browser_cache_file_changed(self):
483 # with If-Modified-Since earlier than Last-Modified, must return 200
484 dt = self.last_modif_datetime
485 # build datetime object : 365 days before last modification
486 old_dt = dt - datetime.timedelta(days=365)
487 headers = email.message.Message()
488 headers['If-Modified-Since'] = email.utils.format_datetime(old_dt,
489 usegmt=True)
490 response = self.request(self.base_url + '/test', headers=headers)
491 self.check_status_and_reason(response, HTTPStatus.OK)
492
493 def test_browser_cache_with_If_None_Match_header(self):
494 # if If-None-Match header is present, ignore If-Modified-Since
495
496 headers = email.message.Message()
497 headers['If-Modified-Since'] = self.last_modif_header
498 headers['If-None-Match'] = "*"
499 response = self.request(self.base_url + '/test', headers=headers)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200500 self.check_status_and_reason(response, HTTPStatus.OK)
Pierre Quentel351adda2017-04-02 12:26:12 +0200501
Georg Brandlb533e262008-05-25 18:19:30 +0000502 def test_invalid_requests(self):
503 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200504 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000505 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400506 response = self.request('/', method='custom')
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 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200509 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000510
Pierre Quentel351adda2017-04-02 12:26:12 +0200511 def test_last_modified(self):
512 """Checks that the datetime returned in Last-Modified response header
513 is the actual datetime of last modification, rounded to the second
514 """
515 response = self.request(self.base_url + '/test')
516 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
517 last_modif_header = response.headers['Last-modified']
518 self.assertEqual(last_modif_header, self.last_modif_header)
519
Martin Panterfc475a92016-04-09 04:56:10 +0000520 def test_path_without_leading_slash(self):
521 response = self.request(self.tempdir_name + '/test')
522 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
523 response = self.request(self.tempdir_name + '/test/')
524 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
525 response = self.request(self.tempdir_name + '/')
526 self.check_status_and_reason(response, HTTPStatus.OK)
527 response = self.request(self.tempdir_name)
528 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
529 response = self.request(self.tempdir_name + '/?hi=2')
530 self.check_status_and_reason(response, HTTPStatus.OK)
531 response = self.request(self.tempdir_name + '?hi=1')
532 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
533 self.assertEqual(response.getheader("Location"),
534 self.tempdir_name + "/?hi=1")
535
Martin Panterda3bb382016-04-11 00:40:08 +0000536 def test_html_escape_filename(self):
537 filename = '<test&>.txt'
538 fullpath = os.path.join(self.tempdir, filename)
539
540 try:
541 open(fullpath, 'w').close()
542 except OSError:
543 raise unittest.SkipTest('Can not create file %s on current file '
544 'system' % filename)
545
546 try:
547 response = self.request(self.base_url + '/')
548 body = self.check_status_and_reason(response, HTTPStatus.OK)
549 enc = response.headers.get_content_charset()
550 finally:
551 os.unlink(fullpath) # avoid affecting test_undecodable_filename
552
553 self.assertIsNotNone(enc)
554 html_text = '>%s<' % html.escape(filename, quote=False)
555 self.assertIn(html_text.encode(enc), body)
556
Georg Brandlb533e262008-05-25 18:19:30 +0000557
558cgi_file1 = """\
559#!%s
560
561print("Content-type: text/html")
562print()
563print("Hello World")
564"""
565
566cgi_file2 = """\
567#!%s
568import cgi
569
570print("Content-type: text/html")
571print()
572
573form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000574print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
575 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000576"""
577
Martin Pantera02e18a2015-10-03 05:38:07 +0000578cgi_file4 = """\
579#!%s
580import os
581
582print("Content-type: text/html")
583print()
584
585print(os.environ["%s"])
586"""
587
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100588
589@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
590 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000591class CGIHTTPServerTestCase(BaseTestCase):
592 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
593 pass
594
Antoine Pitroue768c392012-08-05 14:52:45 +0200595 linesep = os.linesep.encode('ascii')
596
Georg Brandlb533e262008-05-25 18:19:30 +0000597 def setUp(self):
598 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000599 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000600 self.parent_dir = tempfile.mkdtemp()
601 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700602 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000603 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700604 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400605 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000606 self.file1_path = None
607 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700608 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000609 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000610
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000611 # The shebang line should be pure ASCII: use symlink if possible.
612 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000613 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000614 self.pythonexe = os.path.join(self.parent_dir, 'python')
615 os.symlink(sys.executable, self.pythonexe)
616 else:
617 self.pythonexe = sys.executable
618
Victor Stinner3218c312010-10-17 20:13:36 +0000619 try:
620 # The python executable path is written as the first line of the
621 # CGI Python script. The encoding cookie cannot be used, and so the
622 # path should be encodable to the default script encoding (utf-8)
623 self.pythonexe.encode('utf-8')
624 except UnicodeEncodeError:
625 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200626 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000627
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400628 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
629 with open(self.nocgi_path, 'w') as fp:
630 fp.write(cgi_file1 % self.pythonexe)
631 os.chmod(self.nocgi_path, 0o777)
632
Georg Brandlb533e262008-05-25 18:19:30 +0000633 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000634 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000635 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000636 os.chmod(self.file1_path, 0o777)
637
638 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000639 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000640 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000641 os.chmod(self.file2_path, 0o777)
642
Ned Deily915a30f2014-07-12 22:06:26 -0700643 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
644 with open(self.file3_path, 'w', encoding='utf-8') as file3:
645 file3.write(cgi_file1 % self.pythonexe)
646 os.chmod(self.file3_path, 0o777)
647
Martin Pantera02e18a2015-10-03 05:38:07 +0000648 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
649 with open(self.file4_path, 'w', encoding='utf-8') as file4:
650 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
651 os.chmod(self.file4_path, 0o777)
652
Georg Brandlb533e262008-05-25 18:19:30 +0000653 os.chdir(self.parent_dir)
654
655 def tearDown(self):
656 try:
657 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000658 if self.pythonexe != sys.executable:
659 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400660 if self.nocgi_path:
661 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000662 if self.file1_path:
663 os.remove(self.file1_path)
664 if self.file2_path:
665 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700666 if self.file3_path:
667 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000668 if self.file4_path:
669 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700670 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000671 os.rmdir(self.cgi_dir)
672 os.rmdir(self.parent_dir)
673 finally:
674 BaseTestCase.tearDown(self)
675
Senthil Kumarand70846b2012-04-12 02:34:32 +0800676 def test_url_collapse_path(self):
677 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000678 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800679 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000680 '..': IndexError,
681 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800682 '/': '//',
683 '//': '//',
684 '/\\': '//\\',
685 '/.//': '//',
686 'cgi-bin/file1.py': '/cgi-bin/file1.py',
687 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
688 'a': '//a',
689 '/a': '//a',
690 '//a': '//a',
691 './a': '//a',
692 './C:/': '/C:/',
693 '/a/b': '/a/b',
694 '/a/b/': '/a/b/',
695 '/a/b/.': '/a/b/',
696 '/a/b/c/..': '/a/b/',
697 '/a/b/c/../d': '/a/b/d',
698 '/a/b/c/../d/e/../f': '/a/b/d/f',
699 '/a/b/c/../d/e/../../f': '/a/b/f',
700 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000701 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800702 '/a/b/c/../d/e/../../../f': '/a/f',
703 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000704 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800705 '/a/b/c/../d/e/../../../../f/..': '//',
706 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000707 }
708 for path, expected in test_vectors.items():
709 if isinstance(expected, type) and issubclass(expected, Exception):
710 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800711 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000712 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800713 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000714 self.assertEqual(expected, actual,
715 msg='path = %r\nGot: %r\nWanted: %r' %
716 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000717
Georg Brandlb533e262008-05-25 18:19:30 +0000718 def test_headers_and_content(self):
719 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200720 self.assertEqual(
721 (res.read(), res.getheader('Content-type'), res.status),
722 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000723
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400724 def test_issue19435(self):
725 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200726 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400727
Georg Brandlb533e262008-05-25 18:19:30 +0000728 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000729 params = urllib.parse.urlencode(
730 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000731 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
732 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
733
Antoine Pitroue768c392012-08-05 14:52:45 +0200734 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000735
736 def test_invaliduri(self):
737 res = self.request('/cgi-bin/invalid')
738 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200739 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000740
741 def test_authorization(self):
742 headers = {b'Authorization' : b'Basic ' +
743 base64.b64encode(b'username:pass')}
744 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200745 self.assertEqual(
746 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
747 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000748
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000749 def test_no_leading_slash(self):
750 # http://bugs.python.org/issue2254
751 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200752 self.assertEqual(
753 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
754 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000755
Senthil Kumaran42713722010-10-03 17:55:45 +0000756 def test_os_environ_is_not_altered(self):
757 signature = "Test CGI Server"
758 os.environ['SERVER_SOFTWARE'] = signature
759 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200760 self.assertEqual(
761 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
762 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000763 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
764
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700765 def test_urlquote_decoding_in_cgi_check(self):
766 res = self.request('/cgi-bin%2ffile1.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))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700770
Ned Deily915a30f2014-07-12 22:06:26 -0700771 def test_nested_cgi_path_issue21323(self):
772 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200773 self.assertEqual(
774 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
775 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700776
Martin Pantera02e18a2015-10-03 05:38:07 +0000777 def test_query_with_multiple_question_mark(self):
778 res = self.request('/cgi-bin/file4.py?a=b?c=d')
779 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000780 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000781 (res.read(), res.getheader('Content-type'), res.status))
782
Martin Pantercb29e8c2015-10-03 05:55:46 +0000783 def test_query_with_continuous_slashes(self):
784 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
785 self.assertEqual(
786 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000787 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000788 (res.read(), res.getheader('Content-type'), res.status))
789
Georg Brandlb533e262008-05-25 18:19:30 +0000790
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000791class SocketlessRequestHandler(SimpleHTTPRequestHandler):
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200792 def __init__(self, *args, **kwargs):
793 request = mock.Mock()
794 request.makefile.return_value = BytesIO()
795 super().__init__(request, None, None)
796
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000797 self.get_called = False
798 self.protocol_version = "HTTP/1.1"
799
800 def do_GET(self):
801 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200802 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000803 self.send_header('Content-Type', 'text/html')
804 self.end_headers()
805 self.wfile.write(b'<html><body>Data</body></html>\r\n')
806
807 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000808 pass
809
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000810class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
811 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200812 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000813 return False
814
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800815
816class AuditableBytesIO:
817
818 def __init__(self):
819 self.datas = []
820
821 def write(self, data):
822 self.datas.append(data)
823
824 def getData(self):
825 return b''.join(self.datas)
826
827 @property
828 def numWrites(self):
829 return len(self.datas)
830
831
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000832class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200833 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000834
835 Test the support for the Expect 100-continue header.
836 """
837
838 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
839
840 def setUp (self):
841 self.handler = SocketlessRequestHandler()
842
843 def send_typical_request(self, message):
844 input = BytesIO(message)
845 output = BytesIO()
846 self.handler.rfile = input
847 self.handler.wfile = output
848 self.handler.handle_one_request()
849 output.seek(0)
850 return output.readlines()
851
852 def verify_get_called(self):
853 self.assertTrue(self.handler.get_called)
854
855 def verify_expected_headers(self, headers):
856 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
857 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
858
859 def verify_http_server_response(self, response):
860 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200861 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000862
863 def test_http_1_1(self):
864 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
865 self.verify_http_server_response(result[0])
866 self.verify_expected_headers(result[1:-1])
867 self.verify_get_called()
868 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500869 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
870 self.assertEqual(self.handler.command, 'GET')
871 self.assertEqual(self.handler.path, '/')
872 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
873 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000874
875 def test_http_1_0(self):
876 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
877 self.verify_http_server_response(result[0])
878 self.verify_expected_headers(result[1:-1])
879 self.verify_get_called()
880 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500881 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
882 self.assertEqual(self.handler.command, 'GET')
883 self.assertEqual(self.handler.path, '/')
884 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
885 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000886
887 def test_http_0_9(self):
888 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
889 self.assertEqual(len(result), 1)
890 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
891 self.verify_get_called()
892
Martin Pantere82338d2016-11-19 01:06:37 +0000893 def test_extra_space(self):
894 result = self.send_typical_request(
895 b'GET /spaced out HTTP/1.1\r\n'
896 b'Host: dummy\r\n'
897 b'\r\n'
898 )
899 self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
900 self.verify_expected_headers(result[1:result.index(b'\r\n')])
901 self.assertFalse(self.handler.get_called)
902
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000903 def test_with_continue_1_0(self):
904 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
905 self.verify_http_server_response(result[0])
906 self.verify_expected_headers(result[1:-1])
907 self.verify_get_called()
908 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500909 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
910 self.assertEqual(self.handler.command, 'GET')
911 self.assertEqual(self.handler.path, '/')
912 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
913 headers = (("Expect", "100-continue"),)
914 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000915
916 def test_with_continue_1_1(self):
917 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
918 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500919 self.assertEqual(result[1], b'\r\n')
920 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000921 self.verify_expected_headers(result[2:-1])
922 self.verify_get_called()
923 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500924 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
925 self.assertEqual(self.handler.command, 'GET')
926 self.assertEqual(self.handler.path, '/')
927 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
928 headers = (("Expect", "100-continue"),)
929 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000930
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800931 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000932
933 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800934 output = AuditableBytesIO()
935 handler = SocketlessRequestHandler()
936 handler.rfile = input
937 handler.wfile = output
938 handler.request_version = 'HTTP/1.1'
939 handler.requestline = ''
940 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000941
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800942 handler.send_error(418)
943 self.assertEqual(output.numWrites, 2)
944
945 def test_header_buffering_of_send_response_only(self):
946
947 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
948 output = AuditableBytesIO()
949 handler = SocketlessRequestHandler()
950 handler.rfile = input
951 handler.wfile = output
952 handler.request_version = 'HTTP/1.1'
953
954 handler.send_response_only(418)
955 self.assertEqual(output.numWrites, 0)
956 handler.end_headers()
957 self.assertEqual(output.numWrites, 1)
958
959 def test_header_buffering_of_send_header(self):
960
961 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
962 output = AuditableBytesIO()
963 handler = SocketlessRequestHandler()
964 handler.rfile = input
965 handler.wfile = output
966 handler.request_version = 'HTTP/1.1'
967
968 handler.send_header('Foo', 'foo')
969 handler.send_header('bar', 'bar')
970 self.assertEqual(output.numWrites, 0)
971 handler.end_headers()
972 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
973 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000974
975 def test_header_unbuffered_when_continue(self):
976
977 def _readAndReseek(f):
978 pos = f.tell()
979 f.seek(0)
980 data = f.read()
981 f.seek(pos)
982 return data
983
984 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
985 output = BytesIO()
986 self.handler.rfile = input
987 self.handler.wfile = output
988 self.handler.request_version = 'HTTP/1.1'
989
990 self.handler.handle_one_request()
991 self.assertNotEqual(_readAndReseek(output), b'')
992 result = _readAndReseek(output).split(b'\r\n')
993 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500994 self.assertEqual(result[1], b'')
995 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000996
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000997 def test_with_continue_rejected(self):
998 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
999 self.handler = RejectingSocketlessRequestHandler()
1000 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
1001 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
1002 self.verify_expected_headers(result[1:-1])
1003 # The expect handler should short circuit the usual get method by
1004 # returning false here, so get_called should be false
1005 self.assertFalse(self.handler.get_called)
1006 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
1007 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
1008
Antoine Pitrouc4924372010-12-16 16:48:36 +00001009 def test_request_length(self):
1010 # Issue #10714: huge request lines are discarded, to avoid Denial
1011 # of Service attacks.
1012 result = self.send_typical_request(b'GET ' + b'x' * 65537)
1013 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
1014 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001015 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001016
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001017 def test_header_length(self):
1018 # Issue #6791: same for headers
1019 result = self.send_typical_request(
1020 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +00001021 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001022 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001023 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1024
Martin Panteracc03192016-04-03 00:45:46 +00001025 def test_too_many_headers(self):
1026 result = self.send_typical_request(
1027 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
1028 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
1029 self.assertFalse(self.handler.get_called)
1030 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1031
Martin Panterda3bb382016-04-11 00:40:08 +00001032 def test_html_escape_on_error(self):
1033 result = self.send_typical_request(
1034 b'<script>alert("hello")</script> / HTTP/1.1')
1035 result = b''.join(result)
1036 text = '<script>alert("hello")</script>'
1037 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
1038
Benjamin Peterson70e28472015-02-17 21:11:10 -05001039 def test_close_connection(self):
1040 # handle_one_request() should be repeatedly called until
1041 # it sets close_connection
1042 def handle_one_request():
1043 self.handler.close_connection = next(close_values)
1044 self.handler.handle_one_request = handle_one_request
1045
1046 close_values = iter((True,))
1047 self.handler.handle()
1048 self.assertRaises(StopIteration, next, close_values)
1049
1050 close_values = iter((False, False, True))
1051 self.handler.handle()
1052 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001053
Berker Peksag04bc5b92016-03-14 06:06:03 +02001054 def test_date_time_string(self):
1055 now = time.time()
1056 # this is the old code that formats the timestamp
1057 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
1058 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
1059 self.handler.weekdayname[wd],
1060 day,
1061 self.handler.monthname[month],
1062 year, hh, mm, ss
1063 )
1064 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
1065
1066
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001067class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
1068 """ Test url parsing """
1069 def setUp(self):
1070 self.translated = os.getcwd()
1071 self.translated = os.path.join(self.translated, 'filename')
1072 self.handler = SocketlessRequestHandler()
1073
1074 def test_query_arguments(self):
1075 path = self.handler.translate_path('/filename')
1076 self.assertEqual(path, self.translated)
1077 path = self.handler.translate_path('/filename?foo=bar')
1078 self.assertEqual(path, self.translated)
1079 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
1080 self.assertEqual(path, self.translated)
1081
1082 def test_start_with_double_slash(self):
1083 path = self.handler.translate_path('//filename')
1084 self.assertEqual(path, self.translated)
1085 path = self.handler.translate_path('//filename?foo=bar')
1086 self.assertEqual(path, self.translated)
1087
Martin Panterd274b3f2016-04-18 03:45:18 +00001088 def test_windows_colon(self):
1089 with support.swap_attr(server.os, 'path', ntpath):
1090 path = self.handler.translate_path('c:c:c:foo/filename')
1091 path = path.replace(ntpath.sep, os.sep)
1092 self.assertEqual(path, self.translated)
1093
1094 path = self.handler.translate_path('\\c:../filename')
1095 path = path.replace(ntpath.sep, os.sep)
1096 self.assertEqual(path, self.translated)
1097
1098 path = self.handler.translate_path('c:\\c:..\\foo/filename')
1099 path = path.replace(ntpath.sep, os.sep)
1100 self.assertEqual(path, self.translated)
1101
1102 path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
1103 path = path.replace(ntpath.sep, os.sep)
1104 self.assertEqual(path, self.translated)
1105
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001106
Berker Peksag366c5702015-02-13 20:48:15 +02001107class MiscTestCase(unittest.TestCase):
1108 def test_all(self):
1109 expected = []
1110 blacklist = {'executable', 'nobody_uid', 'test'}
1111 for name in dir(server):
1112 if name.startswith('_') or name in blacklist:
1113 continue
1114 module_object = getattr(server, name)
1115 if getattr(module_object, '__module__', None) == 'http.server':
1116 expected.append(name)
1117 self.assertCountEqual(server.__all__, expected)
1118
1119
Lisa Roach433433f2018-11-26 10:43:38 -08001120class ScriptTestCase(unittest.TestCase):
Jason R. Coombsf2890842019-02-07 08:22:45 -05001121
1122 def mock_server_class(self):
1123 return mock.MagicMock(
1124 return_value=mock.MagicMock(
1125 __enter__=mock.MagicMock(
1126 return_value=mock.MagicMock(
1127 socket=mock.MagicMock(
1128 getsockname=lambda: ('', 0),
1129 ),
1130 ),
1131 ),
1132 ),
1133 )
1134
1135 @mock.patch('builtins.print')
1136 def test_server_test_unspec(self, _):
1137 mock_server = self.mock_server_class()
1138 server.test(ServerClass=mock_server, bind=None)
1139 self.assertIn(
1140 mock_server.address_family,
1141 (socket.AF_INET6, socket.AF_INET),
1142 )
1143
1144 @mock.patch('builtins.print')
1145 def test_server_test_localhost(self, _):
1146 mock_server = self.mock_server_class()
1147 server.test(ServerClass=mock_server, bind="localhost")
1148 self.assertIn(
1149 mock_server.address_family,
1150 (socket.AF_INET6, socket.AF_INET),
1151 )
1152
1153 ipv6_addrs = (
1154 "::",
1155 "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
1156 "::1",
1157 )
1158
1159 ipv4_addrs = (
1160 "0.0.0.0",
1161 "8.8.8.8",
1162 "127.0.0.1",
1163 )
1164
Lisa Roach433433f2018-11-26 10:43:38 -08001165 @mock.patch('builtins.print')
1166 def test_server_test_ipv6(self, _):
Jason R. Coombsf2890842019-02-07 08:22:45 -05001167 for bind in self.ipv6_addrs:
1168 mock_server = self.mock_server_class()
1169 server.test(ServerClass=mock_server, bind=bind)
1170 self.assertEqual(mock_server.address_family, socket.AF_INET6)
Lisa Roach433433f2018-11-26 10:43:38 -08001171
Jason R. Coombsf2890842019-02-07 08:22:45 -05001172 @mock.patch('builtins.print')
1173 def test_server_test_ipv4(self, _):
1174 for bind in self.ipv4_addrs:
1175 mock_server = self.mock_server_class()
1176 server.test(ServerClass=mock_server, bind=bind)
1177 self.assertEqual(mock_server.address_family, socket.AF_INET)
Lisa Roach433433f2018-11-26 10:43:38 -08001178
1179
Georg Brandlb533e262008-05-25 18:19:30 +00001180def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001181 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001182 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001183 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001184 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001185 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001186 BaseHTTPServerTestCase,
1187 SimpleHTTPServerTestCase,
1188 CGIHTTPServerTestCase,
1189 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001190 MiscTestCase,
Lisa Roach433433f2018-11-26 10:43:38 -08001191 ScriptTestCase
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001192 )
Georg Brandlb533e262008-05-25 18:19:30 +00001193 finally:
1194 os.chdir(cwd)
1195
1196if __name__ == '__main__':
1197 test_main()