blob: 8df0b5251f1ae3b6601d3a0d9ba2c7a4ac45c535 [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"""
Miss Islington (bot)b630ca72020-12-05 07:26:37 -08006from collections import OrderedDict
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
Géry Ogam781266e2019-09-11 15:03:46 +020017import pathlib
Georg Brandlb533e262008-05-25 18:19:30 +000018import shutil
Pierre Quentel351adda2017-04-02 12:26:12 +020019import email.message
20import email.utils
Serhiy Storchakacb5bc402014-08-17 08:22:11 +030021import html
Miss Islington (bot)b630ca72020-12-05 07:26:37 -080022import http, http.client
Pierre Quentel351adda2017-04-02 12:26:12 +020023import urllib.parse
Georg Brandlb533e262008-05-25 18:19:30 +000024import tempfile
Berker Peksag04bc5b92016-03-14 06:06:03 +020025import time
Pierre Quentel351adda2017-04-02 12:26:12 +020026import datetime
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020027import threading
Stéphane Wirtela17a2f52017-05-24 09:29:06 +020028from unittest import mock
Senthil Kumaran0f476d42010-09-30 06:09:18 +000029from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000030
31import unittest
32from test import support
Antoine Pitroua6a4dc82017-09-07 18:56:24 +020033
Georg Brandlb533e262008-05-25 18:19:30 +000034
Georg Brandlb533e262008-05-25 18:19:30 +000035class NoLogRequestHandler:
36 def log_message(self, *args):
37 # don't write log messages to stderr
38 pass
39
Barry Warsaw820c1202008-06-12 04:06:45 +000040 def read(self, n=None):
41 return ''
42
Georg Brandlb533e262008-05-25 18:19:30 +000043
44class TestServerThread(threading.Thread):
45 def __init__(self, test_object, request_handler):
46 threading.Thread.__init__(self)
47 self.request_handler = request_handler
48 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000049
50 def run(self):
Antoine Pitroucb342182011-03-21 00:26:51 +010051 self.server = HTTPServer(('localhost', 0), self.request_handler)
52 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000053 self.test_object.server_started.set()
54 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000055 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000056 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000057 finally:
58 self.server.server_close()
59
60 def stop(self):
61 self.server.shutdown()
Victor Stinner830d7d22017-08-22 18:05:07 +020062 self.join()
Georg Brandlb533e262008-05-25 18:19:30 +000063
64
65class BaseTestCase(unittest.TestCase):
66 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000067 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000068 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000069 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000070 self.thread = TestServerThread(self, self.request_handler)
71 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000072 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000073
74 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000075 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020076 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000077 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000078 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000079
80 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010081 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000082 self.connection.request(method, uri, body, headers)
83 return self.connection.getresponse()
84
85
86class BaseHTTPServerTestCase(BaseTestCase):
87 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
88 protocol_version = 'HTTP/1.1'
89 default_request_version = 'HTTP/1.1'
90
91 def do_TEST(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020092 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000093 self.send_header('Content-Type', 'text/html')
94 self.send_header('Connection', 'close')
95 self.end_headers()
96
97 def do_KEEP(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020098 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000099 self.send_header('Content-Type', 'text/html')
100 self.send_header('Connection', 'keep-alive')
101 self.end_headers()
102
103 def do_KEYERROR(self):
104 self.send_error(999)
105
Senthil Kumaran52d27202012-10-10 23:16:21 -0700106 def do_NOTFOUND(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200107 self.send_error(HTTPStatus.NOT_FOUND)
Senthil Kumaran52d27202012-10-10 23:16:21 -0700108
Senthil Kumaran26886442013-03-15 07:53:21 -0700109 def do_EXPLAINERROR(self):
110 self.send_error(999, "Short Message",
Martin Panter46f50722016-05-26 05:35:26 +0000111 "This is a long \n explanation")
Senthil Kumaran26886442013-03-15 07:53:21 -0700112
Georg Brandlb533e262008-05-25 18:19:30 +0000113 def do_CUSTOM(self):
114 self.send_response(999)
115 self.send_header('Content-Type', 'text/html')
116 self.send_header('Connection', 'close')
117 self.end_headers()
118
Armin Ronacher8d96d772011-01-22 13:13:05 +0000119 def do_LATINONEHEADER(self):
120 self.send_response(999)
121 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000122 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000123 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000124 body = self.headers['x-special-incoming'].encode('utf-8')
125 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000126
Martin Pantere42e1292016-06-08 08:29:13 +0000127 def do_SEND_ERROR(self):
128 self.send_error(int(self.path[1:]))
129
130 def do_HEAD(self):
131 self.send_error(int(self.path[1:]))
132
Georg Brandlb533e262008-05-25 18:19:30 +0000133 def setUp(self):
134 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100135 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000136 self.con.connect()
137
138 def test_command(self):
139 self.con.request('GET', '/')
140 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200141 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000142
143 def test_request_line_trimming(self):
144 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400145 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000146 self.con.endheaders()
147 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200148 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000149
150 def test_version_bogus(self):
151 self.con._http_vsn_str = 'FUBAR'
152 self.con.putrequest('GET', '/')
153 self.con.endheaders()
154 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200155 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000156
157 def test_version_digits(self):
158 self.con._http_vsn_str = 'HTTP/9.9.9'
159 self.con.putrequest('GET', '/')
160 self.con.endheaders()
161 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200162 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000163
164 def test_version_none_get(self):
165 self.con._http_vsn_str = ''
166 self.con.putrequest('GET', '/')
167 self.con.endheaders()
168 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200169 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000170
171 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400172 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000173 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400174 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000175 self.con.endheaders()
176 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200177 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000178
179 def test_version_invalid(self):
180 self.con._http_vsn = 99
181 self.con._http_vsn_str = 'HTTP/9.9'
182 self.con.putrequest('GET', '/')
183 self.con.endheaders()
184 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200185 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000186
187 def test_send_blank(self):
188 self.con._http_vsn_str = ''
189 self.con.putrequest('', '')
190 self.con.endheaders()
191 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200192 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000193
194 def test_header_close(self):
195 self.con.putrequest('GET', '/')
196 self.con.putheader('Connection', 'close')
197 self.con.endheaders()
198 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200199 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000200
Berker Peksag20853612016-08-25 01:13:34 +0300201 def test_header_keep_alive(self):
Georg Brandlb533e262008-05-25 18:19:30 +0000202 self.con._http_vsn_str = 'HTTP/1.1'
203 self.con.putrequest('GET', '/')
204 self.con.putheader('Connection', 'keep-alive')
205 self.con.endheaders()
206 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200207 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000208
209 def test_handler(self):
210 self.con.request('TEST', '/')
211 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200212 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000213
214 def test_return_header_keep_alive(self):
215 self.con.request('KEEP', '/')
216 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000217 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000218 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000219 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000220
221 def test_internal_key_error(self):
222 self.con.request('KEYERROR', '/')
223 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000224 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000225
226 def test_return_custom_status(self):
227 self.con.request('CUSTOM', '/')
228 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000229 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000230
Senthil Kumaran26886442013-03-15 07:53:21 -0700231 def test_return_explain_error(self):
232 self.con.request('EXPLAINERROR', '/')
233 res = self.con.getresponse()
234 self.assertEqual(res.status, 999)
235 self.assertTrue(int(res.getheader('Content-Length')))
236
Armin Ronacher8d96d772011-01-22 13:13:05 +0000237 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000238 self.con.request('LATINONEHEADER', '/', headers={
239 'X-Special-Incoming': 'Ärger mit Unicode'
240 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000241 res = self.con.getresponse()
242 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000243 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000244
Senthil Kumaran52d27202012-10-10 23:16:21 -0700245 def test_error_content_length(self):
246 # Issue #16088: standard error responses should have a content-length
247 self.con.request('NOTFOUND', '/')
248 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200249 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
250
Senthil Kumaran52d27202012-10-10 23:16:21 -0700251 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700252 self.assertEqual(int(res.getheader('Content-Length')), len(data))
253
Martin Pantere42e1292016-06-08 08:29:13 +0000254 def test_send_error(self):
255 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
256 HTTPStatus.RESET_CONTENT)
257 for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
258 HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
259 HTTPStatus.SWITCHING_PROTOCOLS):
260 self.con.request('SEND_ERROR', '/{}'.format(code))
261 res = self.con.getresponse()
262 self.assertEqual(code, res.status)
263 self.assertEqual(None, res.getheader('Content-Length'))
264 self.assertEqual(None, res.getheader('Content-Type'))
265 if code not in allow_transfer_encoding_codes:
266 self.assertEqual(None, res.getheader('Transfer-Encoding'))
267
268 data = res.read()
269 self.assertEqual(b'', data)
270
271 def test_head_via_send_error(self):
272 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
273 HTTPStatus.RESET_CONTENT)
274 for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
275 HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
276 HTTPStatus.SWITCHING_PROTOCOLS):
277 self.con.request('HEAD', '/{}'.format(code))
278 res = self.con.getresponse()
279 self.assertEqual(code, res.status)
280 if code == HTTPStatus.OK:
281 self.assertTrue(int(res.getheader('Content-Length')) > 0)
282 self.assertIn('text/html', res.getheader('Content-Type'))
283 else:
284 self.assertEqual(None, res.getheader('Content-Length'))
285 self.assertEqual(None, res.getheader('Content-Type'))
286 if code not in allow_transfer_encoding_codes:
287 self.assertEqual(None, res.getheader('Transfer-Encoding'))
288
289 data = res.read()
290 self.assertEqual(b'', data)
291
Georg Brandlb533e262008-05-25 18:19:30 +0000292
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200293class RequestHandlerLoggingTestCase(BaseTestCase):
294 class request_handler(BaseHTTPRequestHandler):
295 protocol_version = 'HTTP/1.1'
296 default_request_version = 'HTTP/1.1'
297
298 def do_GET(self):
299 self.send_response(HTTPStatus.OK)
300 self.end_headers()
301
302 def do_ERROR(self):
303 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
304
305 def test_get(self):
306 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
307 self.con.connect()
308
309 with support.captured_stderr() as err:
310 self.con.request('GET', '/')
311 self.con.getresponse()
312
313 self.assertTrue(
314 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
315
316 def test_err(self):
317 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
318 self.con.connect()
319
320 with support.captured_stderr() as err:
321 self.con.request('ERROR', '/')
322 self.con.getresponse()
323
324 lines = err.getvalue().split('\n')
325 self.assertTrue(lines[0].endswith('code 404, message File not found'))
326 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
327
328
Georg Brandlb533e262008-05-25 18:19:30 +0000329class SimpleHTTPServerTestCase(BaseTestCase):
330 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
331 pass
332
333 def setUp(self):
334 BaseTestCase.setUp(self)
335 self.cwd = os.getcwd()
336 basetempdir = tempfile.gettempdir()
337 os.chdir(basetempdir)
338 self.data = b'We are the knights who say Ni!'
339 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
340 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panterfc475a92016-04-09 04:56:10 +0000341 self.base_url = '/' + self.tempdir_name
Victor Stinner28ce07a2017-07-28 18:15:02 +0200342 tempname = os.path.join(self.tempdir, 'test')
343 with open(tempname, 'wb') as temp:
Brett Cannon105df5d2010-10-29 23:43:42 +0000344 temp.write(self.data)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200345 temp.flush()
346 mtime = os.stat(tempname).st_mtime
Pierre Quentel351adda2017-04-02 12:26:12 +0200347 # compute last modification datetime for browser cache tests
348 last_modif = datetime.datetime.fromtimestamp(mtime,
349 datetime.timezone.utc)
350 self.last_modif_datetime = last_modif.replace(microsecond=0)
351 self.last_modif_header = email.utils.formatdate(
352 last_modif.timestamp(), usegmt=True)
Georg Brandlb533e262008-05-25 18:19:30 +0000353
354 def tearDown(self):
355 try:
356 os.chdir(self.cwd)
357 try:
358 shutil.rmtree(self.tempdir)
359 except:
360 pass
361 finally:
362 BaseTestCase.tearDown(self)
363
364 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300365 def close_conn():
366 """Don't close reader yet so we can check if there was leftover
367 buffered input"""
368 nonlocal reader
369 reader = response.fp
370 response.fp = None
371 reader = None
372 response._close_conn = close_conn
373
Georg Brandlb533e262008-05-25 18:19:30 +0000374 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000375 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000376 self.assertEqual(response.status, status)
377 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000378 if data:
379 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300380 # Ensure the server has not set up a persistent connection, and has
381 # not sent any extra data
382 self.assertEqual(response.version, 10)
383 self.assertEqual(response.msg.get("Connection", "close"), "close")
384 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
385
386 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300387 return body
388
Ned Deilyb3edde82017-12-04 23:42:02 -0500389 @unittest.skipIf(sys.platform == 'darwin',
390 'undecodable name cannot always be decoded on macOS')
Steve Dowere58571b2016-09-08 11:11:13 -0700391 @unittest.skipIf(sys.platform == 'win32',
392 'undecodable name cannot be decoded on win32')
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300393 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
394 'need support.TESTFN_UNDECODABLE')
395 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300396 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300397 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
398 with open(os.path.join(self.tempdir, filename), 'wb') as f:
399 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000400 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300401 if sys.platform == 'darwin':
402 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
403 # UTF-8 into a percent-encoded value.
404 for name in os.listdir(self.tempdir):
405 if name != 'test': # Ignore a filename created in setUp().
406 filename = name
407 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200408 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300409 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
410 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300411 .encode(enc, 'surrogateescape'), body)
Martin Panterda3bb382016-04-11 00:40:08 +0000412 self.assertIn(('>%s<' % html.escape(filename, quote=False))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300413 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000414 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200415 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300416 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000417
418 def test_get(self):
419 #constructs the path relative to the root directory of the HTTPServer
Martin Panterfc475a92016-04-09 04:56:10 +0000420 response = self.request(self.base_url + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200421 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700422 # check for trailing "/" which should return 404. See Issue17324
Martin Panterfc475a92016-04-09 04:56:10 +0000423 response = self.request(self.base_url + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200424 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Martin Panterfc475a92016-04-09 04:56:10 +0000425 response = self.request(self.base_url + '/')
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)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200428 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000429 response = self.request(self.base_url + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200430 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000431 response = self.request(self.base_url + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200432 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600433 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000434 self.base_url + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000435 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200436 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000437 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200438 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300439
440 data = b"Dummy index file\r\n"
441 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
442 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000443 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300444 self.check_status_and_reason(response, HTTPStatus.OK, data)
445
446 # chmod() doesn't work as expected on Windows, and filesystem
447 # permissions are ignored by root on Unix.
448 if os.name == 'posix' and os.geteuid() != 0:
449 os.chmod(self.tempdir, 0)
450 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000451 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200452 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300453 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000454 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000455
456 def test_head(self):
457 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000458 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200459 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000460 self.assertEqual(response.getheader('content-length'),
461 str(len(self.data)))
462 self.assertEqual(response.getheader('content-type'),
463 'application/octet-stream')
464
Pierre Quentel351adda2017-04-02 12:26:12 +0200465 def test_browser_cache(self):
466 """Check that when a request to /test is sent with the request header
467 If-Modified-Since set to date of last modification, the server returns
468 status code 304, not 200
469 """
470 headers = email.message.Message()
471 headers['If-Modified-Since'] = self.last_modif_header
472 response = self.request(self.base_url + '/test', headers=headers)
473 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
474
475 # one hour after last modification : must return 304
476 new_dt = self.last_modif_datetime + datetime.timedelta(hours=1)
477 headers = email.message.Message()
478 headers['If-Modified-Since'] = email.utils.format_datetime(new_dt,
479 usegmt=True)
480 response = self.request(self.base_url + '/test', headers=headers)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200481 self.check_status_and_reason(response, HTTPStatus.NOT_MODIFIED)
Pierre Quentel351adda2017-04-02 12:26:12 +0200482
483 def test_browser_cache_file_changed(self):
484 # with If-Modified-Since earlier than Last-Modified, must return 200
485 dt = self.last_modif_datetime
486 # build datetime object : 365 days before last modification
487 old_dt = dt - datetime.timedelta(days=365)
488 headers = email.message.Message()
489 headers['If-Modified-Since'] = email.utils.format_datetime(old_dt,
490 usegmt=True)
491 response = self.request(self.base_url + '/test', headers=headers)
492 self.check_status_and_reason(response, HTTPStatus.OK)
493
494 def test_browser_cache_with_If_None_Match_header(self):
495 # if If-None-Match header is present, ignore If-Modified-Since
496
497 headers = email.message.Message()
498 headers['If-Modified-Since'] = self.last_modif_header
499 headers['If-None-Match'] = "*"
500 response = self.request(self.base_url + '/test', headers=headers)
Victor Stinner28ce07a2017-07-28 18:15:02 +0200501 self.check_status_and_reason(response, HTTPStatus.OK)
Pierre Quentel351adda2017-04-02 12:26:12 +0200502
Georg Brandlb533e262008-05-25 18:19:30 +0000503 def test_invalid_requests(self):
504 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200505 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000506 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400507 response = self.request('/', method='custom')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200508 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000509 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200510 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000511
Pierre Quentel351adda2017-04-02 12:26:12 +0200512 def test_last_modified(self):
513 """Checks that the datetime returned in Last-Modified response header
514 is the actual datetime of last modification, rounded to the second
515 """
516 response = self.request(self.base_url + '/test')
517 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
518 last_modif_header = response.headers['Last-modified']
519 self.assertEqual(last_modif_header, self.last_modif_header)
520
Martin Panterfc475a92016-04-09 04:56:10 +0000521 def test_path_without_leading_slash(self):
522 response = self.request(self.tempdir_name + '/test')
523 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
524 response = self.request(self.tempdir_name + '/test/')
525 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
526 response = self.request(self.tempdir_name + '/')
527 self.check_status_and_reason(response, HTTPStatus.OK)
528 response = self.request(self.tempdir_name)
529 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
530 response = self.request(self.tempdir_name + '/?hi=2')
531 self.check_status_and_reason(response, HTTPStatus.OK)
532 response = self.request(self.tempdir_name + '?hi=1')
533 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
534 self.assertEqual(response.getheader("Location"),
535 self.tempdir_name + "/?hi=1")
536
Martin Panterda3bb382016-04-11 00:40:08 +0000537 def test_html_escape_filename(self):
538 filename = '<test&>.txt'
539 fullpath = os.path.join(self.tempdir, filename)
540
541 try:
542 open(fullpath, 'w').close()
543 except OSError:
544 raise unittest.SkipTest('Can not create file %s on current file '
545 'system' % filename)
546
547 try:
548 response = self.request(self.base_url + '/')
549 body = self.check_status_and_reason(response, HTTPStatus.OK)
550 enc = response.headers.get_content_charset()
551 finally:
552 os.unlink(fullpath) # avoid affecting test_undecodable_filename
553
554 self.assertIsNotNone(enc)
555 html_text = '>%s<' % html.escape(filename, quote=False)
556 self.assertIn(html_text.encode(enc), body)
557
Georg Brandlb533e262008-05-25 18:19:30 +0000558
559cgi_file1 = """\
560#!%s
561
562print("Content-type: text/html")
563print()
564print("Hello World")
565"""
566
567cgi_file2 = """\
568#!%s
569import cgi
570
571print("Content-type: text/html")
572print()
573
574form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000575print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
576 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000577"""
578
Martin Pantera02e18a2015-10-03 05:38:07 +0000579cgi_file4 = """\
580#!%s
581import os
582
583print("Content-type: text/html")
584print()
585
586print(os.environ["%s"])
587"""
588
Miss Islington (bot)b630ca72020-12-05 07:26:37 -0800589cgi_file6 = """\
590#!%s
591import os
592
593print("Content-type: text/plain")
594print()
595print(repr(os.environ))
596"""
597
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100598
599@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
600 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000601class CGIHTTPServerTestCase(BaseTestCase):
602 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
603 pass
604
Antoine Pitroue768c392012-08-05 14:52:45 +0200605 linesep = os.linesep.encode('ascii')
606
Georg Brandlb533e262008-05-25 18:19:30 +0000607 def setUp(self):
608 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000609 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000610 self.parent_dir = tempfile.mkdtemp()
611 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700612 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Siwon Kang91daa9d2019-11-22 18:13:05 +0900613 self.sub_dir_1 = os.path.join(self.parent_dir, 'sub')
614 self.sub_dir_2 = os.path.join(self.sub_dir_1, 'dir')
615 self.cgi_dir_in_sub_dir = os.path.join(self.sub_dir_2, 'cgi-bin')
Georg Brandlb533e262008-05-25 18:19:30 +0000616 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700617 os.mkdir(self.cgi_child_dir)
Siwon Kang91daa9d2019-11-22 18:13:05 +0900618 os.mkdir(self.sub_dir_1)
619 os.mkdir(self.sub_dir_2)
620 os.mkdir(self.cgi_dir_in_sub_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400621 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000622 self.file1_path = None
623 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700624 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000625 self.file4_path = None
Siwon Kang91daa9d2019-11-22 18:13:05 +0900626 self.file5_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000627
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000628 # The shebang line should be pure ASCII: use symlink if possible.
629 # See issue #7668.
Steve Dower9048c492019-06-29 10:34:11 -0700630 self._pythonexe_symlink = None
Brian Curtin3b4499c2010-12-28 14:31:47 +0000631 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000632 self.pythonexe = os.path.join(self.parent_dir, 'python')
Steve Dower9048c492019-06-29 10:34:11 -0700633 self._pythonexe_symlink = support.PythonSymlink(self.pythonexe).__enter__()
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000634 else:
635 self.pythonexe = sys.executable
636
Victor Stinner3218c312010-10-17 20:13:36 +0000637 try:
638 # The python executable path is written as the first line of the
639 # CGI Python script. The encoding cookie cannot be used, and so the
640 # path should be encodable to the default script encoding (utf-8)
641 self.pythonexe.encode('utf-8')
642 except UnicodeEncodeError:
643 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200644 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000645
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400646 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
647 with open(self.nocgi_path, 'w') as fp:
648 fp.write(cgi_file1 % self.pythonexe)
649 os.chmod(self.nocgi_path, 0o777)
650
Georg Brandlb533e262008-05-25 18:19:30 +0000651 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000652 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000653 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000654 os.chmod(self.file1_path, 0o777)
655
656 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000657 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000658 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000659 os.chmod(self.file2_path, 0o777)
660
Ned Deily915a30f2014-07-12 22:06:26 -0700661 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
662 with open(self.file3_path, 'w', encoding='utf-8') as file3:
663 file3.write(cgi_file1 % self.pythonexe)
664 os.chmod(self.file3_path, 0o777)
665
Martin Pantera02e18a2015-10-03 05:38:07 +0000666 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
667 with open(self.file4_path, 'w', encoding='utf-8') as file4:
668 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
669 os.chmod(self.file4_path, 0o777)
670
Siwon Kang91daa9d2019-11-22 18:13:05 +0900671 self.file5_path = os.path.join(self.cgi_dir_in_sub_dir, 'file5.py')
672 with open(self.file5_path, 'w', encoding='utf-8') as file5:
673 file5.write(cgi_file1 % self.pythonexe)
674 os.chmod(self.file5_path, 0o777)
675
Miss Islington (bot)b630ca72020-12-05 07:26:37 -0800676 self.file6_path = os.path.join(self.cgi_dir, 'file6.py')
677 with open(self.file6_path, 'w', encoding='utf-8') as file6:
678 file6.write(cgi_file6 % self.pythonexe)
679 os.chmod(self.file6_path, 0o777)
680
Georg Brandlb533e262008-05-25 18:19:30 +0000681 os.chdir(self.parent_dir)
682
683 def tearDown(self):
684 try:
685 os.chdir(self.cwd)
Steve Dower9048c492019-06-29 10:34:11 -0700686 if self._pythonexe_symlink:
687 self._pythonexe_symlink.__exit__(None, None, None)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400688 if self.nocgi_path:
689 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000690 if self.file1_path:
691 os.remove(self.file1_path)
692 if self.file2_path:
693 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700694 if self.file3_path:
695 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000696 if self.file4_path:
697 os.remove(self.file4_path)
Siwon Kang91daa9d2019-11-22 18:13:05 +0900698 if self.file5_path:
699 os.remove(self.file5_path)
Miss Islington (bot)b630ca72020-12-05 07:26:37 -0800700 if self.file6_path:
701 os.remove(self.file6_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700702 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000703 os.rmdir(self.cgi_dir)
Siwon Kang91daa9d2019-11-22 18:13:05 +0900704 os.rmdir(self.cgi_dir_in_sub_dir)
705 os.rmdir(self.sub_dir_2)
706 os.rmdir(self.sub_dir_1)
Georg Brandlb533e262008-05-25 18:19:30 +0000707 os.rmdir(self.parent_dir)
708 finally:
709 BaseTestCase.tearDown(self)
710
Senthil Kumarand70846b2012-04-12 02:34:32 +0800711 def test_url_collapse_path(self):
712 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000713 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800714 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000715 '..': IndexError,
716 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800717 '/': '//',
718 '//': '//',
719 '/\\': '//\\',
720 '/.//': '//',
721 'cgi-bin/file1.py': '/cgi-bin/file1.py',
722 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
723 'a': '//a',
724 '/a': '//a',
725 '//a': '//a',
726 './a': '//a',
727 './C:/': '/C:/',
728 '/a/b': '/a/b',
729 '/a/b/': '/a/b/',
730 '/a/b/.': '/a/b/',
731 '/a/b/c/..': '/a/b/',
732 '/a/b/c/../d': '/a/b/d',
733 '/a/b/c/../d/e/../f': '/a/b/d/f',
734 '/a/b/c/../d/e/../../f': '/a/b/f',
735 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000736 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800737 '/a/b/c/../d/e/../../../f': '/a/f',
738 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000739 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800740 '/a/b/c/../d/e/../../../../f/..': '//',
741 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000742 }
743 for path, expected in test_vectors.items():
744 if isinstance(expected, type) and issubclass(expected, Exception):
745 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800746 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000747 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800748 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000749 self.assertEqual(expected, actual,
750 msg='path = %r\nGot: %r\nWanted: %r' %
751 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000752
Georg Brandlb533e262008-05-25 18:19:30 +0000753 def test_headers_and_content(self):
754 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200755 self.assertEqual(
756 (res.read(), res.getheader('Content-type'), res.status),
757 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000758
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400759 def test_issue19435(self):
760 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200761 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400762
Georg Brandlb533e262008-05-25 18:19:30 +0000763 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000764 params = urllib.parse.urlencode(
765 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000766 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
767 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
768
Antoine Pitroue768c392012-08-05 14:52:45 +0200769 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000770
771 def test_invaliduri(self):
772 res = self.request('/cgi-bin/invalid')
773 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200774 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000775
776 def test_authorization(self):
777 headers = {b'Authorization' : b'Basic ' +
778 base64.b64encode(b'username:pass')}
779 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200780 self.assertEqual(
781 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
782 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000783
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000784 def test_no_leading_slash(self):
785 # http://bugs.python.org/issue2254
786 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200787 self.assertEqual(
788 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
789 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000790
Senthil Kumaran42713722010-10-03 17:55:45 +0000791 def test_os_environ_is_not_altered(self):
792 signature = "Test CGI Server"
793 os.environ['SERVER_SOFTWARE'] = signature
794 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200795 self.assertEqual(
796 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
797 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000798 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
799
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700800 def test_urlquote_decoding_in_cgi_check(self):
801 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200802 self.assertEqual(
803 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
804 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700805
Ned Deily915a30f2014-07-12 22:06:26 -0700806 def test_nested_cgi_path_issue21323(self):
807 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200808 self.assertEqual(
809 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
810 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700811
Martin Pantera02e18a2015-10-03 05:38:07 +0000812 def test_query_with_multiple_question_mark(self):
813 res = self.request('/cgi-bin/file4.py?a=b?c=d')
814 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000815 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000816 (res.read(), res.getheader('Content-type'), res.status))
817
Martin Pantercb29e8c2015-10-03 05:55:46 +0000818 def test_query_with_continuous_slashes(self):
819 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
820 self.assertEqual(
821 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000822 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000823 (res.read(), res.getheader('Content-type'), res.status))
824
Siwon Kang91daa9d2019-11-22 18:13:05 +0900825 def test_cgi_path_in_sub_directories(self):
Pablo Galindo24f5cac2019-12-04 09:29:10 +0000826 try:
827 CGIHTTPRequestHandler.cgi_directories.append('/sub/dir/cgi-bin')
828 res = self.request('/sub/dir/cgi-bin/file5.py')
829 self.assertEqual(
830 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
831 (res.read(), res.getheader('Content-type'), res.status))
832 finally:
833 CGIHTTPRequestHandler.cgi_directories.remove('/sub/dir/cgi-bin')
834
Miss Islington (bot)b630ca72020-12-05 07:26:37 -0800835 def test_accept(self):
836 browser_accept = \
837 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
838 tests = (
839 ((('Accept', browser_accept),), browser_accept),
840 ((), ''),
841 # Hack case to get two values for the one header
842 ((('Accept', 'text/html'), ('ACCEPT', 'text/plain')),
843 'text/html,text/plain'),
844 )
845 for headers, expected in tests:
846 headers = OrderedDict(headers)
847 with self.subTest(headers):
848 res = self.request('/cgi-bin/file6.py', 'GET', headers=headers)
849 self.assertEqual(http.HTTPStatus.OK, res.status)
850 expected = f"'HTTP_ACCEPT': {expected!r}"
851 self.assertIn(expected.encode('ascii'), res.read())
Siwon Kang91daa9d2019-11-22 18:13:05 +0900852
Georg Brandlb533e262008-05-25 18:19:30 +0000853
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000854class SocketlessRequestHandler(SimpleHTTPRequestHandler):
Géry Ogam781266e2019-09-11 15:03:46 +0200855 def __init__(self, directory=None):
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200856 request = mock.Mock()
857 request.makefile.return_value = BytesIO()
Géry Ogam781266e2019-09-11 15:03:46 +0200858 super().__init__(request, None, None, directory=directory)
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200859
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000860 self.get_called = False
861 self.protocol_version = "HTTP/1.1"
862
863 def do_GET(self):
864 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200865 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000866 self.send_header('Content-Type', 'text/html')
867 self.end_headers()
868 self.wfile.write(b'<html><body>Data</body></html>\r\n')
869
870 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000871 pass
872
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000873class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
874 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200875 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000876 return False
877
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800878
879class AuditableBytesIO:
880
881 def __init__(self):
882 self.datas = []
883
884 def write(self, data):
885 self.datas.append(data)
886
887 def getData(self):
888 return b''.join(self.datas)
889
890 @property
891 def numWrites(self):
892 return len(self.datas)
893
894
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000895class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200896 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000897
898 Test the support for the Expect 100-continue header.
899 """
900
901 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
902
903 def setUp (self):
904 self.handler = SocketlessRequestHandler()
905
906 def send_typical_request(self, message):
907 input = BytesIO(message)
908 output = BytesIO()
909 self.handler.rfile = input
910 self.handler.wfile = output
911 self.handler.handle_one_request()
912 output.seek(0)
913 return output.readlines()
914
915 def verify_get_called(self):
916 self.assertTrue(self.handler.get_called)
917
918 def verify_expected_headers(self, headers):
919 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
920 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
921
922 def verify_http_server_response(self, response):
923 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200924 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000925
926 def test_http_1_1(self):
927 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
928 self.verify_http_server_response(result[0])
929 self.verify_expected_headers(result[1:-1])
930 self.verify_get_called()
931 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500932 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
933 self.assertEqual(self.handler.command, 'GET')
934 self.assertEqual(self.handler.path, '/')
935 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
936 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000937
938 def test_http_1_0(self):
939 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
940 self.verify_http_server_response(result[0])
941 self.verify_expected_headers(result[1:-1])
942 self.verify_get_called()
943 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500944 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
945 self.assertEqual(self.handler.command, 'GET')
946 self.assertEqual(self.handler.path, '/')
947 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
948 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000949
950 def test_http_0_9(self):
951 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
952 self.assertEqual(len(result), 1)
953 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
954 self.verify_get_called()
955
Martin Pantere82338d2016-11-19 01:06:37 +0000956 def test_extra_space(self):
957 result = self.send_typical_request(
958 b'GET /spaced out HTTP/1.1\r\n'
959 b'Host: dummy\r\n'
960 b'\r\n'
961 )
962 self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
963 self.verify_expected_headers(result[1:result.index(b'\r\n')])
964 self.assertFalse(self.handler.get_called)
965
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000966 def test_with_continue_1_0(self):
967 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
968 self.verify_http_server_response(result[0])
969 self.verify_expected_headers(result[1:-1])
970 self.verify_get_called()
971 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500972 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
973 self.assertEqual(self.handler.command, 'GET')
974 self.assertEqual(self.handler.path, '/')
975 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
976 headers = (("Expect", "100-continue"),)
977 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000978
979 def test_with_continue_1_1(self):
980 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
981 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500982 self.assertEqual(result[1], b'\r\n')
983 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000984 self.verify_expected_headers(result[2:-1])
985 self.verify_get_called()
986 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500987 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
988 self.assertEqual(self.handler.command, 'GET')
989 self.assertEqual(self.handler.path, '/')
990 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
991 headers = (("Expect", "100-continue"),)
992 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000993
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800994 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000995
996 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800997 output = AuditableBytesIO()
998 handler = SocketlessRequestHandler()
999 handler.rfile = input
1000 handler.wfile = output
1001 handler.request_version = 'HTTP/1.1'
1002 handler.requestline = ''
1003 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +00001004
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +08001005 handler.send_error(418)
1006 self.assertEqual(output.numWrites, 2)
1007
1008 def test_header_buffering_of_send_response_only(self):
1009
1010 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
1011 output = AuditableBytesIO()
1012 handler = SocketlessRequestHandler()
1013 handler.rfile = input
1014 handler.wfile = output
1015 handler.request_version = 'HTTP/1.1'
1016
1017 handler.send_response_only(418)
1018 self.assertEqual(output.numWrites, 0)
1019 handler.end_headers()
1020 self.assertEqual(output.numWrites, 1)
1021
1022 def test_header_buffering_of_send_header(self):
1023
1024 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
1025 output = AuditableBytesIO()
1026 handler = SocketlessRequestHandler()
1027 handler.rfile = input
1028 handler.wfile = output
1029 handler.request_version = 'HTTP/1.1'
1030
1031 handler.send_header('Foo', 'foo')
1032 handler.send_header('bar', 'bar')
1033 self.assertEqual(output.numWrites, 0)
1034 handler.end_headers()
1035 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
1036 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +00001037
1038 def test_header_unbuffered_when_continue(self):
1039
1040 def _readAndReseek(f):
1041 pos = f.tell()
1042 f.seek(0)
1043 data = f.read()
1044 f.seek(pos)
1045 return data
1046
1047 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
1048 output = BytesIO()
1049 self.handler.rfile = input
1050 self.handler.wfile = output
1051 self.handler.request_version = 'HTTP/1.1'
1052
1053 self.handler.handle_one_request()
1054 self.assertNotEqual(_readAndReseek(output), b'')
1055 result = _readAndReseek(output).split(b'\r\n')
1056 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -05001057 self.assertEqual(result[1], b'')
1058 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +00001059
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001060 def test_with_continue_rejected(self):
1061 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
1062 self.handler = RejectingSocketlessRequestHandler()
1063 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
1064 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
1065 self.verify_expected_headers(result[1:-1])
1066 # The expect handler should short circuit the usual get method by
1067 # returning false here, so get_called should be false
1068 self.assertFalse(self.handler.get_called)
1069 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
1070 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
1071
Antoine Pitrouc4924372010-12-16 16:48:36 +00001072 def test_request_length(self):
1073 # Issue #10714: huge request lines are discarded, to avoid Denial
1074 # of Service attacks.
1075 result = self.send_typical_request(b'GET ' + b'x' * 65537)
1076 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
1077 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001078 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001079
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001080 def test_header_length(self):
1081 # Issue #6791: same for headers
1082 result = self.send_typical_request(
1083 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +00001084 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001085 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001086 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1087
Martin Panteracc03192016-04-03 00:45:46 +00001088 def test_too_many_headers(self):
1089 result = self.send_typical_request(
1090 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
1091 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
1092 self.assertFalse(self.handler.get_called)
1093 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1094
Martin Panterda3bb382016-04-11 00:40:08 +00001095 def test_html_escape_on_error(self):
1096 result = self.send_typical_request(
1097 b'<script>alert("hello")</script> / HTTP/1.1')
1098 result = b''.join(result)
1099 text = '<script>alert("hello")</script>'
1100 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
1101
Benjamin Peterson70e28472015-02-17 21:11:10 -05001102 def test_close_connection(self):
1103 # handle_one_request() should be repeatedly called until
1104 # it sets close_connection
1105 def handle_one_request():
1106 self.handler.close_connection = next(close_values)
1107 self.handler.handle_one_request = handle_one_request
1108
1109 close_values = iter((True,))
1110 self.handler.handle()
1111 self.assertRaises(StopIteration, next, close_values)
1112
1113 close_values = iter((False, False, True))
1114 self.handler.handle()
1115 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001116
Berker Peksag04bc5b92016-03-14 06:06:03 +02001117 def test_date_time_string(self):
1118 now = time.time()
1119 # this is the old code that formats the timestamp
1120 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
1121 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
1122 self.handler.weekdayname[wd],
1123 day,
1124 self.handler.monthname[month],
1125 year, hh, mm, ss
1126 )
1127 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
1128
1129
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001130class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
1131 """ Test url parsing """
1132 def setUp(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001133 self.translated_1 = os.path.join(os.getcwd(), 'filename')
1134 self.translated_2 = os.path.join('foo', 'filename')
1135 self.translated_3 = os.path.join('bar', 'filename')
1136 self.handler_1 = SocketlessRequestHandler()
1137 self.handler_2 = SocketlessRequestHandler(directory='foo')
1138 self.handler_3 = SocketlessRequestHandler(directory=pathlib.PurePath('bar'))
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001139
1140 def test_query_arguments(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001141 path = self.handler_1.translate_path('/filename')
1142 self.assertEqual(path, self.translated_1)
1143 path = self.handler_2.translate_path('/filename')
1144 self.assertEqual(path, self.translated_2)
1145 path = self.handler_3.translate_path('/filename')
1146 self.assertEqual(path, self.translated_3)
1147
1148 path = self.handler_1.translate_path('/filename?foo=bar')
1149 self.assertEqual(path, self.translated_1)
1150 path = self.handler_2.translate_path('/filename?foo=bar')
1151 self.assertEqual(path, self.translated_2)
1152 path = self.handler_3.translate_path('/filename?foo=bar')
1153 self.assertEqual(path, self.translated_3)
1154
1155 path = self.handler_1.translate_path('/filename?a=b&spam=eggs#zot')
1156 self.assertEqual(path, self.translated_1)
1157 path = self.handler_2.translate_path('/filename?a=b&spam=eggs#zot')
1158 self.assertEqual(path, self.translated_2)
1159 path = self.handler_3.translate_path('/filename?a=b&spam=eggs#zot')
1160 self.assertEqual(path, self.translated_3)
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001161
1162 def test_start_with_double_slash(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001163 path = self.handler_1.translate_path('//filename')
1164 self.assertEqual(path, self.translated_1)
1165 path = self.handler_2.translate_path('//filename')
1166 self.assertEqual(path, self.translated_2)
1167 path = self.handler_3.translate_path('//filename')
1168 self.assertEqual(path, self.translated_3)
1169
1170 path = self.handler_1.translate_path('//filename?foo=bar')
1171 self.assertEqual(path, self.translated_1)
1172 path = self.handler_2.translate_path('//filename?foo=bar')
1173 self.assertEqual(path, self.translated_2)
1174 path = self.handler_3.translate_path('//filename?foo=bar')
1175 self.assertEqual(path, self.translated_3)
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001176
Martin Panterd274b3f2016-04-18 03:45:18 +00001177 def test_windows_colon(self):
1178 with support.swap_attr(server.os, 'path', ntpath):
Géry Ogam781266e2019-09-11 15:03:46 +02001179 path = self.handler_1.translate_path('c:c:c:foo/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001180 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001181 self.assertEqual(path, self.translated_1)
1182 path = self.handler_2.translate_path('c:c:c:foo/filename')
1183 path = path.replace(ntpath.sep, os.sep)
1184 self.assertEqual(path, self.translated_2)
1185 path = self.handler_3.translate_path('c:c:c:foo/filename')
1186 path = path.replace(ntpath.sep, os.sep)
1187 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001188
Géry Ogam781266e2019-09-11 15:03:46 +02001189 path = self.handler_1.translate_path('\\c:../filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001190 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001191 self.assertEqual(path, self.translated_1)
1192 path = self.handler_2.translate_path('\\c:../filename')
1193 path = path.replace(ntpath.sep, os.sep)
1194 self.assertEqual(path, self.translated_2)
1195 path = self.handler_3.translate_path('\\c:../filename')
1196 path = path.replace(ntpath.sep, os.sep)
1197 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001198
Géry Ogam781266e2019-09-11 15:03:46 +02001199 path = self.handler_1.translate_path('c:\\c:..\\foo/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001200 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001201 self.assertEqual(path, self.translated_1)
1202 path = self.handler_2.translate_path('c:\\c:..\\foo/filename')
1203 path = path.replace(ntpath.sep, os.sep)
1204 self.assertEqual(path, self.translated_2)
1205 path = self.handler_3.translate_path('c:\\c:..\\foo/filename')
1206 path = path.replace(ntpath.sep, os.sep)
1207 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001208
Géry Ogam781266e2019-09-11 15:03:46 +02001209 path = self.handler_1.translate_path('c:c:foo\\c:c:bar/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001210 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001211 self.assertEqual(path, self.translated_1)
1212 path = self.handler_2.translate_path('c:c:foo\\c:c:bar/filename')
1213 path = path.replace(ntpath.sep, os.sep)
1214 self.assertEqual(path, self.translated_2)
1215 path = self.handler_3.translate_path('c:c:foo\\c:c:bar/filename')
1216 path = path.replace(ntpath.sep, os.sep)
1217 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001218
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001219
Berker Peksag366c5702015-02-13 20:48:15 +02001220class MiscTestCase(unittest.TestCase):
1221 def test_all(self):
1222 expected = []
1223 blacklist = {'executable', 'nobody_uid', 'test'}
1224 for name in dir(server):
1225 if name.startswith('_') or name in blacklist:
1226 continue
1227 module_object = getattr(server, name)
1228 if getattr(module_object, '__module__', None) == 'http.server':
1229 expected.append(name)
1230 self.assertCountEqual(server.__all__, expected)
1231
1232
Lisa Roach433433f2018-11-26 10:43:38 -08001233class ScriptTestCase(unittest.TestCase):
Jason R. Coombsf2890842019-02-07 08:22:45 -05001234
1235 def mock_server_class(self):
1236 return mock.MagicMock(
1237 return_value=mock.MagicMock(
1238 __enter__=mock.MagicMock(
1239 return_value=mock.MagicMock(
1240 socket=mock.MagicMock(
1241 getsockname=lambda: ('', 0),
1242 ),
1243 ),
1244 ),
1245 ),
1246 )
1247
1248 @mock.patch('builtins.print')
1249 def test_server_test_unspec(self, _):
1250 mock_server = self.mock_server_class()
1251 server.test(ServerClass=mock_server, bind=None)
1252 self.assertIn(
1253 mock_server.address_family,
1254 (socket.AF_INET6, socket.AF_INET),
1255 )
1256
1257 @mock.patch('builtins.print')
1258 def test_server_test_localhost(self, _):
1259 mock_server = self.mock_server_class()
1260 server.test(ServerClass=mock_server, bind="localhost")
1261 self.assertIn(
1262 mock_server.address_family,
1263 (socket.AF_INET6, socket.AF_INET),
1264 )
1265
1266 ipv6_addrs = (
1267 "::",
1268 "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
1269 "::1",
1270 )
1271
1272 ipv4_addrs = (
1273 "0.0.0.0",
1274 "8.8.8.8",
1275 "127.0.0.1",
1276 )
1277
Lisa Roach433433f2018-11-26 10:43:38 -08001278 @mock.patch('builtins.print')
1279 def test_server_test_ipv6(self, _):
Jason R. Coombsf2890842019-02-07 08:22:45 -05001280 for bind in self.ipv6_addrs:
1281 mock_server = self.mock_server_class()
1282 server.test(ServerClass=mock_server, bind=bind)
1283 self.assertEqual(mock_server.address_family, socket.AF_INET6)
Lisa Roach433433f2018-11-26 10:43:38 -08001284
Jason R. Coombsf2890842019-02-07 08:22:45 -05001285 @mock.patch('builtins.print')
1286 def test_server_test_ipv4(self, _):
1287 for bind in self.ipv4_addrs:
1288 mock_server = self.mock_server_class()
1289 server.test(ServerClass=mock_server, bind=bind)
1290 self.assertEqual(mock_server.address_family, socket.AF_INET)
Lisa Roach433433f2018-11-26 10:43:38 -08001291
1292
Georg Brandlb533e262008-05-25 18:19:30 +00001293def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001294 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001295 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001296 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001297 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001298 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001299 BaseHTTPServerTestCase,
1300 SimpleHTTPServerTestCase,
1301 CGIHTTPServerTestCase,
1302 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001303 MiscTestCase,
Lisa Roach433433f2018-11-26 10:43:38 -08001304 ScriptTestCase
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001305 )
Georg Brandlb533e262008-05-25 18:19:30 +00001306 finally:
1307 os.chdir(cwd)
1308
1309if __name__ == '__main__':
1310 test_main()