blob: b313aee63d6723a4577850086b78509d3c9cb513 [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
Berker Peksag04bc5b92016-03-14 06:06:03 +020021import time
Senthil Kumaran0f476d42010-09-30 06:09:18 +000022from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000023
24import unittest
25from test import support
Victor Stinner45df8202010-04-28 22:31:17 +000026threading = support.import_module('threading')
Georg Brandlb533e262008-05-25 18:19:30 +000027
Georg Brandlb533e262008-05-25 18:19:30 +000028class NoLogRequestHandler:
29 def log_message(self, *args):
30 # don't write log messages to stderr
31 pass
32
Barry Warsaw820c1202008-06-12 04:06:45 +000033 def read(self, n=None):
34 return ''
35
Georg Brandlb533e262008-05-25 18:19:30 +000036
37class TestServerThread(threading.Thread):
38 def __init__(self, test_object, request_handler):
39 threading.Thread.__init__(self)
40 self.request_handler = request_handler
41 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000042
43 def run(self):
Antoine Pitroucb342182011-03-21 00:26:51 +010044 self.server = HTTPServer(('localhost', 0), self.request_handler)
45 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000046 self.test_object.server_started.set()
47 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000048 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000049 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000050 finally:
51 self.server.server_close()
52
53 def stop(self):
54 self.server.shutdown()
55
56
57class BaseTestCase(unittest.TestCase):
58 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000059 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000060 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000061 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000062 self.thread = TestServerThread(self, self.request_handler)
63 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000064 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000065
66 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000067 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020068 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000069 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000070 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000071
72 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010073 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000074 self.connection.request(method, uri, body, headers)
75 return self.connection.getresponse()
76
77
78class BaseHTTPServerTestCase(BaseTestCase):
79 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
80 protocol_version = 'HTTP/1.1'
81 default_request_version = 'HTTP/1.1'
82
83 def do_TEST(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020084 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000085 self.send_header('Content-Type', 'text/html')
86 self.send_header('Connection', 'close')
87 self.end_headers()
88
89 def do_KEEP(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020090 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000091 self.send_header('Content-Type', 'text/html')
92 self.send_header('Connection', 'keep-alive')
93 self.end_headers()
94
95 def do_KEYERROR(self):
96 self.send_error(999)
97
Senthil Kumaran52d27202012-10-10 23:16:21 -070098 def do_NOTFOUND(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020099 self.send_error(HTTPStatus.NOT_FOUND)
Senthil Kumaran52d27202012-10-10 23:16:21 -0700100
Senthil Kumaran26886442013-03-15 07:53:21 -0700101 def do_EXPLAINERROR(self):
102 self.send_error(999, "Short Message",
103 "This is a long \n explaination")
104
Georg Brandlb533e262008-05-25 18:19:30 +0000105 def do_CUSTOM(self):
106 self.send_response(999)
107 self.send_header('Content-Type', 'text/html')
108 self.send_header('Connection', 'close')
109 self.end_headers()
110
Armin Ronacher8d96d772011-01-22 13:13:05 +0000111 def do_LATINONEHEADER(self):
112 self.send_response(999)
113 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000114 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000115 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000116 body = self.headers['x-special-incoming'].encode('utf-8')
117 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000118
Georg Brandlb533e262008-05-25 18:19:30 +0000119 def setUp(self):
120 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100121 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000122 self.con.connect()
123
124 def test_command(self):
125 self.con.request('GET', '/')
126 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200127 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000128
129 def test_request_line_trimming(self):
130 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400131 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000132 self.con.endheaders()
133 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200134 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000135
136 def test_version_bogus(self):
137 self.con._http_vsn_str = 'FUBAR'
138 self.con.putrequest('GET', '/')
139 self.con.endheaders()
140 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200141 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000142
143 def test_version_digits(self):
144 self.con._http_vsn_str = 'HTTP/9.9.9'
145 self.con.putrequest('GET', '/')
146 self.con.endheaders()
147 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200148 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000149
150 def test_version_none_get(self):
151 self.con._http_vsn_str = ''
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.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000156
157 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400158 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000159 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400160 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000161 self.con.endheaders()
162 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200163 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000164
165 def test_version_invalid(self):
166 self.con._http_vsn = 99
167 self.con._http_vsn_str = 'HTTP/9.9'
168 self.con.putrequest('GET', '/')
169 self.con.endheaders()
170 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200171 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000172
173 def test_send_blank(self):
174 self.con._http_vsn_str = ''
175 self.con.putrequest('', '')
176 self.con.endheaders()
177 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200178 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000179
180 def test_header_close(self):
181 self.con.putrequest('GET', '/')
182 self.con.putheader('Connection', 'close')
183 self.con.endheaders()
184 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200185 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000186
187 def test_head_keep_alive(self):
188 self.con._http_vsn_str = 'HTTP/1.1'
189 self.con.putrequest('GET', '/')
190 self.con.putheader('Connection', 'keep-alive')
191 self.con.endheaders()
192 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200193 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000194
195 def test_handler(self):
196 self.con.request('TEST', '/')
197 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200198 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000199
200 def test_return_header_keep_alive(self):
201 self.con.request('KEEP', '/')
202 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000203 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000204 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000205 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000206
207 def test_internal_key_error(self):
208 self.con.request('KEYERROR', '/')
209 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000210 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000211
212 def test_return_custom_status(self):
213 self.con.request('CUSTOM', '/')
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
Senthil Kumaran26886442013-03-15 07:53:21 -0700217 def test_return_explain_error(self):
218 self.con.request('EXPLAINERROR', '/')
219 res = self.con.getresponse()
220 self.assertEqual(res.status, 999)
221 self.assertTrue(int(res.getheader('Content-Length')))
222
Armin Ronacher8d96d772011-01-22 13:13:05 +0000223 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000224 self.con.request('LATINONEHEADER', '/', headers={
225 'X-Special-Incoming': 'Ärger mit Unicode'
226 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000227 res = self.con.getresponse()
228 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000229 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000230
Senthil Kumaran52d27202012-10-10 23:16:21 -0700231 def test_error_content_length(self):
232 # Issue #16088: standard error responses should have a content-length
233 self.con.request('NOTFOUND', '/')
234 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200235 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
236
Senthil Kumaran52d27202012-10-10 23:16:21 -0700237 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700238 self.assertEqual(int(res.getheader('Content-Length')), len(data))
239
Georg Brandlb533e262008-05-25 18:19:30 +0000240
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200241class RequestHandlerLoggingTestCase(BaseTestCase):
242 class request_handler(BaseHTTPRequestHandler):
243 protocol_version = 'HTTP/1.1'
244 default_request_version = 'HTTP/1.1'
245
246 def do_GET(self):
247 self.send_response(HTTPStatus.OK)
248 self.end_headers()
249
250 def do_ERROR(self):
251 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
252
253 def test_get(self):
254 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
255 self.con.connect()
256
257 with support.captured_stderr() as err:
258 self.con.request('GET', '/')
259 self.con.getresponse()
260
261 self.assertTrue(
262 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
263
264 def test_err(self):
265 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
266 self.con.connect()
267
268 with support.captured_stderr() as err:
269 self.con.request('ERROR', '/')
270 self.con.getresponse()
271
272 lines = err.getvalue().split('\n')
273 self.assertTrue(lines[0].endswith('code 404, message File not found'))
274 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
275
276
Georg Brandlb533e262008-05-25 18:19:30 +0000277class SimpleHTTPServerTestCase(BaseTestCase):
278 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
279 pass
280
281 def setUp(self):
282 BaseTestCase.setUp(self)
283 self.cwd = os.getcwd()
284 basetempdir = tempfile.gettempdir()
285 os.chdir(basetempdir)
286 self.data = b'We are the knights who say Ni!'
287 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
288 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panterfc475a92016-04-09 04:56:10 +0000289 self.base_url = '/' + self.tempdir_name
Brett Cannon105df5d2010-10-29 23:43:42 +0000290 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
291 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000292
293 def tearDown(self):
294 try:
295 os.chdir(self.cwd)
296 try:
297 shutil.rmtree(self.tempdir)
298 except:
299 pass
300 finally:
301 BaseTestCase.tearDown(self)
302
303 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300304 def close_conn():
305 """Don't close reader yet so we can check if there was leftover
306 buffered input"""
307 nonlocal reader
308 reader = response.fp
309 response.fp = None
310 reader = None
311 response._close_conn = close_conn
312
Georg Brandlb533e262008-05-25 18:19:30 +0000313 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000314 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000315 self.assertEqual(response.status, status)
316 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000317 if data:
318 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300319 # Ensure the server has not set up a persistent connection, and has
320 # not sent any extra data
321 self.assertEqual(response.version, 10)
322 self.assertEqual(response.msg.get("Connection", "close"), "close")
323 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
324
325 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300326 return body
327
Ned Deily14183202015-01-05 01:02:30 -0800328 @support.requires_mac_ver(10, 5)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300329 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
330 'need support.TESTFN_UNDECODABLE')
331 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300332 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300333 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
334 with open(os.path.join(self.tempdir, filename), 'wb') as f:
335 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000336 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300337 if sys.platform == 'darwin':
338 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
339 # UTF-8 into a percent-encoded value.
340 for name in os.listdir(self.tempdir):
341 if name != 'test': # Ignore a filename created in setUp().
342 filename = name
343 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200344 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300345 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
346 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300347 .encode(enc, 'surrogateescape'), body)
Martin Panterda3bb382016-04-11 00:40:08 +0000348 self.assertIn(('>%s<' % html.escape(filename, quote=False))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300349 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000350 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200351 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300352 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000353
354 def test_get(self):
355 #constructs the path relative to the root directory of the HTTPServer
Martin Panterfc475a92016-04-09 04:56:10 +0000356 response = self.request(self.base_url + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200357 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700358 # check for trailing "/" which should return 404. See Issue17324
Martin Panterfc475a92016-04-09 04:56:10 +0000359 response = self.request(self.base_url + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200360 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Martin Panterfc475a92016-04-09 04:56:10 +0000361 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200362 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000363 response = self.request(self.base_url)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200364 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000365 response = self.request(self.base_url + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200366 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000367 response = self.request(self.base_url + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200368 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600369 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000370 self.base_url + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000371 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200372 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000373 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200374 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300375
376 data = b"Dummy index file\r\n"
377 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
378 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000379 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300380 self.check_status_and_reason(response, HTTPStatus.OK, data)
381
382 # chmod() doesn't work as expected on Windows, and filesystem
383 # permissions are ignored by root on Unix.
384 if os.name == 'posix' and os.geteuid() != 0:
385 os.chmod(self.tempdir, 0)
386 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000387 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200388 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300389 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000390 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000391
392 def test_head(self):
393 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000394 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200395 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000396 self.assertEqual(response.getheader('content-length'),
397 str(len(self.data)))
398 self.assertEqual(response.getheader('content-type'),
399 'application/octet-stream')
400
401 def test_invalid_requests(self):
402 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200403 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000404 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400405 response = self.request('/', method='custom')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200406 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000407 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200408 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000409
Martin Panterfc475a92016-04-09 04:56:10 +0000410 def test_path_without_leading_slash(self):
411 response = self.request(self.tempdir_name + '/test')
412 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
413 response = self.request(self.tempdir_name + '/test/')
414 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
415 response = self.request(self.tempdir_name + '/')
416 self.check_status_and_reason(response, HTTPStatus.OK)
417 response = self.request(self.tempdir_name)
418 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
419 response = self.request(self.tempdir_name + '/?hi=2')
420 self.check_status_and_reason(response, HTTPStatus.OK)
421 response = self.request(self.tempdir_name + '?hi=1')
422 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
423 self.assertEqual(response.getheader("Location"),
424 self.tempdir_name + "/?hi=1")
425
Martin Panterda3bb382016-04-11 00:40:08 +0000426 def test_html_escape_filename(self):
427 filename = '<test&>.txt'
428 fullpath = os.path.join(self.tempdir, filename)
429
430 try:
431 open(fullpath, 'w').close()
432 except OSError:
433 raise unittest.SkipTest('Can not create file %s on current file '
434 'system' % filename)
435
436 try:
437 response = self.request(self.base_url + '/')
438 body = self.check_status_and_reason(response, HTTPStatus.OK)
439 enc = response.headers.get_content_charset()
440 finally:
441 os.unlink(fullpath) # avoid affecting test_undecodable_filename
442
443 self.assertIsNotNone(enc)
444 html_text = '>%s<' % html.escape(filename, quote=False)
445 self.assertIn(html_text.encode(enc), body)
446
Georg Brandlb533e262008-05-25 18:19:30 +0000447
448cgi_file1 = """\
449#!%s
450
451print("Content-type: text/html")
452print()
453print("Hello World")
454"""
455
456cgi_file2 = """\
457#!%s
458import cgi
459
460print("Content-type: text/html")
461print()
462
463form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000464print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
465 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000466"""
467
Martin Pantera02e18a2015-10-03 05:38:07 +0000468cgi_file4 = """\
469#!%s
470import os
471
472print("Content-type: text/html")
473print()
474
475print(os.environ["%s"])
476"""
477
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100478
479@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
480 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000481class CGIHTTPServerTestCase(BaseTestCase):
482 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
483 pass
484
Antoine Pitroue768c392012-08-05 14:52:45 +0200485 linesep = os.linesep.encode('ascii')
486
Georg Brandlb533e262008-05-25 18:19:30 +0000487 def setUp(self):
488 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000489 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000490 self.parent_dir = tempfile.mkdtemp()
491 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700492 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000493 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700494 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400495 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000496 self.file1_path = None
497 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700498 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000499 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000500
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000501 # The shebang line should be pure ASCII: use symlink if possible.
502 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000503 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000504 self.pythonexe = os.path.join(self.parent_dir, 'python')
505 os.symlink(sys.executable, self.pythonexe)
506 else:
507 self.pythonexe = sys.executable
508
Victor Stinner3218c312010-10-17 20:13:36 +0000509 try:
510 # The python executable path is written as the first line of the
511 # CGI Python script. The encoding cookie cannot be used, and so the
512 # path should be encodable to the default script encoding (utf-8)
513 self.pythonexe.encode('utf-8')
514 except UnicodeEncodeError:
515 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200516 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000517
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400518 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
519 with open(self.nocgi_path, 'w') as fp:
520 fp.write(cgi_file1 % self.pythonexe)
521 os.chmod(self.nocgi_path, 0o777)
522
Georg Brandlb533e262008-05-25 18:19:30 +0000523 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000524 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000525 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000526 os.chmod(self.file1_path, 0o777)
527
528 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000529 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000530 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000531 os.chmod(self.file2_path, 0o777)
532
Ned Deily915a30f2014-07-12 22:06:26 -0700533 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
534 with open(self.file3_path, 'w', encoding='utf-8') as file3:
535 file3.write(cgi_file1 % self.pythonexe)
536 os.chmod(self.file3_path, 0o777)
537
Martin Pantera02e18a2015-10-03 05:38:07 +0000538 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
539 with open(self.file4_path, 'w', encoding='utf-8') as file4:
540 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
541 os.chmod(self.file4_path, 0o777)
542
Georg Brandlb533e262008-05-25 18:19:30 +0000543 os.chdir(self.parent_dir)
544
545 def tearDown(self):
546 try:
547 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000548 if self.pythonexe != sys.executable:
549 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400550 if self.nocgi_path:
551 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000552 if self.file1_path:
553 os.remove(self.file1_path)
554 if self.file2_path:
555 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700556 if self.file3_path:
557 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000558 if self.file4_path:
559 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700560 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000561 os.rmdir(self.cgi_dir)
562 os.rmdir(self.parent_dir)
563 finally:
564 BaseTestCase.tearDown(self)
565
Senthil Kumarand70846b2012-04-12 02:34:32 +0800566 def test_url_collapse_path(self):
567 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000568 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800569 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000570 '..': IndexError,
571 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800572 '/': '//',
573 '//': '//',
574 '/\\': '//\\',
575 '/.//': '//',
576 'cgi-bin/file1.py': '/cgi-bin/file1.py',
577 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
578 'a': '//a',
579 '/a': '//a',
580 '//a': '//a',
581 './a': '//a',
582 './C:/': '/C:/',
583 '/a/b': '/a/b',
584 '/a/b/': '/a/b/',
585 '/a/b/.': '/a/b/',
586 '/a/b/c/..': '/a/b/',
587 '/a/b/c/../d': '/a/b/d',
588 '/a/b/c/../d/e/../f': '/a/b/d/f',
589 '/a/b/c/../d/e/../../f': '/a/b/f',
590 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000591 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800592 '/a/b/c/../d/e/../../../f': '/a/f',
593 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000594 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800595 '/a/b/c/../d/e/../../../../f/..': '//',
596 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000597 }
598 for path, expected in test_vectors.items():
599 if isinstance(expected, type) and issubclass(expected, Exception):
600 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800601 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000602 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800603 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000604 self.assertEqual(expected, actual,
605 msg='path = %r\nGot: %r\nWanted: %r' %
606 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000607
Georg Brandlb533e262008-05-25 18:19:30 +0000608 def test_headers_and_content(self):
609 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200610 self.assertEqual(
611 (res.read(), res.getheader('Content-type'), res.status),
612 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000613
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400614 def test_issue19435(self):
615 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200616 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400617
Georg Brandlb533e262008-05-25 18:19:30 +0000618 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000619 params = urllib.parse.urlencode(
620 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000621 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
622 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
623
Antoine Pitroue768c392012-08-05 14:52:45 +0200624 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000625
626 def test_invaliduri(self):
627 res = self.request('/cgi-bin/invalid')
628 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200629 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000630
631 def test_authorization(self):
632 headers = {b'Authorization' : b'Basic ' +
633 base64.b64encode(b'username:pass')}
634 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200635 self.assertEqual(
636 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
637 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000638
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000639 def test_no_leading_slash(self):
640 # http://bugs.python.org/issue2254
641 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200642 self.assertEqual(
643 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
644 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000645
Senthil Kumaran42713722010-10-03 17:55:45 +0000646 def test_os_environ_is_not_altered(self):
647 signature = "Test CGI Server"
648 os.environ['SERVER_SOFTWARE'] = signature
649 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200650 self.assertEqual(
651 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
652 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000653 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
654
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700655 def test_urlquote_decoding_in_cgi_check(self):
656 res = self.request('/cgi-bin%2ffile1.py')
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))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700660
Ned Deily915a30f2014-07-12 22:06:26 -0700661 def test_nested_cgi_path_issue21323(self):
662 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200663 self.assertEqual(
664 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
665 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700666
Martin Pantera02e18a2015-10-03 05:38:07 +0000667 def test_query_with_multiple_question_mark(self):
668 res = self.request('/cgi-bin/file4.py?a=b?c=d')
669 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000670 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000671 (res.read(), res.getheader('Content-type'), res.status))
672
Martin Pantercb29e8c2015-10-03 05:55:46 +0000673 def test_query_with_continuous_slashes(self):
674 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
675 self.assertEqual(
676 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000677 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000678 (res.read(), res.getheader('Content-type'), res.status))
679
Georg Brandlb533e262008-05-25 18:19:30 +0000680
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000681class SocketlessRequestHandler(SimpleHTTPRequestHandler):
682 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000683 self.get_called = False
684 self.protocol_version = "HTTP/1.1"
685
686 def do_GET(self):
687 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200688 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000689 self.send_header('Content-Type', 'text/html')
690 self.end_headers()
691 self.wfile.write(b'<html><body>Data</body></html>\r\n')
692
693 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000694 pass
695
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000696class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
697 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200698 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000699 return False
700
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800701
702class AuditableBytesIO:
703
704 def __init__(self):
705 self.datas = []
706
707 def write(self, data):
708 self.datas.append(data)
709
710 def getData(self):
711 return b''.join(self.datas)
712
713 @property
714 def numWrites(self):
715 return len(self.datas)
716
717
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000718class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200719 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000720
721 Test the support for the Expect 100-continue header.
722 """
723
724 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
725
726 def setUp (self):
727 self.handler = SocketlessRequestHandler()
728
729 def send_typical_request(self, message):
730 input = BytesIO(message)
731 output = BytesIO()
732 self.handler.rfile = input
733 self.handler.wfile = output
734 self.handler.handle_one_request()
735 output.seek(0)
736 return output.readlines()
737
738 def verify_get_called(self):
739 self.assertTrue(self.handler.get_called)
740
741 def verify_expected_headers(self, headers):
742 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
743 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
744
745 def verify_http_server_response(self, response):
746 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200747 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000748
749 def test_http_1_1(self):
750 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
751 self.verify_http_server_response(result[0])
752 self.verify_expected_headers(result[1:-1])
753 self.verify_get_called()
754 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500755 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
756 self.assertEqual(self.handler.command, 'GET')
757 self.assertEqual(self.handler.path, '/')
758 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
759 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000760
761 def test_http_1_0(self):
762 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
763 self.verify_http_server_response(result[0])
764 self.verify_expected_headers(result[1:-1])
765 self.verify_get_called()
766 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500767 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
768 self.assertEqual(self.handler.command, 'GET')
769 self.assertEqual(self.handler.path, '/')
770 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
771 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000772
773 def test_http_0_9(self):
774 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
775 self.assertEqual(len(result), 1)
776 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
777 self.verify_get_called()
778
779 def test_with_continue_1_0(self):
780 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
781 self.verify_http_server_response(result[0])
782 self.verify_expected_headers(result[1:-1])
783 self.verify_get_called()
784 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500785 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
786 self.assertEqual(self.handler.command, 'GET')
787 self.assertEqual(self.handler.path, '/')
788 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
789 headers = (("Expect", "100-continue"),)
790 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000791
792 def test_with_continue_1_1(self):
793 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
794 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500795 self.assertEqual(result[1], b'\r\n')
796 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000797 self.verify_expected_headers(result[2:-1])
798 self.verify_get_called()
799 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500800 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
801 self.assertEqual(self.handler.command, 'GET')
802 self.assertEqual(self.handler.path, '/')
803 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
804 headers = (("Expect", "100-continue"),)
805 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000806
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800807 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000808
809 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800810 output = AuditableBytesIO()
811 handler = SocketlessRequestHandler()
812 handler.rfile = input
813 handler.wfile = output
814 handler.request_version = 'HTTP/1.1'
815 handler.requestline = ''
816 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000817
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800818 handler.send_error(418)
819 self.assertEqual(output.numWrites, 2)
820
821 def test_header_buffering_of_send_response_only(self):
822
823 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
824 output = AuditableBytesIO()
825 handler = SocketlessRequestHandler()
826 handler.rfile = input
827 handler.wfile = output
828 handler.request_version = 'HTTP/1.1'
829
830 handler.send_response_only(418)
831 self.assertEqual(output.numWrites, 0)
832 handler.end_headers()
833 self.assertEqual(output.numWrites, 1)
834
835 def test_header_buffering_of_send_header(self):
836
837 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
838 output = AuditableBytesIO()
839 handler = SocketlessRequestHandler()
840 handler.rfile = input
841 handler.wfile = output
842 handler.request_version = 'HTTP/1.1'
843
844 handler.send_header('Foo', 'foo')
845 handler.send_header('bar', 'bar')
846 self.assertEqual(output.numWrites, 0)
847 handler.end_headers()
848 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
849 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000850
851 def test_header_unbuffered_when_continue(self):
852
853 def _readAndReseek(f):
854 pos = f.tell()
855 f.seek(0)
856 data = f.read()
857 f.seek(pos)
858 return data
859
860 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
861 output = BytesIO()
862 self.handler.rfile = input
863 self.handler.wfile = output
864 self.handler.request_version = 'HTTP/1.1'
865
866 self.handler.handle_one_request()
867 self.assertNotEqual(_readAndReseek(output), b'')
868 result = _readAndReseek(output).split(b'\r\n')
869 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500870 self.assertEqual(result[1], b'')
871 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000872
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000873 def test_with_continue_rejected(self):
874 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
875 self.handler = RejectingSocketlessRequestHandler()
876 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
877 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
878 self.verify_expected_headers(result[1:-1])
879 # The expect handler should short circuit the usual get method by
880 # returning false here, so get_called should be false
881 self.assertFalse(self.handler.get_called)
882 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
883 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
884
Antoine Pitrouc4924372010-12-16 16:48:36 +0000885 def test_request_length(self):
886 # Issue #10714: huge request lines are discarded, to avoid Denial
887 # of Service attacks.
888 result = self.send_typical_request(b'GET ' + b'x' * 65537)
889 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
890 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500891 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000892
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000893 def test_header_length(self):
894 # Issue #6791: same for headers
895 result = self.send_typical_request(
896 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +0000897 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000898 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500899 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
900
Martin Panteracc03192016-04-03 00:45:46 +0000901 def test_too_many_headers(self):
902 result = self.send_typical_request(
903 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
904 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
905 self.assertFalse(self.handler.get_called)
906 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
907
Martin Panterda3bb382016-04-11 00:40:08 +0000908 def test_html_escape_on_error(self):
909 result = self.send_typical_request(
910 b'<script>alert("hello")</script> / HTTP/1.1')
911 result = b''.join(result)
912 text = '<script>alert("hello")</script>'
913 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
914
Benjamin Peterson70e28472015-02-17 21:11:10 -0500915 def test_close_connection(self):
916 # handle_one_request() should be repeatedly called until
917 # it sets close_connection
918 def handle_one_request():
919 self.handler.close_connection = next(close_values)
920 self.handler.handle_one_request = handle_one_request
921
922 close_values = iter((True,))
923 self.handler.handle()
924 self.assertRaises(StopIteration, next, close_values)
925
926 close_values = iter((False, False, True))
927 self.handler.handle()
928 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000929
Berker Peksag04bc5b92016-03-14 06:06:03 +0200930 def test_date_time_string(self):
931 now = time.time()
932 # this is the old code that formats the timestamp
933 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
934 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
935 self.handler.weekdayname[wd],
936 day,
937 self.handler.monthname[month],
938 year, hh, mm, ss
939 )
940 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
941
942
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000943class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
944 """ Test url parsing """
945 def setUp(self):
946 self.translated = os.getcwd()
947 self.translated = os.path.join(self.translated, 'filename')
948 self.handler = SocketlessRequestHandler()
949
950 def test_query_arguments(self):
951 path = self.handler.translate_path('/filename')
952 self.assertEqual(path, self.translated)
953 path = self.handler.translate_path('/filename?foo=bar')
954 self.assertEqual(path, self.translated)
955 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
956 self.assertEqual(path, self.translated)
957
958 def test_start_with_double_slash(self):
959 path = self.handler.translate_path('//filename')
960 self.assertEqual(path, self.translated)
961 path = self.handler.translate_path('//filename?foo=bar')
962 self.assertEqual(path, self.translated)
963
Martin Panterd274b3f2016-04-18 03:45:18 +0000964 def test_windows_colon(self):
965 with support.swap_attr(server.os, 'path', ntpath):
966 path = self.handler.translate_path('c:c:c:foo/filename')
967 path = path.replace(ntpath.sep, os.sep)
968 self.assertEqual(path, self.translated)
969
970 path = self.handler.translate_path('\\c:../filename')
971 path = path.replace(ntpath.sep, os.sep)
972 self.assertEqual(path, self.translated)
973
974 path = self.handler.translate_path('c:\\c:..\\foo/filename')
975 path = path.replace(ntpath.sep, os.sep)
976 self.assertEqual(path, self.translated)
977
978 path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
979 path = path.replace(ntpath.sep, os.sep)
980 self.assertEqual(path, self.translated)
981
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000982
Berker Peksag366c5702015-02-13 20:48:15 +0200983class MiscTestCase(unittest.TestCase):
984 def test_all(self):
985 expected = []
986 blacklist = {'executable', 'nobody_uid', 'test'}
987 for name in dir(server):
988 if name.startswith('_') or name in blacklist:
989 continue
990 module_object = getattr(server, name)
991 if getattr(module_object, '__module__', None) == 'http.server':
992 expected.append(name)
993 self.assertCountEqual(server.__all__, expected)
994
995
Georg Brandlb533e262008-05-25 18:19:30 +0000996def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000997 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000998 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000999 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +02001000 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +00001001 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001002 BaseHTTPServerTestCase,
1003 SimpleHTTPServerTestCase,
1004 CGIHTTPServerTestCase,
1005 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +02001006 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +00001007 )
Georg Brandlb533e262008-05-25 18:19:30 +00001008 finally:
1009 os.chdir(cwd)
1010
1011if __name__ == '__main__':
1012 test_main()