blob: 8cddcdc43843ad150300375012bbe61a1506cc2b [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()
Victor Stinner830d7d22017-08-22 18:05:07 +020059 self.join()
Georg Brandlb533e262008-05-25 18:19:30 +000060
61
62class BaseTestCase(unittest.TestCase):
63 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000064 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000065 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000066 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000067 self.thread = TestServerThread(self, self.request_handler)
68 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000069 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000070
71 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000072 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020073 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000074 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000075 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000076
77 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010078 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000079 self.connection.request(method, uri, body, headers)
80 return self.connection.getresponse()
81
82
83class BaseHTTPServerTestCase(BaseTestCase):
84 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
85 protocol_version = 'HTTP/1.1'
86 default_request_version = 'HTTP/1.1'
87
88 def do_TEST(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020089 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000090 self.send_header('Content-Type', 'text/html')
91 self.send_header('Connection', 'close')
92 self.end_headers()
93
94 def do_KEEP(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020095 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000096 self.send_header('Content-Type', 'text/html')
97 self.send_header('Connection', 'keep-alive')
98 self.end_headers()
99
100 def do_KEYERROR(self):
101 self.send_error(999)
102
Senthil Kumaran52d27202012-10-10 23:16:21 -0700103 def do_NOTFOUND(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200104 self.send_error(HTTPStatus.NOT_FOUND)
Senthil Kumaran52d27202012-10-10 23:16:21 -0700105
Senthil Kumaran26886442013-03-15 07:53:21 -0700106 def do_EXPLAINERROR(self):
107 self.send_error(999, "Short Message",
Martin Panter46f50722016-05-26 05:35:26 +0000108 "This is a long \n explanation")
Senthil Kumaran26886442013-03-15 07:53:21 -0700109
Georg Brandlb533e262008-05-25 18:19:30 +0000110 def do_CUSTOM(self):
111 self.send_response(999)
112 self.send_header('Content-Type', 'text/html')
113 self.send_header('Connection', 'close')
114 self.end_headers()
115
Armin Ronacher8d96d772011-01-22 13:13:05 +0000116 def do_LATINONEHEADER(self):
117 self.send_response(999)
118 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000119 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000120 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000121 body = self.headers['x-special-incoming'].encode('utf-8')
122 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000123
Martin Pantere42e1292016-06-08 08:29:13 +0000124 def do_SEND_ERROR(self):
125 self.send_error(int(self.path[1:]))
126
127 def do_HEAD(self):
128 self.send_error(int(self.path[1:]))
129
Georg Brandlb533e262008-05-25 18:19:30 +0000130 def setUp(self):
131 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100132 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000133 self.con.connect()
134
135 def test_command(self):
136 self.con.request('GET', '/')
137 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200138 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000139
140 def test_request_line_trimming(self):
141 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400142 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000143 self.con.endheaders()
144 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200145 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000146
147 def test_version_bogus(self):
148 self.con._http_vsn_str = 'FUBAR'
149 self.con.putrequest('GET', '/')
150 self.con.endheaders()
151 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200152 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000153
154 def test_version_digits(self):
155 self.con._http_vsn_str = 'HTTP/9.9.9'
156 self.con.putrequest('GET', '/')
157 self.con.endheaders()
158 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200159 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000160
161 def test_version_none_get(self):
162 self.con._http_vsn_str = ''
163 self.con.putrequest('GET', '/')
164 self.con.endheaders()
165 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200166 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000167
168 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400169 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000170 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400171 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000172 self.con.endheaders()
173 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200174 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000175
176 def test_version_invalid(self):
177 self.con._http_vsn = 99
178 self.con._http_vsn_str = 'HTTP/9.9'
179 self.con.putrequest('GET', '/')
180 self.con.endheaders()
181 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200182 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000183
184 def test_send_blank(self):
185 self.con._http_vsn_str = ''
186 self.con.putrequest('', '')
187 self.con.endheaders()
188 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200189 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000190
191 def test_header_close(self):
192 self.con.putrequest('GET', '/')
193 self.con.putheader('Connection', 'close')
194 self.con.endheaders()
195 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200196 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000197
Berker Peksag20853612016-08-25 01:13:34 +0300198 def test_header_keep_alive(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000199 self.con._http_vsn_str = 'HTTP/1.1'
200 self.con.putrequest('GET', '/')
201 self.con.putheader('Connection', 'keep-alive')
202 self.con.endheaders()
203 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200204 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000205
206 def test_handler(self):
207 self.con.request('TEST', '/')
208 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200209 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000210
211 def test_return_header_keep_alive(self):
212 self.con.request('KEEP', '/')
213 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000214 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000215 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000216 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000217
218 def test_internal_key_error(self):
219 self.con.request('KEYERROR', '/')
220 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000221 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000222
223 def test_return_custom_status(self):
224 self.con.request('CUSTOM', '/')
225 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000226 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000227
Senthil Kumaran26886442013-03-15 07:53:21 -0700228 def test_return_explain_error(self):
229 self.con.request('EXPLAINERROR', '/')
230 res = self.con.getresponse()
231 self.assertEqual(res.status, 999)
232 self.assertTrue(int(res.getheader('Content-Length')))
233
Armin Ronacher8d96d772011-01-22 13:13:05 +0000234 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000235 self.con.request('LATINONEHEADER', '/', headers={
236 'X-Special-Incoming': 'Ärger mit Unicode'
237 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000238 res = self.con.getresponse()
239 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000240 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000241
Senthil Kumaran52d27202012-10-10 23:16:21 -0700242 def test_error_content_length(self):
243 # Issue #16088: standard error responses should have a content-length
244 self.con.request('NOTFOUND', '/')
245 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200246 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
247
Senthil Kumaran52d27202012-10-10 23:16:21 -0700248 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700249 self.assertEqual(int(res.getheader('Content-Length')), len(data))
250
Martin Pantere42e1292016-06-08 08:29:13 +0000251 def test_send_error(self):
252 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
253 HTTPStatus.RESET_CONTENT)
254 for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
255 HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
256 HTTPStatus.SWITCHING_PROTOCOLS):
257 self.con.request('SEND_ERROR', '/{}'.format(code))
258 res = self.con.getresponse()
259 self.assertEqual(code, res.status)
260 self.assertEqual(None, res.getheader('Content-Length'))
261 self.assertEqual(None, res.getheader('Content-Type'))
262 if code not in allow_transfer_encoding_codes:
263 self.assertEqual(None, res.getheader('Transfer-Encoding'))
264
265 data = res.read()
266 self.assertEqual(b'', data)
267
268 def test_head_via_send_error(self):
269 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
270 HTTPStatus.RESET_CONTENT)
271 for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
272 HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
273 HTTPStatus.SWITCHING_PROTOCOLS):
274 self.con.request('HEAD', '/{}'.format(code))
275 res = self.con.getresponse()
276 self.assertEqual(code, res.status)
277 if code == HTTPStatus.OK:
278 self.assertTrue(int(res.getheader('Content-Length')) > 0)
279 self.assertIn('text/html', res.getheader('Content-Type'))
280 else:
281 self.assertEqual(None, res.getheader('Content-Length'))
282 self.assertEqual(None, res.getheader('Content-Type'))
283 if code not in allow_transfer_encoding_codes:
284 self.assertEqual(None, res.getheader('Transfer-Encoding'))
285
286 data = res.read()
287 self.assertEqual(b'', data)
288
Georg Brandlb533e262008-05-25 18:19:30 +0000289
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200290class RequestHandlerLoggingTestCase(BaseTestCase):
291 class request_handler(BaseHTTPRequestHandler):
292 protocol_version = 'HTTP/1.1'
293 default_request_version = 'HTTP/1.1'
294
295 def do_GET(self):
296 self.send_response(HTTPStatus.OK)
297 self.end_headers()
298
299 def do_ERROR(self):
300 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
301
302 def test_get(self):
303 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
304 self.con.connect()
305
306 with support.captured_stderr() as err:
307 self.con.request('GET', '/')
308 self.con.getresponse()
309
310 self.assertTrue(
311 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
312
313 def test_err(self):
314 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
315 self.con.connect()
316
317 with support.captured_stderr() as err:
318 self.con.request('ERROR', '/')
319 self.con.getresponse()
320
321 lines = err.getvalue().split('\n')
322 self.assertTrue(lines[0].endswith('code 404, message File not found'))
323 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
324
325
Georg Brandlb533e262008-05-25 18:19:30 +0000326class SimpleHTTPServerTestCase(BaseTestCase):
327 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
328 pass
329
330 def setUp(self):
331 BaseTestCase.setUp(self)
332 self.cwd = os.getcwd()
333 basetempdir = tempfile.gettempdir()
334 os.chdir(basetempdir)
335 self.data = b'We are the knights who say Ni!'
336 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
337 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panterfc475a92016-04-09 04:56:10 +0000338 self.base_url = '/' + self.tempdir_name
Victor Stinner28ce07a2017-07-28 18:15:02 +0200339 tempname = os.path.join(self.tempdir, 'test')
340 with open(tempname, 'wb') as temp:
Brett Cannon105df5d2010-10-29 23:43:42 +0000341 temp.write(self.data)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200342 temp.flush()
343 mtime = os.stat(tempname).st_mtime
Pierre Quentel351adda2017-04-02 12:26:12 +0200344 # compute last modification datetime for browser cache tests
345 last_modif = datetime.datetime.fromtimestamp(mtime,
346 datetime.timezone.utc)
347 self.last_modif_datetime = last_modif.replace(microsecond=0)
348 self.last_modif_header = email.utils.formatdate(
349 last_modif.timestamp(), usegmt=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000350
351 def tearDown(self):
352 try:
353 os.chdir(self.cwd)
354 try:
355 shutil.rmtree(self.tempdir)
356 except:
357 pass
358 finally:
359 BaseTestCase.tearDown(self)
360
361 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300362 def close_conn():
363 """Don't close reader yet so we can check if there was leftover
364 buffered input"""
365 nonlocal reader
366 reader = response.fp
367 response.fp = None
368 reader = None
369 response._close_conn = close_conn
370
Georg Brandlb533e262008-05-25 18:19:30 +0000371 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000372 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000373 self.assertEqual(response.status, status)
374 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000375 if data:
376 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300377 # Ensure the server has not set up a persistent connection, and has
378 # not sent any extra data
379 self.assertEqual(response.version, 10)
380 self.assertEqual(response.msg.get("Connection", "close"), "close")
381 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
382
383 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300384 return body
385
Ned Deily14183202015-01-05 01:02:30 -0800386 @support.requires_mac_ver(10, 5)
Steve Dowere58571b2016-09-08 11:11:13 -0700387 @unittest.skipIf(sys.platform == 'win32',
388 'undecodable name cannot be decoded on win32')
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300389 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
390 'need support.TESTFN_UNDECODABLE')
391 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300392 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300393 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
394 with open(os.path.join(self.tempdir, filename), 'wb') as f:
395 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000396 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300397 if sys.platform == 'darwin':
398 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
399 # UTF-8 into a percent-encoded value.
400 for name in os.listdir(self.tempdir):
401 if name != 'test': # Ignore a filename created in setUp().
402 filename = name
403 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200404 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300405 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
406 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300407 .encode(enc, 'surrogateescape'), body)
Martin Panterda3bb382016-04-11 00:40:08 +0000408 self.assertIn(('>%s<' % html.escape(filename, quote=False))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300409 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000410 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200411 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300412 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000413
414 def test_get(self):
415 #constructs the path relative to the root directory of the HTTPServer
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.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700418 # check for trailing "/" which should return 404. See Issue17324
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.NOT_FOUND)
Martin Panterfc475a92016-04-09 04:56:10 +0000421 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200422 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000423 response = self.request(self.base_url)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200424 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000425 response = self.request(self.base_url + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200426 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000427 response = self.request(self.base_url + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200428 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600429 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000430 self.base_url + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000431 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200432 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000433 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200434 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300435
436 data = b"Dummy index file\r\n"
437 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
438 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000439 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300440 self.check_status_and_reason(response, HTTPStatus.OK, data)
441
442 # chmod() doesn't work as expected on Windows, and filesystem
443 # permissions are ignored by root on Unix.
444 if os.name == 'posix' and os.geteuid() != 0:
445 os.chmod(self.tempdir, 0)
446 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000447 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200448 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300449 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000450 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000451
452 def test_head(self):
453 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000454 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200455 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000456 self.assertEqual(response.getheader('content-length'),
457 str(len(self.data)))
458 self.assertEqual(response.getheader('content-type'),
459 'application/octet-stream')
460
Pierre Quentel351adda2017-04-02 12:26:12 +0200461 def test_browser_cache(self):
462 """Check that when a request to /test is sent with the request header
463 If-Modified-Since set to date of last modification, the server returns
464 status code 304, not 200
465 """
466 headers = email.message.Message()
467 headers['If-Modified-Since'] = self.last_modif_header
468 response = self.request(self.base_url + '/test', headers=headers)
469 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
470
471 # one hour after last modification : must return 304
472 new_dt = self.last_modif_datetime + datetime.timedelta(hours=1)
473 headers = email.message.Message()
474 headers['If-Modified-Since'] = email.utils.format_datetime(new_dt,
475 usegmt=True)
476 response = self.request(self.base_url + '/test', headers=headers)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200477 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
Pierre Quentel351adda2017-04-02 12:26:12 +0200478
479 def test_browser_cache_file_changed(self):
480 # with If-Modified-Since earlier than Last-Modified, must return 200
481 dt = self.last_modif_datetime
482 # build datetime object : 365 days before last modification
483 old_dt = dt - datetime.timedelta(days=365)
484 headers = email.message.Message()
485 headers['If-Modified-Since'] = email.utils.format_datetime(old_dt,
486 usegmt=True)
487 response = self.request(self.base_url + '/test', headers=headers)
488 self.check_status_and_reason(response, HTTPStatus.OK)
489
490 def test_browser_cache_with_If_None_Match_header(self):
491 # if If-None-Match header is present, ignore If-Modified-Since
492
493 headers = email.message.Message()
494 headers['If-Modified-Since'] = self.last_modif_header
495 headers['If-None-Match'] = "*"
496 response = self.request(self.base_url + '/test', headers=headers)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200497 self.check_status_and_reason(response, HTTPStatus.OK)
Pierre Quentel351adda2017-04-02 12:26:12 +0200498
Georg Brandlb533e262008-05-25 18:19:30 +0000499 def test_invalid_requests(self):
500 response = self.request('/', method='FOO')
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 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400503 response = self.request('/', method='custom')
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 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200506 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000507
Pierre Quentel351adda2017-04-02 12:26:12 +0200508 def test_last_modified(self):
509 """Checks that the datetime returned in Last-Modified response header
510 is the actual datetime of last modification, rounded to the second
511 """
512 response = self.request(self.base_url + '/test')
513 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
514 last_modif_header = response.headers['Last-modified']
515 self.assertEqual(last_modif_header, self.last_modif_header)
516
Martin Panterfc475a92016-04-09 04:56:10 +0000517 def test_path_without_leading_slash(self):
518 response = self.request(self.tempdir_name + '/test')
519 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
520 response = self.request(self.tempdir_name + '/test/')
521 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
522 response = self.request(self.tempdir_name + '/')
523 self.check_status_and_reason(response, HTTPStatus.OK)
524 response = self.request(self.tempdir_name)
525 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
526 response = self.request(self.tempdir_name + '/?hi=2')
527 self.check_status_and_reason(response, HTTPStatus.OK)
528 response = self.request(self.tempdir_name + '?hi=1')
529 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
530 self.assertEqual(response.getheader("Location"),
531 self.tempdir_name + "/?hi=1")
532
Martin Panterda3bb382016-04-11 00:40:08 +0000533 def test_html_escape_filename(self):
534 filename = '<test&>.txt'
535 fullpath = os.path.join(self.tempdir, filename)
536
537 try:
538 open(fullpath, 'w').close()
539 except OSError:
540 raise unittest.SkipTest('Can not create file %s on current file '
541 'system' % filename)
542
543 try:
544 response = self.request(self.base_url + '/')
545 body = self.check_status_and_reason(response, HTTPStatus.OK)
546 enc = response.headers.get_content_charset()
547 finally:
548 os.unlink(fullpath) # avoid affecting test_undecodable_filename
549
550 self.assertIsNotNone(enc)
551 html_text = '>%s<' % html.escape(filename, quote=False)
552 self.assertIn(html_text.encode(enc), body)
553
Georg Brandlb533e262008-05-25 18:19:30 +0000554
555cgi_file1 = """\
556#!%s
557
558print("Content-type: text/html")
559print()
560print("Hello World")
561"""
562
563cgi_file2 = """\
564#!%s
565import cgi
566
567print("Content-type: text/html")
568print()
569
570form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000571print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
572 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000573"""
574
Martin Pantera02e18a2015-10-03 05:38:07 +0000575cgi_file4 = """\
576#!%s
577import os
578
579print("Content-type: text/html")
580print()
581
582print(os.environ["%s"])
583"""
584
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100585
586@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
587 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000588class CGIHTTPServerTestCase(BaseTestCase):
589 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
590 pass
591
Antoine Pitroue768c392012-08-05 14:52:45 +0200592 linesep = os.linesep.encode('ascii')
593
Georg Brandlb533e262008-05-25 18:19:30 +0000594 def setUp(self):
595 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000596 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000597 self.parent_dir = tempfile.mkdtemp()
598 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700599 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000600 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700601 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400602 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000603 self.file1_path = None
604 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700605 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000606 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000607
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000608 # The shebang line should be pure ASCII: use symlink if possible.
609 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000610 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000611 self.pythonexe = os.path.join(self.parent_dir, 'python')
612 os.symlink(sys.executable, self.pythonexe)
613 else:
614 self.pythonexe = sys.executable
615
Victor Stinner3218c312010-10-17 20:13:36 +0000616 try:
617 # The python executable path is written as the first line of the
618 # CGI Python script. The encoding cookie cannot be used, and so the
619 # path should be encodable to the default script encoding (utf-8)
620 self.pythonexe.encode('utf-8')
621 except UnicodeEncodeError:
622 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200623 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000624
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400625 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
626 with open(self.nocgi_path, 'w') as fp:
627 fp.write(cgi_file1 % self.pythonexe)
628 os.chmod(self.nocgi_path, 0o777)
629
Georg Brandlb533e262008-05-25 18:19:30 +0000630 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000631 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000632 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000633 os.chmod(self.file1_path, 0o777)
634
635 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000636 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000637 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000638 os.chmod(self.file2_path, 0o777)
639
Ned Deily915a30f2014-07-12 22:06:26 -0700640 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
641 with open(self.file3_path, 'w', encoding='utf-8') as file3:
642 file3.write(cgi_file1 % self.pythonexe)
643 os.chmod(self.file3_path, 0o777)
644
Martin Pantera02e18a2015-10-03 05:38:07 +0000645 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
646 with open(self.file4_path, 'w', encoding='utf-8') as file4:
647 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
648 os.chmod(self.file4_path, 0o777)
649
Georg Brandlb533e262008-05-25 18:19:30 +0000650 os.chdir(self.parent_dir)
651
652 def tearDown(self):
653 try:
654 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000655 if self.pythonexe != sys.executable:
656 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400657 if self.nocgi_path:
658 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000659 if self.file1_path:
660 os.remove(self.file1_path)
661 if self.file2_path:
662 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700663 if self.file3_path:
664 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000665 if self.file4_path:
666 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700667 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000668 os.rmdir(self.cgi_dir)
669 os.rmdir(self.parent_dir)
670 finally:
671 BaseTestCase.tearDown(self)
672
Senthil Kumarand70846b2012-04-12 02:34:32 +0800673 def test_url_collapse_path(self):
674 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000675 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800676 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000677 '..': IndexError,
678 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800679 '/': '//',
680 '//': '//',
681 '/\\': '//\\',
682 '/.//': '//',
683 'cgi-bin/file1.py': '/cgi-bin/file1.py',
684 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
685 'a': '//a',
686 '/a': '//a',
687 '//a': '//a',
688 './a': '//a',
689 './C:/': '/C:/',
690 '/a/b': '/a/b',
691 '/a/b/': '/a/b/',
692 '/a/b/.': '/a/b/',
693 '/a/b/c/..': '/a/b/',
694 '/a/b/c/../d': '/a/b/d',
695 '/a/b/c/../d/e/../f': '/a/b/d/f',
696 '/a/b/c/../d/e/../../f': '/a/b/f',
697 '/a/b/c/../d/e/.././././..//f': '/a/b/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': '/a/f',
700 '/a/b/c/../d/e/../../../../f': '//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/..': '//',
703 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000704 }
705 for path, expected in test_vectors.items():
706 if isinstance(expected, type) and issubclass(expected, Exception):
707 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800708 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000709 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800710 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000711 self.assertEqual(expected, actual,
712 msg='path = %r\nGot: %r\nWanted: %r' %
713 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000714
Georg Brandlb533e262008-05-25 18:19:30 +0000715 def test_headers_and_content(self):
716 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200717 self.assertEqual(
718 (res.read(), res.getheader('Content-type'), res.status),
719 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000720
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400721 def test_issue19435(self):
722 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200723 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400724
Georg Brandlb533e262008-05-25 18:19:30 +0000725 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000726 params = urllib.parse.urlencode(
727 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000728 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
729 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
730
Antoine Pitroue768c392012-08-05 14:52:45 +0200731 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000732
733 def test_invaliduri(self):
734 res = self.request('/cgi-bin/invalid')
735 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200736 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000737
738 def test_authorization(self):
739 headers = {b'Authorization' : b'Basic ' +
740 base64.b64encode(b'username:pass')}
741 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200742 self.assertEqual(
743 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
744 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000745
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000746 def test_no_leading_slash(self):
747 # http://bugs.python.org/issue2254
748 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200749 self.assertEqual(
750 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
751 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000752
Senthil Kumaran42713722010-10-03 17:55:45 +0000753 def test_os_environ_is_not_altered(self):
754 signature = "Test CGI Server"
755 os.environ['SERVER_SOFTWARE'] = signature
756 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200757 self.assertEqual(
758 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
759 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000760 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
761
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700762 def test_urlquote_decoding_in_cgi_check(self):
763 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200764 self.assertEqual(
765 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
766 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700767
Ned Deily915a30f2014-07-12 22:06:26 -0700768 def test_nested_cgi_path_issue21323(self):
769 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200770 self.assertEqual(
771 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
772 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700773
Martin Pantera02e18a2015-10-03 05:38:07 +0000774 def test_query_with_multiple_question_mark(self):
775 res = self.request('/cgi-bin/file4.py?a=b?c=d')
776 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000777 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000778 (res.read(), res.getheader('Content-type'), res.status))
779
Martin Pantercb29e8c2015-10-03 05:55:46 +0000780 def test_query_with_continuous_slashes(self):
781 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
782 self.assertEqual(
783 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000784 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000785 (res.read(), res.getheader('Content-type'), res.status))
786
Georg Brandlb533e262008-05-25 18:19:30 +0000787
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000788class SocketlessRequestHandler(SimpleHTTPRequestHandler):
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200789 def __init__(self, *args, **kwargs):
790 request = mock.Mock()
791 request.makefile.return_value = BytesIO()
792 super().__init__(request, None, None)
793
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000794 self.get_called = False
795 self.protocol_version = "HTTP/1.1"
796
797 def do_GET(self):
798 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200799 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000800 self.send_header('Content-Type', 'text/html')
801 self.end_headers()
802 self.wfile.write(b'<html><body>Data</body></html>\r\n')
803
804 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000805 pass
806
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000807class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
808 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200809 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000810 return False
811
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800812
813class AuditableBytesIO:
814
815 def __init__(self):
816 self.datas = []
817
818 def write(self, data):
819 self.datas.append(data)
820
821 def getData(self):
822 return b''.join(self.datas)
823
824 @property
825 def numWrites(self):
826 return len(self.datas)
827
828
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000829class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200830 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000831
832 Test the support for the Expect 100-continue header.
833 """
834
835 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
836
837 def setUp (self):
838 self.handler = SocketlessRequestHandler()
839
840 def send_typical_request(self, message):
841 input = BytesIO(message)
842 output = BytesIO()
843 self.handler.rfile = input
844 self.handler.wfile = output
845 self.handler.handle_one_request()
846 output.seek(0)
847 return output.readlines()
848
849 def verify_get_called(self):
850 self.assertTrue(self.handler.get_called)
851
852 def verify_expected_headers(self, headers):
853 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
854 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
855
856 def verify_http_server_response(self, response):
857 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200858 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000859
860 def test_http_1_1(self):
861 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
862 self.verify_http_server_response(result[0])
863 self.verify_expected_headers(result[1:-1])
864 self.verify_get_called()
865 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500866 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
867 self.assertEqual(self.handler.command, 'GET')
868 self.assertEqual(self.handler.path, '/')
869 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
870 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000871
872 def test_http_1_0(self):
873 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
874 self.verify_http_server_response(result[0])
875 self.verify_expected_headers(result[1:-1])
876 self.verify_get_called()
877 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500878 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
879 self.assertEqual(self.handler.command, 'GET')
880 self.assertEqual(self.handler.path, '/')
881 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
882 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000883
884 def test_http_0_9(self):
885 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
886 self.assertEqual(len(result), 1)
887 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
888 self.verify_get_called()
889
Martin Pantere82338d2016-11-19 01:06:37 +0000890 def test_extra_space(self):
891 result = self.send_typical_request(
892 b'GET /spaced out HTTP/1.1\r\n'
893 b'Host: dummy\r\n'
894 b'\r\n'
895 )
896 self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
897 self.verify_expected_headers(result[1:result.index(b'\r\n')])
898 self.assertFalse(self.handler.get_called)
899
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000900 def test_with_continue_1_0(self):
901 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
902 self.verify_http_server_response(result[0])
903 self.verify_expected_headers(result[1:-1])
904 self.verify_get_called()
905 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500906 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
907 self.assertEqual(self.handler.command, 'GET')
908 self.assertEqual(self.handler.path, '/')
909 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
910 headers = (("Expect", "100-continue"),)
911 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000912
913 def test_with_continue_1_1(self):
914 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
915 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500916 self.assertEqual(result[1], b'\r\n')
917 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000918 self.verify_expected_headers(result[2:-1])
919 self.verify_get_called()
920 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500921 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
922 self.assertEqual(self.handler.command, 'GET')
923 self.assertEqual(self.handler.path, '/')
924 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
925 headers = (("Expect", "100-continue"),)
926 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000927
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800928 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000929
930 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800931 output = AuditableBytesIO()
932 handler = SocketlessRequestHandler()
933 handler.rfile = input
934 handler.wfile = output
935 handler.request_version = 'HTTP/1.1'
936 handler.requestline = ''
937 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000938
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800939 handler.send_error(418)
940 self.assertEqual(output.numWrites, 2)
941
942 def test_header_buffering_of_send_response_only(self):
943
944 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
945 output = AuditableBytesIO()
946 handler = SocketlessRequestHandler()
947 handler.rfile = input
948 handler.wfile = output
949 handler.request_version = 'HTTP/1.1'
950
951 handler.send_response_only(418)
952 self.assertEqual(output.numWrites, 0)
953 handler.end_headers()
954 self.assertEqual(output.numWrites, 1)
955
956 def test_header_buffering_of_send_header(self):
957
958 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
959 output = AuditableBytesIO()
960 handler = SocketlessRequestHandler()
961 handler.rfile = input
962 handler.wfile = output
963 handler.request_version = 'HTTP/1.1'
964
965 handler.send_header('Foo', 'foo')
966 handler.send_header('bar', 'bar')
967 self.assertEqual(output.numWrites, 0)
968 handler.end_headers()
969 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
970 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000971
972 def test_header_unbuffered_when_continue(self):
973
974 def _readAndReseek(f):
975 pos = f.tell()
976 f.seek(0)
977 data = f.read()
978 f.seek(pos)
979 return data
980
981 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
982 output = BytesIO()
983 self.handler.rfile = input
984 self.handler.wfile = output
985 self.handler.request_version = 'HTTP/1.1'
986
987 self.handler.handle_one_request()
988 self.assertNotEqual(_readAndReseek(output), b'')
989 result = _readAndReseek(output).split(b'\r\n')
990 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500991 self.assertEqual(result[1], b'')
992 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000993
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000994 def test_with_continue_rejected(self):
995 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
996 self.handler = RejectingSocketlessRequestHandler()
997 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
998 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
999 self.verify_expected_headers(result[1:-1])
1000 # The expect handler should short circuit the usual get method by
1001 # returning false here, so get_called should be false
1002 self.assertFalse(self.handler.get_called)
1003 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
1004 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
1005
Antoine Pitrouc4924372010-12-16 16:48:36 +00001006 def test_request_length(self):
1007 # Issue #10714: huge request lines are discarded, to avoid Denial
1008 # of Service attacks.
1009 result = self.send_typical_request(b'GET ' + b'x' * 65537)
1010 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
1011 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001012 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001013
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001014 def test_header_length(self):
1015 # Issue #6791: same for headers
1016 result = self.send_typical_request(
1017 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +00001018 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001019 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001020 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1021
Martin Panteracc03192016-04-03 00:45:46 +00001022 def test_too_many_headers(self):
1023 result = self.send_typical_request(
1024 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
1025 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
1026 self.assertFalse(self.handler.get_called)
1027 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1028
Martin Panterda3bb382016-04-11 00:40:08 +00001029 def test_html_escape_on_error(self):
1030 result = self.send_typical_request(
1031 b'<script>alert("hello")</script> / HTTP/1.1')
1032 result = b''.join(result)
1033 text = '<script>alert("hello")</script>'
1034 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
1035
Benjamin Peterson70e28472015-02-17 21:11:10 -05001036 def test_close_connection(self):
1037 # handle_one_request() should be repeatedly called until
1038 # it sets close_connection
1039 def handle_one_request():
1040 self.handler.close_connection = next(close_values)
1041 self.handler.handle_one_request = handle_one_request
1042
1043 close_values = iter((True,))
1044 self.handler.handle()
1045 self.assertRaises(StopIteration, next, close_values)
1046
1047 close_values = iter((False, False, True))
1048 self.handler.handle()
1049 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001050
Berker Peksag04bc5b92016-03-14 06:06:03 +02001051 def test_date_time_string(self):
1052 now = time.time()
1053 # this is the old code that formats the timestamp
1054 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
1055 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
1056 self.handler.weekdayname[wd],
1057 day,
1058 self.handler.monthname[month],
1059 year, hh, mm, ss
1060 )
1061 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
1062
1063
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001064class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
1065 """ Test url parsing """
1066 def setUp(self):
1067 self.translated = os.getcwd()
1068 self.translated = os.path.join(self.translated, 'filename')
1069 self.handler = SocketlessRequestHandler()
1070
1071 def test_query_arguments(self):
1072 path = self.handler.translate_path('/filename')
1073 self.assertEqual(path, self.translated)
1074 path = self.handler.translate_path('/filename?foo=bar')
1075 self.assertEqual(path, self.translated)
1076 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
1077 self.assertEqual(path, self.translated)
1078
1079 def test_start_with_double_slash(self):
1080 path = self.handler.translate_path('//filename')
1081 self.assertEqual(path, self.translated)
1082 path = self.handler.translate_path('//filename?foo=bar')
1083 self.assertEqual(path, self.translated)
1084
Martin Panterd274b3f2016-04-18 03:45:18 +00001085 def test_windows_colon(self):
1086 with support.swap_attr(server.os, 'path', ntpath):
1087 path = self.handler.translate_path('c:c:c:foo/filename')
1088 path = path.replace(ntpath.sep, os.sep)
1089 self.assertEqual(path, self.translated)
1090
1091 path = self.handler.translate_path('\\c:../filename')
1092 path = path.replace(ntpath.sep, os.sep)
1093 self.assertEqual(path, self.translated)
1094
1095 path = self.handler.translate_path('c:\\c:..\\foo/filename')
1096 path = path.replace(ntpath.sep, os.sep)
1097 self.assertEqual(path, self.translated)
1098
1099 path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
1100 path = path.replace(ntpath.sep, os.sep)
1101 self.assertEqual(path, self.translated)
1102
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001103
Berker Peksag366c5702015-02-13 20:48:15 +02001104class MiscTestCase(unittest.TestCase):
1105 def test_all(self):
1106 expected = []
1107 blacklist = {'executable', 'nobody_uid', 'test'}
1108 for name in dir(server):
1109 if name.startswith('_') or name in blacklist:
1110 continue
1111 module_object = getattr(server, name)
1112 if getattr(module_object, '__module__', None) == 'http.server':
1113 expected.append(name)
1114 self.assertCountEqual(server.__all__, expected)
1115
1116
Georg Brandlb533e262008-05-25 18:19:30 +00001117def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001118 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001119 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001120 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001121 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001122 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001123 BaseHTTPServerTestCase,
1124 SimpleHTTPServerTestCase,
1125 CGIHTTPServerTestCase,
1126 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001127 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001128 )
Georg Brandlb533e262008-05-25 18:19:30 +00001129 finally:
1130 os.chdir(cwd)
1131
1132if __name__ == '__main__':
1133 test_main()