blob: 08666848d00f6de070920207e74a4a6311c194e3 [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",
102 "This is a long \n explaination")
103
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
Georg Brandlb533e262008-05-25 18:19:30 +0000118 def setUp(self):
119 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100120 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000121 self.con.connect()
122
123 def test_command(self):
124 self.con.request('GET', '/')
125 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200126 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000127
128 def test_request_line_trimming(self):
129 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400130 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000131 self.con.endheaders()
132 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200133 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000134
135 def test_version_bogus(self):
136 self.con._http_vsn_str = 'FUBAR'
137 self.con.putrequest('GET', '/')
138 self.con.endheaders()
139 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200140 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000141
142 def test_version_digits(self):
143 self.con._http_vsn_str = 'HTTP/9.9.9'
144 self.con.putrequest('GET', '/')
145 self.con.endheaders()
146 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200147 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000148
149 def test_version_none_get(self):
150 self.con._http_vsn_str = ''
151 self.con.putrequest('GET', '/')
152 self.con.endheaders()
153 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200154 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000155
156 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400157 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000158 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400159 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000160 self.con.endheaders()
161 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200162 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000163
164 def test_version_invalid(self):
165 self.con._http_vsn = 99
166 self.con._http_vsn_str = 'HTTP/9.9'
167 self.con.putrequest('GET', '/')
168 self.con.endheaders()
169 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200170 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000171
172 def test_send_blank(self):
173 self.con._http_vsn_str = ''
174 self.con.putrequest('', '')
175 self.con.endheaders()
176 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200177 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000178
179 def test_header_close(self):
180 self.con.putrequest('GET', '/')
181 self.con.putheader('Connection', 'close')
182 self.con.endheaders()
183 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200184 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000185
186 def test_head_keep_alive(self):
187 self.con._http_vsn_str = 'HTTP/1.1'
188 self.con.putrequest('GET', '/')
189 self.con.putheader('Connection', 'keep-alive')
190 self.con.endheaders()
191 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200192 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000193
194 def test_handler(self):
195 self.con.request('TEST', '/')
196 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200197 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000198
199 def test_return_header_keep_alive(self):
200 self.con.request('KEEP', '/')
201 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000202 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000203 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000204 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000205
206 def test_internal_key_error(self):
207 self.con.request('KEYERROR', '/')
208 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000209 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000210
211 def test_return_custom_status(self):
212 self.con.request('CUSTOM', '/')
213 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000214 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000215
Senthil Kumaran26886442013-03-15 07:53:21 -0700216 def test_return_explain_error(self):
217 self.con.request('EXPLAINERROR', '/')
218 res = self.con.getresponse()
219 self.assertEqual(res.status, 999)
220 self.assertTrue(int(res.getheader('Content-Length')))
221
Armin Ronacher8d96d772011-01-22 13:13:05 +0000222 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000223 self.con.request('LATINONEHEADER', '/', headers={
224 'X-Special-Incoming': 'Ärger mit Unicode'
225 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000226 res = self.con.getresponse()
227 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000228 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000229
Senthil Kumaran52d27202012-10-10 23:16:21 -0700230 def test_error_content_length(self):
231 # Issue #16088: standard error responses should have a content-length
232 self.con.request('NOTFOUND', '/')
233 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200234 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
235
Senthil Kumaran52d27202012-10-10 23:16:21 -0700236 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700237 self.assertEqual(int(res.getheader('Content-Length')), len(data))
238
Georg Brandlb533e262008-05-25 18:19:30 +0000239
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200240class RequestHandlerLoggingTestCase(BaseTestCase):
241 class request_handler(BaseHTTPRequestHandler):
242 protocol_version = 'HTTP/1.1'
243 default_request_version = 'HTTP/1.1'
244
245 def do_GET(self):
246 self.send_response(HTTPStatus.OK)
247 self.end_headers()
248
249 def do_ERROR(self):
250 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
251
252 def test_get(self):
253 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
254 self.con.connect()
255
256 with support.captured_stderr() as err:
257 self.con.request('GET', '/')
258 self.con.getresponse()
259
260 self.assertTrue(
261 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
262
263 def test_err(self):
264 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
265 self.con.connect()
266
267 with support.captured_stderr() as err:
268 self.con.request('ERROR', '/')
269 self.con.getresponse()
270
271 lines = err.getvalue().split('\n')
272 self.assertTrue(lines[0].endswith('code 404, message File not found'))
273 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
274
275
Georg Brandlb533e262008-05-25 18:19:30 +0000276class SimpleHTTPServerTestCase(BaseTestCase):
277 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
278 pass
279
280 def setUp(self):
281 BaseTestCase.setUp(self)
282 self.cwd = os.getcwd()
283 basetempdir = tempfile.gettempdir()
284 os.chdir(basetempdir)
285 self.data = b'We are the knights who say Ni!'
286 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
287 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panterfc475a92016-04-09 04:56:10 +0000288 self.base_url = '/' + self.tempdir_name
Brett Cannon105df5d2010-10-29 23:43:42 +0000289 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
290 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000291
292 def tearDown(self):
293 try:
294 os.chdir(self.cwd)
295 try:
296 shutil.rmtree(self.tempdir)
297 except:
298 pass
299 finally:
300 BaseTestCase.tearDown(self)
301
302 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300303 def close_conn():
304 """Don't close reader yet so we can check if there was leftover
305 buffered input"""
306 nonlocal reader
307 reader = response.fp
308 response.fp = None
309 reader = None
310 response._close_conn = close_conn
311
Georg Brandlb533e262008-05-25 18:19:30 +0000312 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000313 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000314 self.assertEqual(response.status, status)
315 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000316 if data:
317 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300318 # Ensure the server has not set up a persistent connection, and has
319 # not sent any extra data
320 self.assertEqual(response.version, 10)
321 self.assertEqual(response.msg.get("Connection", "close"), "close")
322 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
323
324 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300325 return body
326
Ned Deily14183202015-01-05 01:02:30 -0800327 @support.requires_mac_ver(10, 5)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300328 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
329 'need support.TESTFN_UNDECODABLE')
330 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300331 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300332 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
333 with open(os.path.join(self.tempdir, filename), 'wb') as f:
334 f.write(support.TESTFN_UNDECODABLE)
Martin Panterfc475a92016-04-09 04:56:10 +0000335 response = self.request(self.base_url + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300336 if sys.platform == 'darwin':
337 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
338 # UTF-8 into a percent-encoded value.
339 for name in os.listdir(self.tempdir):
340 if name != 'test': # Ignore a filename created in setUp().
341 filename = name
342 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200343 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300344 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
345 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300346 .encode(enc, 'surrogateescape'), body)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300347 self.assertIn(('>%s<' % html.escape(filename))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300348 .encode(enc, 'surrogateescape'), body)
Martin Panterfc475a92016-04-09 04:56:10 +0000349 response = self.request(self.base_url + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200350 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300351 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000352
353 def test_get(self):
354 #constructs the path relative to the root directory of the HTTPServer
Martin Panterfc475a92016-04-09 04:56:10 +0000355 response = self.request(self.base_url + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200356 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700357 # check for trailing "/" which should return 404. See Issue17324
Martin Panterfc475a92016-04-09 04:56:10 +0000358 response = self.request(self.base_url + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200359 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Martin Panterfc475a92016-04-09 04:56:10 +0000360 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200361 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000362 response = self.request(self.base_url)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200363 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Martin Panterfc475a92016-04-09 04:56:10 +0000364 response = self.request(self.base_url + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200365 self.check_status_and_reason(response, HTTPStatus.OK)
Martin Panterfc475a92016-04-09 04:56:10 +0000366 response = self.request(self.base_url + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200367 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600368 self.assertEqual(response.getheader("Location"),
Martin Panterfc475a92016-04-09 04:56:10 +0000369 self.base_url + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000370 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200371 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000372 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200373 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300374
375 data = b"Dummy index file\r\n"
376 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
377 f.write(data)
Martin Panterfc475a92016-04-09 04:56:10 +0000378 response = self.request(self.base_url + '/')
Berker Peksagb5754322015-07-22 19:25:37 +0300379 self.check_status_and_reason(response, HTTPStatus.OK, data)
380
381 # chmod() doesn't work as expected on Windows, and filesystem
382 # permissions are ignored by root on Unix.
383 if os.name == 'posix' and os.geteuid() != 0:
384 os.chmod(self.tempdir, 0)
385 try:
Martin Panterfc475a92016-04-09 04:56:10 +0000386 response = self.request(self.base_url + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200387 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300388 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000389 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000390
391 def test_head(self):
392 response = self.request(
Martin Panterfc475a92016-04-09 04:56:10 +0000393 self.base_url + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200394 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000395 self.assertEqual(response.getheader('content-length'),
396 str(len(self.data)))
397 self.assertEqual(response.getheader('content-type'),
398 'application/octet-stream')
399
400 def test_invalid_requests(self):
401 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200402 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000403 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400404 response = self.request('/', method='custom')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200405 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000406 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200407 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000408
Martin Panterfc475a92016-04-09 04:56:10 +0000409 def test_path_without_leading_slash(self):
410 response = self.request(self.tempdir_name + '/test')
411 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
412 response = self.request(self.tempdir_name + '/test/')
413 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
414 response = self.request(self.tempdir_name + '/')
415 self.check_status_and_reason(response, HTTPStatus.OK)
416 response = self.request(self.tempdir_name)
417 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
418 response = self.request(self.tempdir_name + '/?hi=2')
419 self.check_status_and_reason(response, HTTPStatus.OK)
420 response = self.request(self.tempdir_name + '?hi=1')
421 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
422 self.assertEqual(response.getheader("Location"),
423 self.tempdir_name + "/?hi=1")
424
Georg Brandlb533e262008-05-25 18:19:30 +0000425
426cgi_file1 = """\
427#!%s
428
429print("Content-type: text/html")
430print()
431print("Hello World")
432"""
433
434cgi_file2 = """\
435#!%s
436import cgi
437
438print("Content-type: text/html")
439print()
440
441form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000442print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
443 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000444"""
445
Martin Pantera02e18a2015-10-03 05:38:07 +0000446cgi_file4 = """\
447#!%s
448import os
449
450print("Content-type: text/html")
451print()
452
453print(os.environ["%s"])
454"""
455
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100456
457@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
458 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000459class CGIHTTPServerTestCase(BaseTestCase):
460 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
461 pass
462
Antoine Pitroue768c392012-08-05 14:52:45 +0200463 linesep = os.linesep.encode('ascii')
464
Georg Brandlb533e262008-05-25 18:19:30 +0000465 def setUp(self):
466 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000467 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000468 self.parent_dir = tempfile.mkdtemp()
469 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700470 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000471 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700472 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400473 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000474 self.file1_path = None
475 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700476 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000477 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000478
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000479 # The shebang line should be pure ASCII: use symlink if possible.
480 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000481 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000482 self.pythonexe = os.path.join(self.parent_dir, 'python')
483 os.symlink(sys.executable, self.pythonexe)
484 else:
485 self.pythonexe = sys.executable
486
Victor Stinner3218c312010-10-17 20:13:36 +0000487 try:
488 # The python executable path is written as the first line of the
489 # CGI Python script. The encoding cookie cannot be used, and so the
490 # path should be encodable to the default script encoding (utf-8)
491 self.pythonexe.encode('utf-8')
492 except UnicodeEncodeError:
493 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200494 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000495
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400496 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
497 with open(self.nocgi_path, 'w') as fp:
498 fp.write(cgi_file1 % self.pythonexe)
499 os.chmod(self.nocgi_path, 0o777)
500
Georg Brandlb533e262008-05-25 18:19:30 +0000501 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000502 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000503 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000504 os.chmod(self.file1_path, 0o777)
505
506 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000507 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000508 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000509 os.chmod(self.file2_path, 0o777)
510
Ned Deily915a30f2014-07-12 22:06:26 -0700511 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
512 with open(self.file3_path, 'w', encoding='utf-8') as file3:
513 file3.write(cgi_file1 % self.pythonexe)
514 os.chmod(self.file3_path, 0o777)
515
Martin Pantera02e18a2015-10-03 05:38:07 +0000516 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
517 with open(self.file4_path, 'w', encoding='utf-8') as file4:
518 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
519 os.chmod(self.file4_path, 0o777)
520
Georg Brandlb533e262008-05-25 18:19:30 +0000521 os.chdir(self.parent_dir)
522
523 def tearDown(self):
524 try:
525 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000526 if self.pythonexe != sys.executable:
527 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400528 if self.nocgi_path:
529 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000530 if self.file1_path:
531 os.remove(self.file1_path)
532 if self.file2_path:
533 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700534 if self.file3_path:
535 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000536 if self.file4_path:
537 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700538 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000539 os.rmdir(self.cgi_dir)
540 os.rmdir(self.parent_dir)
541 finally:
542 BaseTestCase.tearDown(self)
543
Senthil Kumarand70846b2012-04-12 02:34:32 +0800544 def test_url_collapse_path(self):
545 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000546 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800547 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000548 '..': IndexError,
549 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800550 '/': '//',
551 '//': '//',
552 '/\\': '//\\',
553 '/.//': '//',
554 'cgi-bin/file1.py': '/cgi-bin/file1.py',
555 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
556 'a': '//a',
557 '/a': '//a',
558 '//a': '//a',
559 './a': '//a',
560 './C:/': '/C:/',
561 '/a/b': '/a/b',
562 '/a/b/': '/a/b/',
563 '/a/b/.': '/a/b/',
564 '/a/b/c/..': '/a/b/',
565 '/a/b/c/../d': '/a/b/d',
566 '/a/b/c/../d/e/../f': '/a/b/d/f',
567 '/a/b/c/../d/e/../../f': '/a/b/f',
568 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000569 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800570 '/a/b/c/../d/e/../../../f': '/a/f',
571 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000572 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800573 '/a/b/c/../d/e/../../../../f/..': '//',
574 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000575 }
576 for path, expected in test_vectors.items():
577 if isinstance(expected, type) and issubclass(expected, Exception):
578 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800579 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000580 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800581 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000582 self.assertEqual(expected, actual,
583 msg='path = %r\nGot: %r\nWanted: %r' %
584 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000585
Georg Brandlb533e262008-05-25 18:19:30 +0000586 def test_headers_and_content(self):
587 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200588 self.assertEqual(
589 (res.read(), res.getheader('Content-type'), res.status),
590 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000591
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400592 def test_issue19435(self):
593 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200594 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400595
Georg Brandlb533e262008-05-25 18:19:30 +0000596 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000597 params = urllib.parse.urlencode(
598 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000599 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
600 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
601
Antoine Pitroue768c392012-08-05 14:52:45 +0200602 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000603
604 def test_invaliduri(self):
605 res = self.request('/cgi-bin/invalid')
606 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200607 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000608
609 def test_authorization(self):
610 headers = {b'Authorization' : b'Basic ' +
611 base64.b64encode(b'username:pass')}
612 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200613 self.assertEqual(
614 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
615 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000616
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000617 def test_no_leading_slash(self):
618 # http://bugs.python.org/issue2254
619 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200620 self.assertEqual(
621 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
622 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000623
Senthil Kumaran42713722010-10-03 17:55:45 +0000624 def test_os_environ_is_not_altered(self):
625 signature = "Test CGI Server"
626 os.environ['SERVER_SOFTWARE'] = signature
627 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200628 self.assertEqual(
629 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
630 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000631 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
632
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700633 def test_urlquote_decoding_in_cgi_check(self):
634 res = self.request('/cgi-bin%2ffile1.py')
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))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700638
Ned Deily915a30f2014-07-12 22:06:26 -0700639 def test_nested_cgi_path_issue21323(self):
640 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200641 self.assertEqual(
642 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
643 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700644
Martin Pantera02e18a2015-10-03 05:38:07 +0000645 def test_query_with_multiple_question_mark(self):
646 res = self.request('/cgi-bin/file4.py?a=b?c=d')
647 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000648 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000649 (res.read(), res.getheader('Content-type'), res.status))
650
Martin Pantercb29e8c2015-10-03 05:55:46 +0000651 def test_query_with_continuous_slashes(self):
652 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
653 self.assertEqual(
654 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000655 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000656 (res.read(), res.getheader('Content-type'), res.status))
657
Georg Brandlb533e262008-05-25 18:19:30 +0000658
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000659class SocketlessRequestHandler(SimpleHTTPRequestHandler):
660 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000661 self.get_called = False
662 self.protocol_version = "HTTP/1.1"
663
664 def do_GET(self):
665 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200666 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000667 self.send_header('Content-Type', 'text/html')
668 self.end_headers()
669 self.wfile.write(b'<html><body>Data</body></html>\r\n')
670
671 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000672 pass
673
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000674class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
675 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200676 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000677 return False
678
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800679
680class AuditableBytesIO:
681
682 def __init__(self):
683 self.datas = []
684
685 def write(self, data):
686 self.datas.append(data)
687
688 def getData(self):
689 return b''.join(self.datas)
690
691 @property
692 def numWrites(self):
693 return len(self.datas)
694
695
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000696class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200697 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000698
699 Test the support for the Expect 100-continue header.
700 """
701
702 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
703
704 def setUp (self):
705 self.handler = SocketlessRequestHandler()
706
707 def send_typical_request(self, message):
708 input = BytesIO(message)
709 output = BytesIO()
710 self.handler.rfile = input
711 self.handler.wfile = output
712 self.handler.handle_one_request()
713 output.seek(0)
714 return output.readlines()
715
716 def verify_get_called(self):
717 self.assertTrue(self.handler.get_called)
718
719 def verify_expected_headers(self, headers):
720 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
721 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
722
723 def verify_http_server_response(self, response):
724 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200725 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000726
727 def test_http_1_1(self):
728 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
729 self.verify_http_server_response(result[0])
730 self.verify_expected_headers(result[1:-1])
731 self.verify_get_called()
732 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500733 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
734 self.assertEqual(self.handler.command, 'GET')
735 self.assertEqual(self.handler.path, '/')
736 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
737 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000738
739 def test_http_1_0(self):
740 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
741 self.verify_http_server_response(result[0])
742 self.verify_expected_headers(result[1:-1])
743 self.verify_get_called()
744 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500745 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
746 self.assertEqual(self.handler.command, 'GET')
747 self.assertEqual(self.handler.path, '/')
748 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
749 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000750
751 def test_http_0_9(self):
752 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
753 self.assertEqual(len(result), 1)
754 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
755 self.verify_get_called()
756
757 def test_with_continue_1_0(self):
758 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
759 self.verify_http_server_response(result[0])
760 self.verify_expected_headers(result[1:-1])
761 self.verify_get_called()
762 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500763 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
764 self.assertEqual(self.handler.command, 'GET')
765 self.assertEqual(self.handler.path, '/')
766 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
767 headers = (("Expect", "100-continue"),)
768 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000769
770 def test_with_continue_1_1(self):
771 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
772 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500773 self.assertEqual(result[1], b'\r\n')
774 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000775 self.verify_expected_headers(result[2:-1])
776 self.verify_get_called()
777 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500778 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
779 self.assertEqual(self.handler.command, 'GET')
780 self.assertEqual(self.handler.path, '/')
781 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
782 headers = (("Expect", "100-continue"),)
783 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000784
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800785 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000786
787 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800788 output = AuditableBytesIO()
789 handler = SocketlessRequestHandler()
790 handler.rfile = input
791 handler.wfile = output
792 handler.request_version = 'HTTP/1.1'
793 handler.requestline = ''
794 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000795
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800796 handler.send_error(418)
797 self.assertEqual(output.numWrites, 2)
798
799 def test_header_buffering_of_send_response_only(self):
800
801 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
802 output = AuditableBytesIO()
803 handler = SocketlessRequestHandler()
804 handler.rfile = input
805 handler.wfile = output
806 handler.request_version = 'HTTP/1.1'
807
808 handler.send_response_only(418)
809 self.assertEqual(output.numWrites, 0)
810 handler.end_headers()
811 self.assertEqual(output.numWrites, 1)
812
813 def test_header_buffering_of_send_header(self):
814
815 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
816 output = AuditableBytesIO()
817 handler = SocketlessRequestHandler()
818 handler.rfile = input
819 handler.wfile = output
820 handler.request_version = 'HTTP/1.1'
821
822 handler.send_header('Foo', 'foo')
823 handler.send_header('bar', 'bar')
824 self.assertEqual(output.numWrites, 0)
825 handler.end_headers()
826 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
827 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000828
829 def test_header_unbuffered_when_continue(self):
830
831 def _readAndReseek(f):
832 pos = f.tell()
833 f.seek(0)
834 data = f.read()
835 f.seek(pos)
836 return data
837
838 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
839 output = BytesIO()
840 self.handler.rfile = input
841 self.handler.wfile = output
842 self.handler.request_version = 'HTTP/1.1'
843
844 self.handler.handle_one_request()
845 self.assertNotEqual(_readAndReseek(output), b'')
846 result = _readAndReseek(output).split(b'\r\n')
847 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500848 self.assertEqual(result[1], b'')
849 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000850
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000851 def test_with_continue_rejected(self):
852 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
853 self.handler = RejectingSocketlessRequestHandler()
854 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
855 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
856 self.verify_expected_headers(result[1:-1])
857 # The expect handler should short circuit the usual get method by
858 # returning false here, so get_called should be false
859 self.assertFalse(self.handler.get_called)
860 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
861 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
862
Antoine Pitrouc4924372010-12-16 16:48:36 +0000863 def test_request_length(self):
864 # Issue #10714: huge request lines are discarded, to avoid Denial
865 # of Service attacks.
866 result = self.send_typical_request(b'GET ' + b'x' * 65537)
867 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
868 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500869 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000870
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000871 def test_header_length(self):
872 # Issue #6791: same for headers
873 result = self.send_typical_request(
874 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
875 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
876 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500877 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
878
Martin Panteracc03192016-04-03 00:45:46 +0000879 def test_too_many_headers(self):
880 result = self.send_typical_request(
881 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
882 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
883 self.assertFalse(self.handler.get_called)
884 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
885
Benjamin Peterson70e28472015-02-17 21:11:10 -0500886 def test_close_connection(self):
887 # handle_one_request() should be repeatedly called until
888 # it sets close_connection
889 def handle_one_request():
890 self.handler.close_connection = next(close_values)
891 self.handler.handle_one_request = handle_one_request
892
893 close_values = iter((True,))
894 self.handler.handle()
895 self.assertRaises(StopIteration, next, close_values)
896
897 close_values = iter((False, False, True))
898 self.handler.handle()
899 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000900
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000901class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
902 """ Test url parsing """
903 def setUp(self):
904 self.translated = os.getcwd()
905 self.translated = os.path.join(self.translated, 'filename')
906 self.handler = SocketlessRequestHandler()
907
908 def test_query_arguments(self):
909 path = self.handler.translate_path('/filename')
910 self.assertEqual(path, self.translated)
911 path = self.handler.translate_path('/filename?foo=bar')
912 self.assertEqual(path, self.translated)
913 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
914 self.assertEqual(path, self.translated)
915
916 def test_start_with_double_slash(self):
917 path = self.handler.translate_path('//filename')
918 self.assertEqual(path, self.translated)
919 path = self.handler.translate_path('//filename?foo=bar')
920 self.assertEqual(path, self.translated)
921
Martin Panterd274b3f2016-04-18 03:45:18 +0000922 def test_windows_colon(self):
923 with support.swap_attr(server.os, 'path', ntpath):
924 path = self.handler.translate_path('c:c:c:foo/filename')
925 path = path.replace(ntpath.sep, os.sep)
926 self.assertEqual(path, self.translated)
927
928 path = self.handler.translate_path('\\c:../filename')
929 path = path.replace(ntpath.sep, os.sep)
930 self.assertEqual(path, self.translated)
931
932 path = self.handler.translate_path('c:\\c:..\\foo/filename')
933 path = path.replace(ntpath.sep, os.sep)
934 self.assertEqual(path, self.translated)
935
936 path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
937 path = path.replace(ntpath.sep, os.sep)
938 self.assertEqual(path, self.translated)
939
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000940
Berker Peksag366c5702015-02-13 20:48:15 +0200941class MiscTestCase(unittest.TestCase):
942 def test_all(self):
943 expected = []
944 blacklist = {'executable', 'nobody_uid', 'test'}
945 for name in dir(server):
946 if name.startswith('_') or name in blacklist:
947 continue
948 module_object = getattr(server, name)
949 if getattr(module_object, '__module__', None) == 'http.server':
950 expected.append(name)
951 self.assertCountEqual(server.__all__, expected)
952
953
Georg Brandlb533e262008-05-25 18:19:30 +0000954def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000955 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000956 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000957 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200958 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000959 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000960 BaseHTTPServerTestCase,
961 SimpleHTTPServerTestCase,
962 CGIHTTPServerTestCase,
963 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +0200964 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000965 )
Georg Brandlb533e262008-05-25 18:19:30 +0000966 finally:
967 os.chdir(cwd)
968
969if __name__ == '__main__':
970 test_main()