blob: 1c980a2fa66eafde98879d7aafebcb67942e2e47 [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')
Georg Brandlb533e262008-05-25 18:19:30 +0000604 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700605 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400606 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000607 self.file1_path = None
608 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700609 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000610 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000611
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000612 # The shebang line should be pure ASCII: use symlink if possible.
613 # See issue #7668.
Steve Dower9048c492019-06-29 10:34:11 -0700614 self._pythonexe_symlink = None
Brian Curtin3b4499c2010-12-28 14:31:47 +0000615 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000616 self.pythonexe = os.path.join(self.parent_dir, 'python')
Steve Dower9048c492019-06-29 10:34:11 -0700617 self._pythonexe_symlink = support.PythonSymlink(self.pythonexe).__enter__()
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000618 else:
619 self.pythonexe = sys.executable
620
Victor Stinner3218c312010-10-17 20:13:36 +0000621 try:
622 # The python executable path is written as the first line of the
623 # CGI Python script. The encoding cookie cannot be used, and so the
624 # path should be encodable to the default script encoding (utf-8)
625 self.pythonexe.encode('utf-8')
626 except UnicodeEncodeError:
627 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200628 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000629
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400630 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
631 with open(self.nocgi_path, 'w') as fp:
632 fp.write(cgi_file1 % self.pythonexe)
633 os.chmod(self.nocgi_path, 0o777)
634
Georg Brandlb533e262008-05-25 18:19:30 +0000635 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000636 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000637 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000638 os.chmod(self.file1_path, 0o777)
639
640 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000641 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000642 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000643 os.chmod(self.file2_path, 0o777)
644
Ned Deily915a30f2014-07-12 22:06:26 -0700645 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
646 with open(self.file3_path, 'w', encoding='utf-8') as file3:
647 file3.write(cgi_file1 % self.pythonexe)
648 os.chmod(self.file3_path, 0o777)
649
Martin Pantera02e18a2015-10-03 05:38:07 +0000650 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
651 with open(self.file4_path, 'w', encoding='utf-8') as file4:
652 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
653 os.chmod(self.file4_path, 0o777)
654
Georg Brandlb533e262008-05-25 18:19:30 +0000655 os.chdir(self.parent_dir)
656
657 def tearDown(self):
658 try:
659 os.chdir(self.cwd)
Steve Dower9048c492019-06-29 10:34:11 -0700660 if self._pythonexe_symlink:
661 self._pythonexe_symlink.__exit__(None, None, None)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400662 if self.nocgi_path:
663 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000664 if self.file1_path:
665 os.remove(self.file1_path)
666 if self.file2_path:
667 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700668 if self.file3_path:
669 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000670 if self.file4_path:
671 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700672 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000673 os.rmdir(self.cgi_dir)
674 os.rmdir(self.parent_dir)
675 finally:
676 BaseTestCase.tearDown(self)
677
Senthil Kumarand70846b2012-04-12 02:34:32 +0800678 def test_url_collapse_path(self):
679 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000680 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800681 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000682 '..': IndexError,
683 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800684 '/': '//',
685 '//': '//',
686 '/\\': '//\\',
687 '/.//': '//',
688 'cgi-bin/file1.py': '/cgi-bin/file1.py',
689 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
690 'a': '//a',
691 '/a': '//a',
692 '//a': '//a',
693 './a': '//a',
694 './C:/': '/C:/',
695 '/a/b': '/a/b',
696 '/a/b/': '/a/b/',
697 '/a/b/.': '/a/b/',
698 '/a/b/c/..': '/a/b/',
699 '/a/b/c/../d': '/a/b/d',
700 '/a/b/c/../d/e/../f': '/a/b/d/f',
701 '/a/b/c/../d/e/../../f': '/a/b/f',
702 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000703 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800704 '/a/b/c/../d/e/../../../f': '/a/f',
705 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000706 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800707 '/a/b/c/../d/e/../../../../f/..': '//',
708 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000709 }
710 for path, expected in test_vectors.items():
711 if isinstance(expected, type) and issubclass(expected, Exception):
712 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800713 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000714 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800715 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000716 self.assertEqual(expected, actual,
717 msg='path = %r\nGot: %r\nWanted: %r' %
718 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000719
Georg Brandlb533e262008-05-25 18:19:30 +0000720 def test_headers_and_content(self):
721 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200722 self.assertEqual(
723 (res.read(), res.getheader('Content-type'), res.status),
724 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000725
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400726 def test_issue19435(self):
727 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200728 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400729
Georg Brandlb533e262008-05-25 18:19:30 +0000730 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000731 params = urllib.parse.urlencode(
732 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000733 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
734 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
735
Antoine Pitroue768c392012-08-05 14:52:45 +0200736 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000737
738 def test_invaliduri(self):
739 res = self.request('/cgi-bin/invalid')
740 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200741 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000742
743 def test_authorization(self):
744 headers = {b'Authorization' : b'Basic ' +
745 base64.b64encode(b'username:pass')}
746 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200747 self.assertEqual(
748 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
749 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000750
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000751 def test_no_leading_slash(self):
752 # http://bugs.python.org/issue2254
753 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200754 self.assertEqual(
755 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
756 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000757
Senthil Kumaran42713722010-10-03 17:55:45 +0000758 def test_os_environ_is_not_altered(self):
759 signature = "Test CGI Server"
760 os.environ['SERVER_SOFTWARE'] = signature
761 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200762 self.assertEqual(
763 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
764 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000765 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
766
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700767 def test_urlquote_decoding_in_cgi_check(self):
768 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200769 self.assertEqual(
770 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
771 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700772
Ned Deily915a30f2014-07-12 22:06:26 -0700773 def test_nested_cgi_path_issue21323(self):
774 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200775 self.assertEqual(
776 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
777 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700778
Martin Pantera02e18a2015-10-03 05:38:07 +0000779 def test_query_with_multiple_question_mark(self):
780 res = self.request('/cgi-bin/file4.py?a=b?c=d')
781 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000782 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000783 (res.read(), res.getheader('Content-type'), res.status))
784
Martin Pantercb29e8c2015-10-03 05:55:46 +0000785 def test_query_with_continuous_slashes(self):
786 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
787 self.assertEqual(
788 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000789 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000790 (res.read(), res.getheader('Content-type'), res.status))
791
Georg Brandlb533e262008-05-25 18:19:30 +0000792
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000793class SocketlessRequestHandler(SimpleHTTPRequestHandler):
Géry Ogam781266e2019-09-11 15:03:46 +0200794 def __init__(self, directory=None):
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200795 request = mock.Mock()
796 request.makefile.return_value = BytesIO()
Géry Ogam781266e2019-09-11 15:03:46 +0200797 super().__init__(request, None, None, directory=directory)
Stéphane Wirtela17a2f52017-05-24 09:29:06 +0200798
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000799 self.get_called = False
800 self.protocol_version = "HTTP/1.1"
801
802 def do_GET(self):
803 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200804 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000805 self.send_header('Content-Type', 'text/html')
806 self.end_headers()
807 self.wfile.write(b'<html><body>Data</body></html>\r\n')
808
809 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000810 pass
811
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000812class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
813 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200814 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000815 return False
816
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800817
818class AuditableBytesIO:
819
820 def __init__(self):
821 self.datas = []
822
823 def write(self, data):
824 self.datas.append(data)
825
826 def getData(self):
827 return b''.join(self.datas)
828
829 @property
830 def numWrites(self):
831 return len(self.datas)
832
833
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000834class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200835 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000836
837 Test the support for the Expect 100-continue header.
838 """
839
840 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
841
842 def setUp (self):
843 self.handler = SocketlessRequestHandler()
844
845 def send_typical_request(self, message):
846 input = BytesIO(message)
847 output = BytesIO()
848 self.handler.rfile = input
849 self.handler.wfile = output
850 self.handler.handle_one_request()
851 output.seek(0)
852 return output.readlines()
853
854 def verify_get_called(self):
855 self.assertTrue(self.handler.get_called)
856
857 def verify_expected_headers(self, headers):
858 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
859 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
860
861 def verify_http_server_response(self, response):
862 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200863 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000864
865 def test_http_1_1(self):
866 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
867 self.verify_http_server_response(result[0])
868 self.verify_expected_headers(result[1:-1])
869 self.verify_get_called()
870 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500871 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
872 self.assertEqual(self.handler.command, 'GET')
873 self.assertEqual(self.handler.path, '/')
874 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
875 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000876
877 def test_http_1_0(self):
878 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
879 self.verify_http_server_response(result[0])
880 self.verify_expected_headers(result[1:-1])
881 self.verify_get_called()
882 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500883 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
884 self.assertEqual(self.handler.command, 'GET')
885 self.assertEqual(self.handler.path, '/')
886 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
887 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000888
889 def test_http_0_9(self):
890 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
891 self.assertEqual(len(result), 1)
892 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
893 self.verify_get_called()
894
Martin Pantere82338d2016-11-19 01:06:37 +0000895 def test_extra_space(self):
896 result = self.send_typical_request(
897 b'GET /spaced out HTTP/1.1\r\n'
898 b'Host: dummy\r\n'
899 b'\r\n'
900 )
901 self.assertTrue(result[0].startswith(b'HTTP/1.1 400 '))
902 self.verify_expected_headers(result[1:result.index(b'\r\n')])
903 self.assertFalse(self.handler.get_called)
904
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000905 def test_with_continue_1_0(self):
906 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\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 headers = (("Expect", "100-continue"),)
916 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000917
918 def test_with_continue_1_1(self):
919 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
920 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500921 self.assertEqual(result[1], b'\r\n')
922 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000923 self.verify_expected_headers(result[2:-1])
924 self.verify_get_called()
925 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500926 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
927 self.assertEqual(self.handler.command, 'GET')
928 self.assertEqual(self.handler.path, '/')
929 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
930 headers = (("Expect", "100-continue"),)
931 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000932
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800933 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000934
935 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800936 output = AuditableBytesIO()
937 handler = SocketlessRequestHandler()
938 handler.rfile = input
939 handler.wfile = output
940 handler.request_version = 'HTTP/1.1'
941 handler.requestline = ''
942 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000943
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800944 handler.send_error(418)
945 self.assertEqual(output.numWrites, 2)
946
947 def test_header_buffering_of_send_response_only(self):
948
949 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
950 output = AuditableBytesIO()
951 handler = SocketlessRequestHandler()
952 handler.rfile = input
953 handler.wfile = output
954 handler.request_version = 'HTTP/1.1'
955
956 handler.send_response_only(418)
957 self.assertEqual(output.numWrites, 0)
958 handler.end_headers()
959 self.assertEqual(output.numWrites, 1)
960
961 def test_header_buffering_of_send_header(self):
962
963 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
964 output = AuditableBytesIO()
965 handler = SocketlessRequestHandler()
966 handler.rfile = input
967 handler.wfile = output
968 handler.request_version = 'HTTP/1.1'
969
970 handler.send_header('Foo', 'foo')
971 handler.send_header('bar', 'bar')
972 self.assertEqual(output.numWrites, 0)
973 handler.end_headers()
974 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
975 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000976
977 def test_header_unbuffered_when_continue(self):
978
979 def _readAndReseek(f):
980 pos = f.tell()
981 f.seek(0)
982 data = f.read()
983 f.seek(pos)
984 return data
985
986 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
987 output = BytesIO()
988 self.handler.rfile = input
989 self.handler.wfile = output
990 self.handler.request_version = 'HTTP/1.1'
991
992 self.handler.handle_one_request()
993 self.assertNotEqual(_readAndReseek(output), b'')
994 result = _readAndReseek(output).split(b'\r\n')
995 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500996 self.assertEqual(result[1], b'')
997 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000998
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000999 def test_with_continue_rejected(self):
1000 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
1001 self.handler = RejectingSocketlessRequestHandler()
1002 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
1003 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
1004 self.verify_expected_headers(result[1:-1])
1005 # The expect handler should short circuit the usual get method by
1006 # returning false here, so get_called should be false
1007 self.assertFalse(self.handler.get_called)
1008 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
1009 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
1010
Antoine Pitrouc4924372010-12-16 16:48:36 +00001011 def test_request_length(self):
1012 # Issue #10714: huge request lines are discarded, to avoid Denial
1013 # of Service attacks.
1014 result = self.send_typical_request(b'GET ' + b'x' * 65537)
1015 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
1016 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001017 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001018
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001019 def test_header_length(self):
1020 # Issue #6791: same for headers
1021 result = self.send_typical_request(
1022 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +00001023 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001024 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -05001025 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1026
Martin Panteracc03192016-04-03 00:45:46 +00001027 def test_too_many_headers(self):
1028 result = self.send_typical_request(
1029 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
1030 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
1031 self.assertFalse(self.handler.get_called)
1032 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
1033
Martin Panterda3bb382016-04-11 00:40:08 +00001034 def test_html_escape_on_error(self):
1035 result = self.send_typical_request(
1036 b'<script>alert("hello")</script> / HTTP/1.1')
1037 result = b''.join(result)
1038 text = '<script>alert("hello")</script>'
1039 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
1040
Benjamin Peterson70e28472015-02-17 21:11:10 -05001041 def test_close_connection(self):
1042 # handle_one_request() should be repeatedly called until
1043 # it sets close_connection
1044 def handle_one_request():
1045 self.handler.close_connection = next(close_values)
1046 self.handler.handle_one_request = handle_one_request
1047
1048 close_values = iter((True,))
1049 self.handler.handle()
1050 self.assertRaises(StopIteration, next, close_values)
1051
1052 close_values = iter((False, False, True))
1053 self.handler.handle()
1054 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001055
Berker Peksag04bc5b92016-03-14 06:06:03 +02001056 def test_date_time_string(self):
1057 now = time.time()
1058 # this is the old code that formats the timestamp
1059 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
1060 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
1061 self.handler.weekdayname[wd],
1062 day,
1063 self.handler.monthname[month],
1064 year, hh, mm, ss
1065 )
1066 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
1067
1068
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001069class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
1070 """ Test url parsing """
1071 def setUp(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001072 self.translated_1 = os.path.join(os.getcwd(), 'filename')
1073 self.translated_2 = os.path.join('foo', 'filename')
1074 self.translated_3 = os.path.join('bar', 'filename')
1075 self.handler_1 = SocketlessRequestHandler()
1076 self.handler_2 = SocketlessRequestHandler(directory='foo')
1077 self.handler_3 = SocketlessRequestHandler(directory=pathlib.PurePath('bar'))
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001078
1079 def test_query_arguments(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001080 path = self.handler_1.translate_path('/filename')
1081 self.assertEqual(path, self.translated_1)
1082 path = self.handler_2.translate_path('/filename')
1083 self.assertEqual(path, self.translated_2)
1084 path = self.handler_3.translate_path('/filename')
1085 self.assertEqual(path, self.translated_3)
1086
1087 path = self.handler_1.translate_path('/filename?foo=bar')
1088 self.assertEqual(path, self.translated_1)
1089 path = self.handler_2.translate_path('/filename?foo=bar')
1090 self.assertEqual(path, self.translated_2)
1091 path = self.handler_3.translate_path('/filename?foo=bar')
1092 self.assertEqual(path, self.translated_3)
1093
1094 path = self.handler_1.translate_path('/filename?a=b&spam=eggs#zot')
1095 self.assertEqual(path, self.translated_1)
1096 path = self.handler_2.translate_path('/filename?a=b&spam=eggs#zot')
1097 self.assertEqual(path, self.translated_2)
1098 path = self.handler_3.translate_path('/filename?a=b&spam=eggs#zot')
1099 self.assertEqual(path, self.translated_3)
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001100
1101 def test_start_with_double_slash(self):
Géry Ogam781266e2019-09-11 15:03:46 +02001102 path = self.handler_1.translate_path('//filename')
1103 self.assertEqual(path, self.translated_1)
1104 path = self.handler_2.translate_path('//filename')
1105 self.assertEqual(path, self.translated_2)
1106 path = self.handler_3.translate_path('//filename')
1107 self.assertEqual(path, self.translated_3)
1108
1109 path = self.handler_1.translate_path('//filename?foo=bar')
1110 self.assertEqual(path, self.translated_1)
1111 path = self.handler_2.translate_path('//filename?foo=bar')
1112 self.assertEqual(path, self.translated_2)
1113 path = self.handler_3.translate_path('//filename?foo=bar')
1114 self.assertEqual(path, self.translated_3)
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001115
Martin Panterd274b3f2016-04-18 03:45:18 +00001116 def test_windows_colon(self):
1117 with support.swap_attr(server.os, 'path', ntpath):
Géry Ogam781266e2019-09-11 15:03:46 +02001118 path = self.handler_1.translate_path('c:c:c:foo/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001119 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001120 self.assertEqual(path, self.translated_1)
1121 path = self.handler_2.translate_path('c:c:c:foo/filename')
1122 path = path.replace(ntpath.sep, os.sep)
1123 self.assertEqual(path, self.translated_2)
1124 path = self.handler_3.translate_path('c:c:c:foo/filename')
1125 path = path.replace(ntpath.sep, os.sep)
1126 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001127
Géry Ogam781266e2019-09-11 15:03:46 +02001128 path = self.handler_1.translate_path('\\c:../filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001129 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001130 self.assertEqual(path, self.translated_1)
1131 path = self.handler_2.translate_path('\\c:../filename')
1132 path = path.replace(ntpath.sep, os.sep)
1133 self.assertEqual(path, self.translated_2)
1134 path = self.handler_3.translate_path('\\c:../filename')
1135 path = path.replace(ntpath.sep, os.sep)
1136 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001137
Géry Ogam781266e2019-09-11 15:03:46 +02001138 path = self.handler_1.translate_path('c:\\c:..\\foo/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001139 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001140 self.assertEqual(path, self.translated_1)
1141 path = self.handler_2.translate_path('c:\\c:..\\foo/filename')
1142 path = path.replace(ntpath.sep, os.sep)
1143 self.assertEqual(path, self.translated_2)
1144 path = self.handler_3.translate_path('c:\\c:..\\foo/filename')
1145 path = path.replace(ntpath.sep, os.sep)
1146 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001147
Géry Ogam781266e2019-09-11 15:03:46 +02001148 path = self.handler_1.translate_path('c:c:foo\\c:c:bar/filename')
Martin Panterd274b3f2016-04-18 03:45:18 +00001149 path = path.replace(ntpath.sep, os.sep)
Géry Ogam781266e2019-09-11 15:03:46 +02001150 self.assertEqual(path, self.translated_1)
1151 path = self.handler_2.translate_path('c:c:foo\\c:c:bar/filename')
1152 path = path.replace(ntpath.sep, os.sep)
1153 self.assertEqual(path, self.translated_2)
1154 path = self.handler_3.translate_path('c:c:foo\\c:c:bar/filename')
1155 path = path.replace(ntpath.sep, os.sep)
1156 self.assertEqual(path, self.translated_3)
Martin Panterd274b3f2016-04-18 03:45:18 +00001157
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001158
Berker Peksag366c5702015-02-13 20:48:15 +02001159class MiscTestCase(unittest.TestCase):
1160 def test_all(self):
1161 expected = []
1162 blacklist = {'executable', 'nobody_uid', 'test'}
1163 for name in dir(server):
1164 if name.startswith('_') or name in blacklist:
1165 continue
1166 module_object = getattr(server, name)
1167 if getattr(module_object, '__module__', None) == 'http.server':
1168 expected.append(name)
1169 self.assertCountEqual(server.__all__, expected)
1170
1171
Lisa Roach433433f2018-11-26 10:43:38 -08001172class ScriptTestCase(unittest.TestCase):
Jason R. Coombsf2890842019-02-07 08:22:45 -05001173
1174 def mock_server_class(self):
1175 return mock.MagicMock(
1176 return_value=mock.MagicMock(
1177 __enter__=mock.MagicMock(
1178 return_value=mock.MagicMock(
1179 socket=mock.MagicMock(
1180 getsockname=lambda: ('', 0),
1181 ),
1182 ),
1183 ),
1184 ),
1185 )
1186
1187 @mock.patch('builtins.print')
1188 def test_server_test_unspec(self, _):
1189 mock_server = self.mock_server_class()
1190 server.test(ServerClass=mock_server, bind=None)
1191 self.assertIn(
1192 mock_server.address_family,
1193 (socket.AF_INET6, socket.AF_INET),
1194 )
1195
1196 @mock.patch('builtins.print')
1197 def test_server_test_localhost(self, _):
1198 mock_server = self.mock_server_class()
1199 server.test(ServerClass=mock_server, bind="localhost")
1200 self.assertIn(
1201 mock_server.address_family,
1202 (socket.AF_INET6, socket.AF_INET),
1203 )
1204
1205 ipv6_addrs = (
1206 "::",
1207 "2001:0db8:85a3:0000:0000:8a2e:0370:7334",
1208 "::1",
1209 )
1210
1211 ipv4_addrs = (
1212 "0.0.0.0",
1213 "8.8.8.8",
1214 "127.0.0.1",
1215 )
1216
Lisa Roach433433f2018-11-26 10:43:38 -08001217 @mock.patch('builtins.print')
1218 def test_server_test_ipv6(self, _):
Jason R. Coombsf2890842019-02-07 08:22:45 -05001219 for bind in self.ipv6_addrs:
1220 mock_server = self.mock_server_class()
1221 server.test(ServerClass=mock_server, bind=bind)
1222 self.assertEqual(mock_server.address_family, socket.AF_INET6)
Lisa Roach433433f2018-11-26 10:43:38 -08001223
Jason R. Coombsf2890842019-02-07 08:22:45 -05001224 @mock.patch('builtins.print')
1225 def test_server_test_ipv4(self, _):
1226 for bind in self.ipv4_addrs:
1227 mock_server = self.mock_server_class()
1228 server.test(ServerClass=mock_server, bind=bind)
1229 self.assertEqual(mock_server.address_family, socket.AF_INET)
Lisa Roach433433f2018-11-26 10:43:38 -08001230
1231
Georg Brandlb533e262008-05-25 18:19:30 +00001232def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001233 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001234 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001235 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001236 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001237 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001238 BaseHTTPServerTestCase,
1239 SimpleHTTPServerTestCase,
1240 CGIHTTPServerTestCase,
1241 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001242 MiscTestCase,
Lisa Roach433433f2018-11-26 10:43:38 -08001243 ScriptTestCase
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001244 )
Georg Brandlb533e262008-05-25 18:19:30 +00001245 finally:
1246 os.chdir(cwd)
1247
1248if __name__ == '__main__':
1249 test_main()