blob: c442f5571a86823e8e7b725e6277e292348dad15 [file] [log] [blame]
Georg Brandlb533e262008-05-25 18:19:30 +00001"""Unittests for the various HTTPServer modules.
2
3Written by Cody A.W. Somerville <cody-somerville@ubuntu.com>,
4Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest.
5"""
6
Georg Brandl24420152008-05-26 16:32:26 +00007from http.server import BaseHTTPRequestHandler, HTTPServer, \
8 SimpleHTTPRequestHandler, CGIHTTPRequestHandler
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02009from http import server, HTTPStatus
Georg Brandlb533e262008-05-25 18:19:30 +000010
11import os
Lisa Roach433433f2018-11-26 10:43:38 -080012import socket
Georg Brandlb533e262008-05-25 18:19:30 +000013import sys
Senthil Kumaran0f476d42010-09-30 06:09:18 +000014import re
Georg Brandlb533e262008-05-25 18:19:30 +000015import base64
Martin Panterd274b3f2016-04-18 03:45:18 +000016import ntpath
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
Georg Brandl24420152008-05-26 16:32:26 +000022import 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
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100589
590@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
591 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000592class CGIHTTPServerTestCase(BaseTestCase):
593 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
594 pass
595
Antoine Pitroue768c392012-08-05 14:52:45 +0200596 linesep = os.linesep.encode('ascii')
597
Georg Brandlb533e262008-05-25 18:19:30 +0000598 def setUp(self):
599 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000600 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000601 self.parent_dir = tempfile.mkdtemp()
602 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700603 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Siwon Kang91daa9d2019-11-22 18:13:05 +0900604 self.sub_dir_1 = os.path.join(self.parent_dir, 'sub')
605 self.sub_dir_2 = os.path.join(self.sub_dir_1, 'dir')
606 self.cgi_dir_in_sub_dir = os.path.join(self.sub_dir_2, 'cgi-bin')
Georg Brandlb533e262008-05-25 18:19:30 +0000607 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700608 os.mkdir(self.cgi_child_dir)
Siwon Kang91daa9d2019-11-22 18:13:05 +0900609 os.mkdir(self.sub_dir_1)
610 os.mkdir(self.sub_dir_2)
611 os.mkdir(self.cgi_dir_in_sub_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400612 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000613 self.file1_path = None
614 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700615 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000616 self.file4_path = None
Siwon Kang91daa9d2019-11-22 18:13:05 +0900617 self.file5_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000618
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000619 # The shebang line should be pure ASCII: use symlink if possible.
620 # See issue #7668.
Steve Dower9048c492019-06-29 10:34:11 -0700621 self._pythonexe_symlink = None
Brian Curtin3b4499c2010-12-28 14:31:47 +0000622 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000623 self.pythonexe = os.path.join(self.parent_dir, 'python')
Steve Dower9048c492019-06-29 10:34:11 -0700624 self._pythonexe_symlink = support.PythonSymlink(self.pythonexe).__enter__()
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000625 else:
626 self.pythonexe = sys.executable
627
Victor Stinner3218c312010-10-17 20:13:36 +0000628 try:
629 # The python executable path is written as the first line of the
630 # CGI Python script. The encoding cookie cannot be used, and so the
631 # path should be encodable to the default script encoding (utf-8)
632 self.pythonexe.encode('utf-8')
633 except UnicodeEncodeError:
634 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200635 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000636
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400637 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
638 with open(self.nocgi_path, 'w') as fp:
639 fp.write(cgi_file1 % self.pythonexe)
640 os.chmod(self.nocgi_path, 0o777)
641
Georg Brandlb533e262008-05-25 18:19:30 +0000642 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000643 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000644 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000645 os.chmod(self.file1_path, 0o777)
646
647 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000648 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000649 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000650 os.chmod(self.file2_path, 0o777)
651
Ned Deily915a30f2014-07-12 22:06:26 -0700652 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
653 with open(self.file3_path, 'w', encoding='utf-8') as file3:
654 file3.write(cgi_file1 % self.pythonexe)
655 os.chmod(self.file3_path, 0o777)
656
Martin Pantera02e18a2015-10-03 05:38:07 +0000657 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
658 with open(self.file4_path, 'w', encoding='utf-8') as file4:
659 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
660 os.chmod(self.file4_path, 0o777)
661
Siwon Kang91daa9d2019-11-22 18:13:05 +0900662 self.file5_path = os.path.join(self.cgi_dir_in_sub_dir, 'file5.py')
663 with open(self.file5_path, 'w', encoding='utf-8') as file5:
664 file5.write(cgi_file1 % self.pythonexe)
665 os.chmod(self.file5_path, 0o777)
666
Georg Brandlb533e262008-05-25 18:19:30 +0000667 os.chdir(self.parent_dir)
668
669 def tearDown(self):
670 try:
671 os.chdir(self.cwd)
Steve Dower9048c492019-06-29 10:34:11 -0700672 if self._pythonexe_symlink:
673 self._pythonexe_symlink.__exit__(None, None, None)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400674 if self.nocgi_path:
675 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000676 if self.file1_path:
677 os.remove(self.file1_path)
678 if self.file2_path:
679 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700680 if self.file3_path:
681 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000682 if self.file4_path:
683 os.remove(self.file4_path)
Siwon Kang91daa9d2019-11-22 18:13:05 +0900684 if self.file5_path:
685 os.remove(self.file5_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700686 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000687 os.rmdir(self.cgi_dir)
Siwon Kang91daa9d2019-11-22 18:13:05 +0900688 os.rmdir(self.cgi_dir_in_sub_dir)
689 os.rmdir(self.sub_dir_2)
690 os.rmdir(self.sub_dir_1)
Georg Brandlb533e262008-05-25 18:19:30 +0000691 os.rmdir(self.parent_dir)
692 finally:
693 BaseTestCase.tearDown(self)
694
Senthil Kumarand70846b2012-04-12 02:34:32 +0800695 def test_url_collapse_path(self):
696 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000697 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800698 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000699 '..': IndexError,
700 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800701 '/': '//',
702 '//': '//',
703 '/\\': '//\\',
704 '/.//': '//',
705 'cgi-bin/file1.py': '/cgi-bin/file1.py',
706 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
707 'a': '//a',
708 '/a': '//a',
709 '//a': '//a',
710 './a': '//a',
711 './C:/': '/C:/',
712 '/a/b': '/a/b',
713 '/a/b/': '/a/b/',
714 '/a/b/.': '/a/b/',
715 '/a/b/c/..': '/a/b/',
716 '/a/b/c/../d': '/a/b/d',
717 '/a/b/c/../d/e/../f': '/a/b/d/f',
718 '/a/b/c/../d/e/../../f': '/a/b/f',
719 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000720 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800721 '/a/b/c/../d/e/../../../f': '/a/f',
722 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000723 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800724 '/a/b/c/../d/e/../../../../f/..': '//',
725 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000726 }
727 for path, expected in test_vectors.items():
728 if isinstance(expected, type) and issubclass(expected, Exception):
729 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800730 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000731 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800732 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000733 self.assertEqual(expected, actual,
734 msg='path = %r\nGot: %r\nWanted: %r' %
735 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000736
Georg Brandlb533e262008-05-25 18:19:30 +0000737 def test_headers_and_content(self):
738 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200739 self.assertEqual(
740 (res.read(), res.getheader('Content-type'), res.status),
741 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000742
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400743 def test_issue19435(self):
744 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200745 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400746
Georg Brandlb533e262008-05-25 18:19:30 +0000747 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000748 params = urllib.parse.urlencode(
749 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000750 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
751 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
752
Antoine Pitroue768c392012-08-05 14:52:45 +0200753 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000754
755 def test_invaliduri(self):
756 res = self.request('/cgi-bin/invalid')
757 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200758 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000759
760 def test_authorization(self):
761 headers = {b'Authorization' : b'Basic ' +
762 base64.b64encode(b'username:pass')}
763 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
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))
Georg Brandlb533e262008-05-25 18:19:30 +0000767
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000768 def test_no_leading_slash(self):
769 # http://bugs.python.org/issue2254
770 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200771 self.assertEqual(
772 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
773 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000774
Senthil Kumaran42713722010-10-03 17:55:45 +0000775 def test_os_environ_is_not_altered(self):
776 signature = "Test CGI Server"
777 os.environ['SERVER_SOFTWARE'] = signature
778 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200779 self.assertEqual(
780 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
781 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000782 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
783
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700784 def test_urlquote_decoding_in_cgi_check(self):
785 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200786 self.assertEqual(
787 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
788 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700789
Ned Deily915a30f2014-07-12 22:06:26 -0700790 def test_nested_cgi_path_issue21323(self):
791 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200792 self.assertEqual(
793 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
794 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700795
Martin Pantera02e18a2015-10-03 05:38:07 +0000796 def test_query_with_multiple_question_mark(self):
797 res = self.request('/cgi-bin/file4.py?a=b?c=d')
798 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000799 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000800 (res.read(), res.getheader('Content-type'), res.status))
801
Martin Pantercb29e8c2015-10-03 05:55:46 +0000802 def test_query_with_continuous_slashes(self):
803 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
804 self.assertEqual(
805 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000806 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000807 (res.read(), res.getheader('Content-type'), res.status))
808
Siwon Kang91daa9d2019-11-22 18:13:05 +0900809 def test_cgi_path_in_sub_directories(self):
Pablo Galindo24f5cac2019-12-04 09:29:10 +0000810 try:
811 CGIHTTPRequestHandler.cgi_directories.append('/sub/dir/cgi-bin')
812 res = self.request('/sub/dir/cgi-bin/file5.py')
813 self.assertEqual(
814 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
815 (res.read(), res.getheader('Content-type'), res.status))
816 finally:
817 CGIHTTPRequestHandler.cgi_directories.remove('/sub/dir/cgi-bin')
818
Siwon Kang91daa9d2019-11-22 18:13:05 +0900819
Georg Brandlb533e262008-05-25 18:19:30 +0000820
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000821class SocketlessRequestHandler(SimpleHTTPRequestHandler):
Géry Ogam781266e2019-09-11 15:03:46 +0200822 def __init__(self, directory=None):
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200823 request = mock.Mock()
824 request.makefile.return_value = BytesIO()
Géry Ogam781266e2019-09-11 15:03:46 +0200825 super().__init__(request, None, None, directory=directory)
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200826
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000827 self.get_called = False
828 self.protocol_version = "HTTP/1.1"
829
830 def do_GET(self):
831 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200832 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000833 self.send_header('Content-Type', 'text/html')
834 self.end_headers()
835 self.wfile.write(b'<html><body>Data</body></html>\r\n')
836
837 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000838 pass
839
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000840class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
841 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200842 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000843 return False
844
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800845
846class AuditableBytesIO:
847
848 def __init__(self):
849 self.datas = []
850
851 def write(self, data):
852 self.datas.append(data)
853
854 def getData(self):
855 return b''.join(self.datas)
856
857 @property
858 def numWrites(self):
859 return len(self.datas)
860
861
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000862class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200863 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000864
865 Test the support for the Expect 100-continue header.
866 """
867
868 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
869
870 def setUp (self):
871 self.handler = SocketlessRequestHandler()
872
873 def send_typical_request(self, message):
874 input = BytesIO(message)
875 output = BytesIO()
876 self.handler.rfile = input
877 self.handler.wfile = output
878 self.handler.handle_one_request()
879 output.seek(0)
880 return output.readlines()
881
882 def verify_get_called(self):
883 self.assertTrue(self.handler.get_called)
884
885 def verify_expected_headers(self, headers):
886 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
887 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
888
889 def verify_http_server_response(self, response):
890 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200891 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000892
893 def test_http_1_1(self):
894 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
895 self.verify_http_server_response(result[0])
896 self.verify_expected_headers(result[1:-1])
897 self.verify_get_called()
898 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500899 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
900 self.assertEqual(self.handler.command, 'GET')
901 self.assertEqual(self.handler.path, '/')
902 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
903 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000904
905 def test_http_1_0(self):
906 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
907 self.verify_http_server_response(result[0])
908 self.verify_expected_headers(result[1:-1])
909 self.verify_get_called()
910 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500911 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
912 self.assertEqual(self.handler.command, 'GET')
913 self.assertEqual(self.handler.path, '/')
914 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
915 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000916
917 def test_http_0_9(self):
918 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
919 self.assertEqual(len(result), 1)
920 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
921 self.verify_get_called()
922
Martin Pantere82338d2016-11-19 01:06:37 +0000923 def test_extra_space(self):
924 result = self.send_typical_request(
925 b'GET /spaced out HTTP/1.1\r\n'
926 b'Host: dummy\r\n'
927 b'\r\n'
928 )
929 self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
930 self.verify_expected_headers(result[1:result.index(b'\r\n')])
931 self.assertFalse(self.handler.get_called)
932
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000933 def test_with_continue_1_0(self):
934 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
935 self.verify_http_server_response(result[0])
936 self.verify_expected_headers(result[1:-1])
937 self.verify_get_called()
938 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500939 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
940 self.assertEqual(self.handler.command, 'GET')
941 self.assertEqual(self.handler.path, '/')
942 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
943 headers = (("Expect", "100-continue"),)
944 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000945
946 def test_with_continue_1_1(self):
947 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
948 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500949 self.assertEqual(result[1], b'\r\n')
950 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000951 self.verify_expected_headers(result[2:-1])
952 self.verify_get_called()
953 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500954 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
955 self.assertEqual(self.handler.command, 'GET')
956 self.assertEqual(self.handler.path, '/')
957 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
958 headers = (("Expect", "100-continue"),)
959 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000960
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800961 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000962
963 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800964 output = AuditableBytesIO()
965 handler = SocketlessRequestHandler()
966 handler.rfile = input
967 handler.wfile = output
968 handler.request_version = 'HTTP/1.1'
969 handler.requestline = ''
970 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000971
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800972 handler.send_error(418)
973 self.assertEqual(output.numWrites, 2)
974
975 def test_header_buffering_of_send_response_only(self):
976
977 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
978 output = AuditableBytesIO()
979 handler = SocketlessRequestHandler()
980 handler.rfile = input
981 handler.wfile = output
982 handler.request_version = 'HTTP/1.1'
983
984 handler.send_response_only(418)
985 self.assertEqual(output.numWrites, 0)
986 handler.end_headers()
987 self.assertEqual(output.numWrites, 1)
988
989 def test_header_buffering_of_send_header(self):
990
991 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
992 output = AuditableBytesIO()
993 handler = SocketlessRequestHandler()
994 handler.rfile = input
995 handler.wfile = output
996 handler.request_version = 'HTTP/1.1'
997
998 handler.send_header('Foo', 'foo')
999 handler.send_header('bar', 'bar')
1000 self.assertEqual(output.numWrites, 0)
1001 handler.end_headers()
1002 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
1003 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +00001004
1005 def test_header_unbuffered_when_continue(self):
1006
1007 def _readAndReseek(f):
1008 pos = f.tell()
1009 f.seek(0)
1010 data = f.read()
1011 f.seek(pos)
1012 return data
1013
1014 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
1015 output = BytesIO()
1016 self.handler.rfile = input
1017 self.handler.wfile = output
1018 self.handler.request_version = 'HTTP/1.1'
1019
1020 self.handler.handle_one_request()
1021 self.assertNotEqual(_readAndReseek(output), b'')
1022 result = _readAndReseek(output).split(b'\r\n')
1023 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -05001024 self.assertEqual(result[1], b'')
1025 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +00001026
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001027 def test_with_continue_rejected(self):
1028 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
1029 self.handler = RejectingSocketlessRequestHandler()
1030 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
1031 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
1032 self.verify_expected_headers(result[1:-1])
1033 # The expect handler should short circuit the usual get method by
1034 # returning false here, so get_called should be false
1035 self.assertFalse(self.handler.get_called)
1036 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
1037 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
1038
Antoine Pitrouc4924372010-12-16 16:48:36 +00001039 def test_request_length(self):
1040 # Issue #10714: huge request lines are discarded, to avoid Denial
1041 # of Service attacks.
1042 result = self.send_typical_request(b'GET ' + b'x' * 65537)
1043 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
1044 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001045 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001046
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001047 def test_header_length(self):
1048 # Issue #6791: same for headers
1049 result = self.send_typical_request(
1050 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +00001051 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001052 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001053 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1054
Martin Panteracc03192016-04-03 00:45:46 +00001055 def test_too_many_headers(self):
1056 result = self.send_typical_request(
1057 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
1058 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
1059 self.assertFalse(self.handler.get_called)
1060 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1061
Martin Panterda3bb382016-04-11 00:40:08 +00001062 def test_html_escape_on_error(self):
1063 result = self.send_typical_request(
1064 b'<script>alert("hello")</script> / HTTP/1.1')
1065 result = b''.join(result)
1066 text = '<script>alert("hello")</script>'
1067 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
1068
Benjamin Peterson70e28472015-02-17 21:11:10 -05001069 def test_close_connection(self):
1070 # handle_one_request() should be repeatedly called until
1071 # it sets close_connection
1072 def handle_one_request():
1073 self.handler.close_connection = next(close_values)
1074 self.handler.handle_one_request = handle_one_request
1075
1076 close_values = iter((True,))
1077 self.handler.handle()
1078 self.assertRaises(StopIteration, next, close_values)
1079
1080 close_values = iter((False, False, True))
1081 self.handler.handle()
1082 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001083
Berker Peksag04bc5b92016-03-14 06:06:03 +02001084 def test_date_time_string(self):
1085 now = time.time()
1086 # this is the old code that formats the timestamp
1087 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
1088 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
1089 self.handler.weekdayname[wd],
1090 day,
1091 self.handler.monthname[month],
1092 year, hh, mm, ss
1093 )
1094 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
1095
1096
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001097class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
1098 """ Test url parsing """
1099 def setUp(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001100 self.translated_1 = os.path.join(os.getcwd(), 'filename')
1101 self.translated_2 = os.path.join('foo', 'filename')
1102 self.translated_3 = os.path.join('bar', 'filename')
1103 self.handler_1 = SocketlessRequestHandler()
1104 self.handler_2 = SocketlessRequestHandler(directory='foo')
1105 self.handler_3 = SocketlessRequestHandler(directory=pathlib.PurePath('bar'))
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001106
1107 def test_query_arguments(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001108 path = self.handler_1.translate_path('/filename')
1109 self.assertEqual(path, self.translated_1)
1110 path = self.handler_2.translate_path('/filename')
1111 self.assertEqual(path, self.translated_2)
1112 path = self.handler_3.translate_path('/filename')
1113 self.assertEqual(path, self.translated_3)
1114
1115 path = self.handler_1.translate_path('/filename?foo=bar')
1116 self.assertEqual(path, self.translated_1)
1117 path = self.handler_2.translate_path('/filename?foo=bar')
1118 self.assertEqual(path, self.translated_2)
1119 path = self.handler_3.translate_path('/filename?foo=bar')
1120 self.assertEqual(path, self.translated_3)
1121
1122 path = self.handler_1.translate_path('/filename?a=b&spam=eggs#zot')
1123 self.assertEqual(path, self.translated_1)
1124 path = self.handler_2.translate_path('/filename?a=b&spam=eggs#zot')
1125 self.assertEqual(path, self.translated_2)
1126 path = self.handler_3.translate_path('/filename?a=b&spam=eggs#zot')
1127 self.assertEqual(path, self.translated_3)
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001128
1129 def test_start_with_double_slash(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001130 path = self.handler_1.translate_path('//filename')
1131 self.assertEqual(path, self.translated_1)
1132 path = self.handler_2.translate_path('//filename')
1133 self.assertEqual(path, self.translated_2)
1134 path = self.handler_3.translate_path('//filename')
1135 self.assertEqual(path, self.translated_3)
1136
1137 path = self.handler_1.translate_path('//filename?foo=bar')
1138 self.assertEqual(path, self.translated_1)
1139 path = self.handler_2.translate_path('//filename?foo=bar')
1140 self.assertEqual(path, self.translated_2)
1141 path = self.handler_3.translate_path('//filename?foo=bar')
1142 self.assertEqual(path, self.translated_3)
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001143
Martin Panterd274b3f2016-04-18 03:45:18 +00001144 def test_windows_colon(self):
1145 with support.swap_attr(server.os, 'path', ntpath):
Géry Ogam781266e2019-09-11 15:03:46 +02001146 path = self.handler_1.translate_path('c:c:c:foo/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001147 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001148 self.assertEqual(path, self.translated_1)
1149 path = self.handler_2.translate_path('c:c:c:foo/filename')
1150 path = path.replace(ntpath.sep, os.sep)
1151 self.assertEqual(path, self.translated_2)
1152 path = self.handler_3.translate_path('c:c:c:foo/filename')
1153 path = path.replace(ntpath.sep, os.sep)
1154 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001155
Géry Ogam781266e2019-09-11 15:03:46 +02001156 path = self.handler_1.translate_path('\\c:../filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001157 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001158 self.assertEqual(path, self.translated_1)
1159 path = self.handler_2.translate_path('\\c:../filename')
1160 path = path.replace(ntpath.sep, os.sep)
1161 self.assertEqual(path, self.translated_2)
1162 path = self.handler_3.translate_path('\\c:../filename')
1163 path = path.replace(ntpath.sep, os.sep)
1164 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001165
Géry Ogam781266e2019-09-11 15:03:46 +02001166 path = self.handler_1.translate_path('c:\\c:..\\foo/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001167 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001168 self.assertEqual(path, self.translated_1)
1169 path = self.handler_2.translate_path('c:\\c:..\\foo/filename')
1170 path = path.replace(ntpath.sep, os.sep)
1171 self.assertEqual(path, self.translated_2)
1172 path = self.handler_3.translate_path('c:\\c:..\\foo/filename')
1173 path = path.replace(ntpath.sep, os.sep)
1174 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001175
Géry Ogam781266e2019-09-11 15:03:46 +02001176 path = self.handler_1.translate_path('c:c:foo\\c:c:bar/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001177 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001178 self.assertEqual(path, self.translated_1)
1179 path = self.handler_2.translate_path('c:c:foo\\c:c:bar/filename')
1180 path = path.replace(ntpath.sep, os.sep)
1181 self.assertEqual(path, self.translated_2)
1182 path = self.handler_3.translate_path('c:c:foo\\c:c:bar/filename')
1183 path = path.replace(ntpath.sep, os.sep)
1184 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001185
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001186
Berker Peksag366c5702015-02-13 20:48:15 +02001187class MiscTestCase(unittest.TestCase):
1188 def test_all(self):
1189 expected = []
1190 blacklist = {'executable', 'nobody_uid', 'test'}
1191 for name in dir(server):
1192 if name.startswith('_') or name in blacklist:
1193 continue
1194 module_object = getattr(server, name)
1195 if getattr(module_object, '__module__', None) == 'http.server':
1196 expected.append(name)
1197 self.assertCountEqual(server.__all__, expected)
1198
1199
Lisa Roach433433f2018-11-26 10:43:38 -08001200class ScriptTestCase(unittest.TestCase):
Jason R. Coombsf2890842019-02-07 08:22:45 -05001201
1202 def mock_server_class(self):
1203 return mock.MagicMock(
1204 return_value=mock.MagicMock(
1205 __enter__=mock.MagicMock(
1206 return_value=mock.MagicMock(
1207 socket=mock.MagicMock(
1208 getsockname=lambda: ('', 0),
1209 ),
1210 ),
1211 ),
1212 ),
1213 )
1214
1215 @mock.patch('builtins.print')
1216 def test_server_test_unspec(self, _):
1217 mock_server = self.mock_server_class()
1218 server.test(ServerClass=mock_server, bind=None)
1219 self.assertIn(
1220 mock_server.address_family,
1221 (socket.AF_INET6, socket.AF_INET),
1222 )
1223
1224 @mock.patch('builtins.print')
1225 def test_server_test_localhost(self, _):
1226 mock_server = self.mock_server_class()
1227 server.test(ServerClass=mock_server, bind="localhost")
1228 self.assertIn(
1229 mock_server.address_family,
1230 (socket.AF_INET6, socket.AF_INET),
1231 )
1232
1233 ipv6_addrs = (
1234 "::",
1235 "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
1236 "::1",
1237 )
1238
1239 ipv4_addrs = (
1240 "0.0.0.0",
1241 "8.8.8.8",
1242 "127.0.0.1",
1243 )
1244
Lisa Roach433433f2018-11-26 10:43:38 -08001245 @mock.patch('builtins.print')
1246 def test_server_test_ipv6(self, _):
Jason R. Coombsf2890842019-02-07 08:22:45 -05001247 for bind in self.ipv6_addrs:
1248 mock_server = self.mock_server_class()
1249 server.test(ServerClass=mock_server, bind=bind)
1250 self.assertEqual(mock_server.address_family, socket.AF_INET6)
Lisa Roach433433f2018-11-26 10:43:38 -08001251
Jason R. Coombsf2890842019-02-07 08:22:45 -05001252 @mock.patch('builtins.print')
1253 def test_server_test_ipv4(self, _):
1254 for bind in self.ipv4_addrs:
1255 mock_server = self.mock_server_class()
1256 server.test(ServerClass=mock_server, bind=bind)
1257 self.assertEqual(mock_server.address_family, socket.AF_INET)
Lisa Roach433433f2018-11-26 10:43:38 -08001258
1259
Georg Brandlb533e262008-05-25 18:19:30 +00001260def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001261 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001262 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001263 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001264 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001265 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001266 BaseHTTPServerTestCase,
1267 SimpleHTTPServerTestCase,
1268 CGIHTTPServerTestCase,
1269 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001270 MiscTestCase,
Lisa Roach433433f2018-11-26 10:43:38 -08001271 ScriptTestCase
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001272 )
Georg Brandlb533e262008-05-25 18:19:30 +00001273 finally:
1274 os.chdir(cwd)
1275
1276if __name__ == '__main__':
1277 test_main()