blob: 72e6e0888027febc78efb2b6ca01012e903ee374 [file] [log] [blame]
Georg Brandlb533e262008-05-25 18:19:30 +00001"""Unittests for the various HTTPServer modules.
2
3Written by Cody A.W. Somerville <cody-somerville@ubuntu.com>,
4Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest.
5"""
6
Georg Brandl24420152008-05-26 16:32:26 +00007from http.server import BaseHTTPRequestHandler, HTTPServer, \
8 SimpleHTTPRequestHandler, CGIHTTPRequestHandler
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02009from http import server, HTTPStatus
Georg Brandlb533e262008-05-25 18:19:30 +000010
11import os
12import sys
Senthil Kumaran0f476d42010-09-30 06:09:18 +000013import re
Georg Brandlb533e262008-05-25 18:19:30 +000014import base64
Martin Panterd274b3f2016-04-18 03:45:18 +000015import ntpath
Georg Brandlb533e262008-05-25 18:19:30 +000016import shutil
Jeremy Hylton1afc1692008-06-18 20:49:58 +000017import urllib.parse
Serhiy Storchakacb5bc402014-08-17 08:22:11 +030018import html
Georg Brandl24420152008-05-26 16:32:26 +000019import http.client
Georg Brandlb533e262008-05-25 18:19:30 +000020import tempfile
Senthil Kumaran0f476d42010-09-30 06:09:18 +000021from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000022
23import unittest
24from test import support
Victor Stinner45df8202010-04-28 22:31:17 +000025threading = support.import_module('threading')
Georg Brandlb533e262008-05-25 18:19:30 +000026
Georg Brandlb533e262008-05-25 18:19:30 +000027class NoLogRequestHandler:
28 def log_message(self, *args):
29 # don't write log messages to stderr
30 pass
31
Barry Warsaw820c1202008-06-12 04:06:45 +000032 def read(self, n=None):
33 return ''
34
Georg Brandlb533e262008-05-25 18:19:30 +000035
36class TestServerThread(threading.Thread):
37 def __init__(self, test_object, request_handler):
38 threading.Thread.__init__(self)
39 self.request_handler = request_handler
40 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000041
42 def run(self):
Antoine Pitroucb342182011-03-21 00:26:51 +010043 self.server = HTTPServer(('localhost', 0), self.request_handler)
44 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000045 self.test_object.server_started.set()
46 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000047 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000048 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000049 finally:
50 self.server.server_close()
51
52 def stop(self):
53 self.server.shutdown()
54
55
56class BaseTestCase(unittest.TestCase):
57 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000058 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000059 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000060 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000061 self.thread = TestServerThread(self, self.request_handler)
62 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000063 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000064
65 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000066 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020067 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000068 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000069 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000070
71 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010072 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000073 self.connection.request(method, uri, body, headers)
74 return self.connection.getresponse()
75
76
77class BaseHTTPServerTestCase(BaseTestCase):
78 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
79 protocol_version = 'HTTP/1.1'
80 default_request_version = 'HTTP/1.1'
81
82 def do_TEST(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020083 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000084 self.send_header('Content-Type', 'text/html')
85 self.send_header('Connection', 'close')
86 self.end_headers()
87
88 def do_KEEP(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020089 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000090 self.send_header('Content-Type', 'text/html')
91 self.send_header('Connection', 'keep-alive')
92 self.end_headers()
93
94 def do_KEYERROR(self):
95 self.send_error(999)
96
Senthil Kumaran52d27202012-10-10 23:16:21 -070097 def do_NOTFOUND(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020098 self.send_error(HTTPStatus.NOT_FOUND)
Senthil Kumaran52d27202012-10-10 23:16:21 -070099
Senthil Kumaran26886442013-03-15 07:53:21 -0700100 def do_EXPLAINERROR(self):
101 self.send_error(999, "Short Message",
Martin Panter46f50722016-05-26 05:35:26 +0000102 "This is a long \n explanation")
Senthil Kumaran26886442013-03-15 07:53:21 -0700103
Georg Brandlb533e262008-05-25 18:19:30 +0000104 def do_CUSTOM(self):
105 self.send_response(999)
106 self.send_header('Content-Type', 'text/html')
107 self.send_header('Connection', 'close')
108 self.end_headers()
109
Armin Ronacher8d96d772011-01-22 13:13:05 +0000110 def do_LATINONEHEADER(self):
111 self.send_response(999)
112 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000113 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000114 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000115 body = self.headers['x-special-incoming'].encode('utf-8')
116 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000117
Martin Pantere42e1292016-06-08 08:29:13 +0000118 def do_SEND_ERROR(self):
119 self.send_error(int(self.path[1:]))
120
121 def do_HEAD(self):
122 self.send_error(int(self.path[1:]))
123
Georg Brandlb533e262008-05-25 18:19:30 +0000124 def setUp(self):
125 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100126 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000127 self.con.connect()
128
129 def test_command(self):
130 self.con.request('GET', '/')
131 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200132 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000133
134 def test_request_line_trimming(self):
135 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400136 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000137 self.con.endheaders()
138 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200139 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000140
141 def test_version_bogus(self):
142 self.con._http_vsn_str = 'FUBAR'
143 self.con.putrequest('GET', '/')
144 self.con.endheaders()
145 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200146 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000147
148 def test_version_digits(self):
149 self.con._http_vsn_str = 'HTTP/9.9.9'
150 self.con.putrequest('GET', '/')
151 self.con.endheaders()
152 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200153 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000154
155 def test_version_none_get(self):
156 self.con._http_vsn_str = ''
157 self.con.putrequest('GET', '/')
158 self.con.endheaders()
159 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200160 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000161
162 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400163 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000164 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400165 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000166 self.con.endheaders()
167 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200168 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000169
170 def test_version_invalid(self):
171 self.con._http_vsn = 99
172 self.con._http_vsn_str = 'HTTP/9.9'
173 self.con.putrequest('GET', '/')
174 self.con.endheaders()
175 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200176 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000177
178 def test_send_blank(self):
179 self.con._http_vsn_str = ''
180 self.con.putrequest('', '')
181 self.con.endheaders()
182 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200183 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000184
185 def test_header_close(self):
186 self.con.putrequest('GET', '/')
187 self.con.putheader('Connection', 'close')
188 self.con.endheaders()
189 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200190 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000191
192 def test_head_keep_alive(self):
193 self.con._http_vsn_str = 'HTTP/1.1'
194 self.con.putrequest('GET', '/')
195 self.con.putheader('Connection', 'keep-alive')
196 self.con.endheaders()
197 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200198 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000199
200 def test_handler(self):
201 self.con.request('TEST', '/')
202 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200203 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000204
205 def test_return_header_keep_alive(self):
206 self.con.request('KEEP', '/')
207 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000208 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000209 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000210 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000211
212 def test_internal_key_error(self):
213 self.con.request('KEYERROR', '/')
214 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000215 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000216
217 def test_return_custom_status(self):
218 self.con.request('CUSTOM', '/')
219 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000220 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000221
Senthil Kumaran26886442013-03-15 07:53:21 -0700222 def test_return_explain_error(self):
223 self.con.request('EXPLAINERROR', '/')
224 res = self.con.getresponse()
225 self.assertEqual(res.status, 999)
226 self.assertTrue(int(res.getheader('Content-Length')))
227
Armin Ronacher8d96d772011-01-22 13:13:05 +0000228 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000229 self.con.request('LATINONEHEADER', '/', headers={
230 'X-Special-Incoming': 'Ärger mit Unicode'
231 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000232 res = self.con.getresponse()
233 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000234 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000235
Senthil Kumaran52d27202012-10-10 23:16:21 -0700236 def test_error_content_length(self):
237 # Issue #16088: standard error responses should have a content-length
238 self.con.request('NOTFOUND', '/')
239 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200240 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
241
Senthil Kumaran52d27202012-10-10 23:16:21 -0700242 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700243 self.assertEqual(int(res.getheader('Content-Length')), len(data))
244
Martin Pantere42e1292016-06-08 08:29:13 +0000245 def test_send_error(self):
246 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
247 HTTPStatus.RESET_CONTENT)
248 for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED,
249 HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT,
250 HTTPStatus.SWITCHING_PROTOCOLS):
251 self.con.request('SEND_ERROR', '/{}'.format(code))
252 res = self.con.getresponse()
253 self.assertEqual(code, res.status)
254 self.assertEqual(None, res.getheader('Content-Length'))
255 self.assertEqual(None, res.getheader('Content-Type'))
256 if code not in allow_transfer_encoding_codes:
257 self.assertEqual(None, res.getheader('Transfer-Encoding'))
258
259 data = res.read()
260 self.assertEqual(b'', data)
261
262 def test_head_via_send_error(self):
263 allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED,
264 HTTPStatus.RESET_CONTENT)
265 for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT,
266 HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT,
267 HTTPStatus.SWITCHING_PROTOCOLS):
268 self.con.request('HEAD', '/{}'.format(code))
269 res = self.con.getresponse()
270 self.assertEqual(code, res.status)
271 if code == HTTPStatus.OK:
272 self.assertTrue(int(res.getheader('Content-Length')) > 0)
273 self.assertIn('text/html', res.getheader('Content-Type'))
274 else:
275 self.assertEqual(None, res.getheader('Content-Length'))
276 self.assertEqual(None, res.getheader('Content-Type'))
277 if code not in allow_transfer_encoding_codes:
278 self.assertEqual(None, res.getheader('Transfer-Encoding'))
279
280 data = res.read()
281 self.assertEqual(b'', data)
282
Georg Brandlb533e262008-05-25 18:19:30 +0000283
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200284class RequestHandlerLoggingTestCase(BaseTestCase):
285 class request_handler(BaseHTTPRequestHandler):
286 protocol_version = 'HTTP/1.1'
287 default_request_version = 'HTTP/1.1'
288
289 def do_GET(self):
290 self.send_response(HTTPStatus.OK)
291 self.end_headers()
292
293 def do_ERROR(self):
294 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
295
296 def test_get(self):
297 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
298 self.con.connect()
299
300 with support.captured_stderr() as err:
301 self.con.request('GET', '/')
302 self.con.getresponse()
303
304 self.assertTrue(
305 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
306
307 def test_err(self):
308 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
309 self.con.connect()
310
311 with support.captured_stderr() as err:
312 self.con.request('ERROR', '/')
313 self.con.getresponse()
314
315 lines = err.getvalue().split('\n')
316 self.assertTrue(lines[0].endswith('code 404, message File not found'))
317 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
318
319
Georg Brandlb533e262008-05-25 18:19:30 +0000320class SimpleHTTPServerTestCase(BaseTestCase):
321 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
322 pass
323
324 def setUp(self):
325 BaseTestCase.setUp(self)
326 self.cwd = os.getcwd()
327 basetempdir = tempfile.gettempdir()
328 os.chdir(basetempdir)
329 self.data = b'We are the knights who say Ni!'
330 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
331 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panterfc475a92016-04-09 04:56:10 +0000332 self.base_url = '/' + self.tempdir_name
Brett Cannon105df5d2010-10-29 23:43:42 +0000333 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
334 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000335
336 def tearDown(self):
337 try:
338 os.chdir(self.cwd)
339 try:
340 shutil.rmtree(self.tempdir)
341 except:
342 pass
343 finally:
344 BaseTestCase.tearDown(self)
345
346 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300347 def close_conn():
348 """Don't close reader yet so we can check if there was leftover
349 buffered input"""
350 nonlocal reader
351 reader = response.fp
352 response.fp = None
353 reader = None
354 response._close_conn = close_conn
355
Georg Brandlb533e262008-05-25 18:19:30 +0000356 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000357 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000358 self.assertEqual(response.status, status)
359 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000360 if data:
361 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300362 # Ensure the server has not set up a persistent connection, and has
363 # not sent any extra data
364 self.assertEqual(response.version, 10)
365 self.assertEqual(response.msg.get("Connection", "close"), "close")
366 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
367
368 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300369 return body
370
Ned Deily14183202015-01-05 01:02:30 -0800371 @support.requires_mac_ver(10, 5)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300372 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
373 'need support.TESTFN_UNDECODABLE')
374 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300375 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300376 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
377 with open(os.path.join(self.tempdir, filename), 'wb') as f:
378 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000379 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300380 if sys.platform == 'darwin':
381 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
382 # UTF-8 into a percent-encoded value.
383 for name in os.listdir(self.tempdir):
384 if name != 'test': # Ignore a filename created in setUp().
385 filename = name
386 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200387 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300388 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
389 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300390 .encode(enc, 'surrogateescape'), body)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300391 self.assertIn(('>%s<' % html.escape(filename))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300392 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000393 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200394 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300395 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000396
397 def test_get(self):
398 #constructs the path relative to the root directory of the HTTPServer
Martin Panterfc475a92016-04-09 04:56:10 +0000399 response = self.request(self.base_url + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200400 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700401 # check for trailing "/" which should return 404. See Issue17324
Martin Panterfc475a92016-04-09 04:56:10 +0000402 response = self.request(self.base_url + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200403 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Martin Panterfc475a92016-04-09 04:56:10 +0000404 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200405 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000406 response = self.request(self.base_url)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200407 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000408 response = self.request(self.base_url + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200409 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000410 response = self.request(self.base_url + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200411 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600412 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000413 self.base_url + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000414 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200415 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000416 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200417 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300418
419 data = b"Dummy index file\r\n"
420 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
421 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000422 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300423 self.check_status_and_reason(response, HTTPStatus.OK, data)
424
425 # chmod() doesn't work as expected on Windows, and filesystem
426 # permissions are ignored by root on Unix.
427 if os.name == 'posix' and os.geteuid() != 0:
428 os.chmod(self.tempdir, 0)
429 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000430 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200431 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300432 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000433 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000434
435 def test_head(self):
436 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000437 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200438 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000439 self.assertEqual(response.getheader('content-length'),
440 str(len(self.data)))
441 self.assertEqual(response.getheader('content-type'),
442 'application/octet-stream')
443
444 def test_invalid_requests(self):
445 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200446 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000447 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400448 response = self.request('/', method='custom')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200449 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000450 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200451 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000452
Martin Panterfc475a92016-04-09 04:56:10 +0000453 def test_path_without_leading_slash(self):
454 response = self.request(self.tempdir_name + '/test')
455 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
456 response = self.request(self.tempdir_name + '/test/')
457 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
458 response = self.request(self.tempdir_name + '/')
459 self.check_status_and_reason(response, HTTPStatus.OK)
460 response = self.request(self.tempdir_name)
461 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
462 response = self.request(self.tempdir_name + '/?hi=2')
463 self.check_status_and_reason(response, HTTPStatus.OK)
464 response = self.request(self.tempdir_name + '?hi=1')
465 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
466 self.assertEqual(response.getheader("Location"),
467 self.tempdir_name + "/?hi=1")
468
Georg Brandlb533e262008-05-25 18:19:30 +0000469
470cgi_file1 = """\
471#!%s
472
473print("Content-type: text/html")
474print()
475print("Hello World")
476"""
477
478cgi_file2 = """\
479#!%s
480import cgi
481
482print("Content-type: text/html")
483print()
484
485form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000486print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
487 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000488"""
489
Martin Pantera02e18a2015-10-03 05:38:07 +0000490cgi_file4 = """\
491#!%s
492import os
493
494print("Content-type: text/html")
495print()
496
497print(os.environ["%s"])
498"""
499
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100500
501@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
502 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000503class CGIHTTPServerTestCase(BaseTestCase):
504 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
505 pass
506
Antoine Pitroue768c392012-08-05 14:52:45 +0200507 linesep = os.linesep.encode('ascii')
508
Georg Brandlb533e262008-05-25 18:19:30 +0000509 def setUp(self):
510 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000511 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000512 self.parent_dir = tempfile.mkdtemp()
513 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700514 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000515 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700516 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400517 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000518 self.file1_path = None
519 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700520 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000521 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000522
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000523 # The shebang line should be pure ASCII: use symlink if possible.
524 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000525 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000526 self.pythonexe = os.path.join(self.parent_dir, 'python')
527 os.symlink(sys.executable, self.pythonexe)
528 else:
529 self.pythonexe = sys.executable
530
Victor Stinner3218c312010-10-17 20:13:36 +0000531 try:
532 # The python executable path is written as the first line of the
533 # CGI Python script. The encoding cookie cannot be used, and so the
534 # path should be encodable to the default script encoding (utf-8)
535 self.pythonexe.encode('utf-8')
536 except UnicodeEncodeError:
537 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200538 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000539
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400540 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
541 with open(self.nocgi_path, 'w') as fp:
542 fp.write(cgi_file1 % self.pythonexe)
543 os.chmod(self.nocgi_path, 0o777)
544
Georg Brandlb533e262008-05-25 18:19:30 +0000545 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000546 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000547 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000548 os.chmod(self.file1_path, 0o777)
549
550 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000551 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000552 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000553 os.chmod(self.file2_path, 0o777)
554
Ned Deily915a30f2014-07-12 22:06:26 -0700555 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
556 with open(self.file3_path, 'w', encoding='utf-8') as file3:
557 file3.write(cgi_file1 % self.pythonexe)
558 os.chmod(self.file3_path, 0o777)
559
Martin Pantera02e18a2015-10-03 05:38:07 +0000560 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
561 with open(self.file4_path, 'w', encoding='utf-8') as file4:
562 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
563 os.chmod(self.file4_path, 0o777)
564
Georg Brandlb533e262008-05-25 18:19:30 +0000565 os.chdir(self.parent_dir)
566
567 def tearDown(self):
568 try:
569 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000570 if self.pythonexe != sys.executable:
571 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400572 if self.nocgi_path:
573 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000574 if self.file1_path:
575 os.remove(self.file1_path)
576 if self.file2_path:
577 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700578 if self.file3_path:
579 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000580 if self.file4_path:
581 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700582 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000583 os.rmdir(self.cgi_dir)
584 os.rmdir(self.parent_dir)
585 finally:
586 BaseTestCase.tearDown(self)
587
Senthil Kumarand70846b2012-04-12 02:34:32 +0800588 def test_url_collapse_path(self):
589 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000590 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800591 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000592 '..': IndexError,
593 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800594 '/': '//',
595 '//': '//',
596 '/\\': '//\\',
597 '/.//': '//',
598 'cgi-bin/file1.py': '/cgi-bin/file1.py',
599 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
600 'a': '//a',
601 '/a': '//a',
602 '//a': '//a',
603 './a': '//a',
604 './C:/': '/C:/',
605 '/a/b': '/a/b',
606 '/a/b/': '/a/b/',
607 '/a/b/.': '/a/b/',
608 '/a/b/c/..': '/a/b/',
609 '/a/b/c/../d': '/a/b/d',
610 '/a/b/c/../d/e/../f': '/a/b/d/f',
611 '/a/b/c/../d/e/../../f': '/a/b/f',
612 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000613 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800614 '/a/b/c/../d/e/../../../f': '/a/f',
615 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000616 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800617 '/a/b/c/../d/e/../../../../f/..': '//',
618 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000619 }
620 for path, expected in test_vectors.items():
621 if isinstance(expected, type) and issubclass(expected, Exception):
622 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800623 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000624 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800625 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000626 self.assertEqual(expected, actual,
627 msg='path = %r\nGot: %r\nWanted: %r' %
628 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000629
Georg Brandlb533e262008-05-25 18:19:30 +0000630 def test_headers_and_content(self):
631 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200632 self.assertEqual(
633 (res.read(), res.getheader('Content-type'), res.status),
634 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000635
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400636 def test_issue19435(self):
637 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200638 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400639
Georg Brandlb533e262008-05-25 18:19:30 +0000640 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000641 params = urllib.parse.urlencode(
642 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000643 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
644 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
645
Antoine Pitroue768c392012-08-05 14:52:45 +0200646 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000647
648 def test_invaliduri(self):
649 res = self.request('/cgi-bin/invalid')
650 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200651 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000652
653 def test_authorization(self):
654 headers = {b'Authorization' : b'Basic ' +
655 base64.b64encode(b'username:pass')}
656 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200657 self.assertEqual(
658 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
659 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000660
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000661 def test_no_leading_slash(self):
662 # http://bugs.python.org/issue2254
663 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200664 self.assertEqual(
665 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
666 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000667
Senthil Kumaran42713722010-10-03 17:55:45 +0000668 def test_os_environ_is_not_altered(self):
669 signature = "Test CGI Server"
670 os.environ['SERVER_SOFTWARE'] = signature
671 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200672 self.assertEqual(
673 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
674 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000675 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
676
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700677 def test_urlquote_decoding_in_cgi_check(self):
678 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200679 self.assertEqual(
680 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
681 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700682
Ned Deily915a30f2014-07-12 22:06:26 -0700683 def test_nested_cgi_path_issue21323(self):
684 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200685 self.assertEqual(
686 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
687 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700688
Martin Pantera02e18a2015-10-03 05:38:07 +0000689 def test_query_with_multiple_question_mark(self):
690 res = self.request('/cgi-bin/file4.py?a=b?c=d')
691 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000692 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000693 (res.read(), res.getheader('Content-type'), res.status))
694
Martin Pantercb29e8c2015-10-03 05:55:46 +0000695 def test_query_with_continuous_slashes(self):
696 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
697 self.assertEqual(
698 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000699 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000700 (res.read(), res.getheader('Content-type'), res.status))
701
Georg Brandlb533e262008-05-25 18:19:30 +0000702
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000703class SocketlessRequestHandler(SimpleHTTPRequestHandler):
704 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000705 self.get_called = False
706 self.protocol_version = "HTTP/1.1"
707
708 def do_GET(self):
709 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200710 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000711 self.send_header('Content-Type', 'text/html')
712 self.end_headers()
713 self.wfile.write(b'<html><body>Data</body></html>\r\n')
714
715 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000716 pass
717
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000718class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
719 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200720 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000721 return False
722
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800723
724class AuditableBytesIO:
725
726 def __init__(self):
727 self.datas = []
728
729 def write(self, data):
730 self.datas.append(data)
731
732 def getData(self):
733 return b''.join(self.datas)
734
735 @property
736 def numWrites(self):
737 return len(self.datas)
738
739
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000740class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200741 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000742
743 Test the support for the Expect 100-continue header.
744 """
745
746 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
747
748 def setUp (self):
749 self.handler = SocketlessRequestHandler()
750
751 def send_typical_request(self, message):
752 input = BytesIO(message)
753 output = BytesIO()
754 self.handler.rfile = input
755 self.handler.wfile = output
756 self.handler.handle_one_request()
757 output.seek(0)
758 return output.readlines()
759
760 def verify_get_called(self):
761 self.assertTrue(self.handler.get_called)
762
763 def verify_expected_headers(self, headers):
764 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
765 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
766
767 def verify_http_server_response(self, response):
768 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200769 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000770
771 def test_http_1_1(self):
772 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
773 self.verify_http_server_response(result[0])
774 self.verify_expected_headers(result[1:-1])
775 self.verify_get_called()
776 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500777 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
778 self.assertEqual(self.handler.command, 'GET')
779 self.assertEqual(self.handler.path, '/')
780 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
781 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000782
783 def test_http_1_0(self):
784 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
785 self.verify_http_server_response(result[0])
786 self.verify_expected_headers(result[1:-1])
787 self.verify_get_called()
788 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500789 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
790 self.assertEqual(self.handler.command, 'GET')
791 self.assertEqual(self.handler.path, '/')
792 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
793 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000794
795 def test_http_0_9(self):
796 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
797 self.assertEqual(len(result), 1)
798 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
799 self.verify_get_called()
800
801 def test_with_continue_1_0(self):
802 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
803 self.verify_http_server_response(result[0])
804 self.verify_expected_headers(result[1:-1])
805 self.verify_get_called()
806 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500807 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
808 self.assertEqual(self.handler.command, 'GET')
809 self.assertEqual(self.handler.path, '/')
810 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
811 headers = (("Expect", "100-continue"),)
812 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000813
814 def test_with_continue_1_1(self):
815 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
816 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500817 self.assertEqual(result[1], b'\r\n')
818 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000819 self.verify_expected_headers(result[2:-1])
820 self.verify_get_called()
821 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500822 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
823 self.assertEqual(self.handler.command, 'GET')
824 self.assertEqual(self.handler.path, '/')
825 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
826 headers = (("Expect", "100-continue"),)
827 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000828
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800829 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000830
831 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800832 output = AuditableBytesIO()
833 handler = SocketlessRequestHandler()
834 handler.rfile = input
835 handler.wfile = output
836 handler.request_version = 'HTTP/1.1'
837 handler.requestline = ''
838 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000839
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800840 handler.send_error(418)
841 self.assertEqual(output.numWrites, 2)
842
843 def test_header_buffering_of_send_response_only(self):
844
845 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
846 output = AuditableBytesIO()
847 handler = SocketlessRequestHandler()
848 handler.rfile = input
849 handler.wfile = output
850 handler.request_version = 'HTTP/1.1'
851
852 handler.send_response_only(418)
853 self.assertEqual(output.numWrites, 0)
854 handler.end_headers()
855 self.assertEqual(output.numWrites, 1)
856
857 def test_header_buffering_of_send_header(self):
858
859 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
860 output = AuditableBytesIO()
861 handler = SocketlessRequestHandler()
862 handler.rfile = input
863 handler.wfile = output
864 handler.request_version = 'HTTP/1.1'
865
866 handler.send_header('Foo', 'foo')
867 handler.send_header('bar', 'bar')
868 self.assertEqual(output.numWrites, 0)
869 handler.end_headers()
870 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
871 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000872
873 def test_header_unbuffered_when_continue(self):
874
875 def _readAndReseek(f):
876 pos = f.tell()
877 f.seek(0)
878 data = f.read()
879 f.seek(pos)
880 return data
881
882 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
883 output = BytesIO()
884 self.handler.rfile = input
885 self.handler.wfile = output
886 self.handler.request_version = 'HTTP/1.1'
887
888 self.handler.handle_one_request()
889 self.assertNotEqual(_readAndReseek(output), b'')
890 result = _readAndReseek(output).split(b'\r\n')
891 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500892 self.assertEqual(result[1], b'')
893 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000894
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000895 def test_with_continue_rejected(self):
896 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
897 self.handler = RejectingSocketlessRequestHandler()
898 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
899 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
900 self.verify_expected_headers(result[1:-1])
901 # The expect handler should short circuit the usual get method by
902 # returning false here, so get_called should be false
903 self.assertFalse(self.handler.get_called)
904 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
905 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
906
Antoine Pitrouc4924372010-12-16 16:48:36 +0000907 def test_request_length(self):
908 # Issue #10714: huge request lines are discarded, to avoid Denial
909 # of Service attacks.
910 result = self.send_typical_request(b'GET ' + b'x' * 65537)
911 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
912 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500913 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000914
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000915 def test_header_length(self):
916 # Issue #6791: same for headers
917 result = self.send_typical_request(
918 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
919 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
920 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500921 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
922
Martin Panteracc03192016-04-03 00:45:46 +0000923 def test_too_many_headers(self):
924 result = self.send_typical_request(
925 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
926 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
927 self.assertFalse(self.handler.get_called)
928 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
929
Benjamin Peterson70e28472015-02-17 21:11:10 -0500930 def test_close_connection(self):
931 # handle_one_request() should be repeatedly called until
932 # it sets close_connection
933 def handle_one_request():
934 self.handler.close_connection = next(close_values)
935 self.handler.handle_one_request = handle_one_request
936
937 close_values = iter((True,))
938 self.handler.handle()
939 self.assertRaises(StopIteration, next, close_values)
940
941 close_values = iter((False, False, True))
942 self.handler.handle()
943 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000944
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000945class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
946 """ Test url parsing """
947 def setUp(self):
948 self.translated = os.getcwd()
949 self.translated = os.path.join(self.translated, 'filename')
950 self.handler = SocketlessRequestHandler()
951
952 def test_query_arguments(self):
953 path = self.handler.translate_path('/filename')
954 self.assertEqual(path, self.translated)
955 path = self.handler.translate_path('/filename?foo=bar')
956 self.assertEqual(path, self.translated)
957 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
958 self.assertEqual(path, self.translated)
959
960 def test_start_with_double_slash(self):
961 path = self.handler.translate_path('//filename')
962 self.assertEqual(path, self.translated)
963 path = self.handler.translate_path('//filename?foo=bar')
964 self.assertEqual(path, self.translated)
965
Martin Panterd274b3f2016-04-18 03:45:18 +0000966 def test_windows_colon(self):
967 with support.swap_attr(server.os, 'path', ntpath):
968 path = self.handler.translate_path('c:c:c:foo/filename')
969 path = path.replace(ntpath.sep, os.sep)
970 self.assertEqual(path, self.translated)
971
972 path = self.handler.translate_path('\\c:../filename')
973 path = path.replace(ntpath.sep, os.sep)
974 self.assertEqual(path, self.translated)
975
976 path = self.handler.translate_path('c:\\c:..\\foo/filename')
977 path = path.replace(ntpath.sep, os.sep)
978 self.assertEqual(path, self.translated)
979
980 path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
981 path = path.replace(ntpath.sep, os.sep)
982 self.assertEqual(path, self.translated)
983
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000984
Berker Peksag366c5702015-02-13 20:48:15 +0200985class MiscTestCase(unittest.TestCase):
986 def test_all(self):
987 expected = []
988 blacklist = {'executable', 'nobody_uid', 'test'}
989 for name in dir(server):
990 if name.startswith('_') or name in blacklist:
991 continue
992 module_object = getattr(server, name)
993 if getattr(module_object, '__module__', None) == 'http.server':
994 expected.append(name)
995 self.assertCountEqual(server.__all__, expected)
996
997
Georg Brandlb533e262008-05-25 18:19:30 +0000998def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000999 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +00001000 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001001 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001002 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001003 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001004 BaseHTTPServerTestCase,
1005 SimpleHTTPServerTestCase,
1006 CGIHTTPServerTestCase,
1007 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001008 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001009 )
Georg Brandlb533e262008-05-25 18:19:30 +00001010 finally:
1011 os.chdir(cwd)
1012
1013if __name__ == '__main__':
1014 test_main()