blob: 518e38ec3d11a89e33e3f56f3732715a7f1e21f8 [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
15import shutil
Jeremy Hylton1afc1692008-06-18 20:49:58 +000016import urllib.parse
Serhiy Storchakacb5bc402014-08-17 08:22:11 +030017import html
Georg Brandl24420152008-05-26 16:32:26 +000018import http.client
Georg Brandlb533e262008-05-25 18:19:30 +000019import tempfile
Senthil Kumaran0f476d42010-09-30 06:09:18 +000020from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000021
22import unittest
23from test import support
Victor Stinner45df8202010-04-28 22:31:17 +000024threading = support.import_module('threading')
Georg Brandlb533e262008-05-25 18:19:30 +000025
Georg Brandlb533e262008-05-25 18:19:30 +000026class NoLogRequestHandler:
27 def log_message(self, *args):
28 # don't write log messages to stderr
29 pass
30
Barry Warsaw820c1202008-06-12 04:06:45 +000031 def read(self, n=None):
32 return ''
33
Georg Brandlb533e262008-05-25 18:19:30 +000034
35class TestServerThread(threading.Thread):
36 def __init__(self, test_object, request_handler):
37 threading.Thread.__init__(self)
38 self.request_handler = request_handler
39 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000040
41 def run(self):
Antoine Pitroucb342182011-03-21 00:26:51 +010042 self.server = HTTPServer(('localhost', 0), self.request_handler)
43 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000044 self.test_object.server_started.set()
45 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000046 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000047 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000048 finally:
49 self.server.server_close()
50
51 def stop(self):
52 self.server.shutdown()
53
54
55class BaseTestCase(unittest.TestCase):
56 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000057 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000058 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000059 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000060 self.thread = TestServerThread(self, self.request_handler)
61 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000062 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000063
64 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000065 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020066 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000067 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000068 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000069
70 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010071 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000072 self.connection.request(method, uri, body, headers)
73 return self.connection.getresponse()
74
75
76class BaseHTTPServerTestCase(BaseTestCase):
77 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
78 protocol_version = 'HTTP/1.1'
79 default_request_version = 'HTTP/1.1'
80
81 def do_TEST(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020082 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000083 self.send_header('Content-Type', 'text/html')
84 self.send_header('Connection', 'close')
85 self.end_headers()
86
87 def do_KEEP(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020088 self.send_response(HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +000089 self.send_header('Content-Type', 'text/html')
90 self.send_header('Connection', 'keep-alive')
91 self.end_headers()
92
93 def do_KEYERROR(self):
94 self.send_error(999)
95
Senthil Kumaran52d27202012-10-10 23:16:21 -070096 def do_NOTFOUND(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +020097 self.send_error(HTTPStatus.NOT_FOUND)
Senthil Kumaran52d27202012-10-10 23:16:21 -070098
Senthil Kumaran26886442013-03-15 07:53:21 -070099 def do_EXPLAINERROR(self):
100 self.send_error(999, "Short Message",
101 "This is a long \n explaination")
102
Georg Brandlb533e262008-05-25 18:19:30 +0000103 def do_CUSTOM(self):
104 self.send_response(999)
105 self.send_header('Content-Type', 'text/html')
106 self.send_header('Connection', 'close')
107 self.end_headers()
108
Armin Ronacher8d96d772011-01-22 13:13:05 +0000109 def do_LATINONEHEADER(self):
110 self.send_response(999)
111 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000112 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000113 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000114 body = self.headers['x-special-incoming'].encode('utf-8')
115 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000116
Georg Brandlb533e262008-05-25 18:19:30 +0000117 def setUp(self):
118 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100119 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000120 self.con.connect()
121
122 def test_command(self):
123 self.con.request('GET', '/')
124 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200125 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000126
127 def test_request_line_trimming(self):
128 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray14199f92014-06-24 16:39:49 -0400129 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000130 self.con.endheaders()
131 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200132 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000133
134 def test_version_bogus(self):
135 self.con._http_vsn_str = 'FUBAR'
136 self.con.putrequest('GET', '/')
137 self.con.endheaders()
138 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200139 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000140
141 def test_version_digits(self):
142 self.con._http_vsn_str = 'HTTP/9.9.9'
143 self.con.putrequest('GET', '/')
144 self.con.endheaders()
145 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200146 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000147
148 def test_version_none_get(self):
149 self.con._http_vsn_str = ''
150 self.con.putrequest('GET', '/')
151 self.con.endheaders()
152 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200153 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000154
155 def test_version_none(self):
R David Murray14199f92014-06-24 16:39:49 -0400156 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlb533e262008-05-25 18:19:30 +0000157 self.con._http_vsn_str = ''
R David Murray14199f92014-06-24 16:39:49 -0400158 self.con.putrequest('CUSTOM', '/')
Georg Brandlb533e262008-05-25 18:19:30 +0000159 self.con.endheaders()
160 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200161 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000162
163 def test_version_invalid(self):
164 self.con._http_vsn = 99
165 self.con._http_vsn_str = 'HTTP/9.9'
166 self.con.putrequest('GET', '/')
167 self.con.endheaders()
168 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200169 self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000170
171 def test_send_blank(self):
172 self.con._http_vsn_str = ''
173 self.con.putrequest('', '')
174 self.con.endheaders()
175 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200176 self.assertEqual(res.status, HTTPStatus.BAD_REQUEST)
Georg Brandlb533e262008-05-25 18:19:30 +0000177
178 def test_header_close(self):
179 self.con.putrequest('GET', '/')
180 self.con.putheader('Connection', 'close')
181 self.con.endheaders()
182 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200183 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000184
185 def test_head_keep_alive(self):
186 self.con._http_vsn_str = 'HTTP/1.1'
187 self.con.putrequest('GET', '/')
188 self.con.putheader('Connection', 'keep-alive')
189 self.con.endheaders()
190 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200191 self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000192
193 def test_handler(self):
194 self.con.request('TEST', '/')
195 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200196 self.assertEqual(res.status, HTTPStatus.NO_CONTENT)
Georg Brandlb533e262008-05-25 18:19:30 +0000197
198 def test_return_header_keep_alive(self):
199 self.con.request('KEEP', '/')
200 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000201 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000202 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000203 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000204
205 def test_internal_key_error(self):
206 self.con.request('KEYERROR', '/')
207 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000208 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000209
210 def test_return_custom_status(self):
211 self.con.request('CUSTOM', '/')
212 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000213 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000214
Senthil Kumaran26886442013-03-15 07:53:21 -0700215 def test_return_explain_error(self):
216 self.con.request('EXPLAINERROR', '/')
217 res = self.con.getresponse()
218 self.assertEqual(res.status, 999)
219 self.assertTrue(int(res.getheader('Content-Length')))
220
Armin Ronacher8d96d772011-01-22 13:13:05 +0000221 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000222 self.con.request('LATINONEHEADER', '/', headers={
223 'X-Special-Incoming': 'Ärger mit Unicode'
224 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000225 res = self.con.getresponse()
226 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000227 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000228
Senthil Kumaran52d27202012-10-10 23:16:21 -0700229 def test_error_content_length(self):
230 # Issue #16088: standard error responses should have a content-length
231 self.con.request('NOTFOUND', '/')
232 res = self.con.getresponse()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200233 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
234
Senthil Kumaran52d27202012-10-10 23:16:21 -0700235 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700236 self.assertEqual(int(res.getheader('Content-Length')), len(data))
237
Georg Brandlb533e262008-05-25 18:19:30 +0000238
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200239class RequestHandlerLoggingTestCase(BaseTestCase):
240 class request_handler(BaseHTTPRequestHandler):
241 protocol_version = 'HTTP/1.1'
242 default_request_version = 'HTTP/1.1'
243
244 def do_GET(self):
245 self.send_response(HTTPStatus.OK)
246 self.end_headers()
247
248 def do_ERROR(self):
249 self.send_error(HTTPStatus.NOT_FOUND, 'File not found')
250
251 def test_get(self):
252 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
253 self.con.connect()
254
255 with support.captured_stderr() as err:
256 self.con.request('GET', '/')
257 self.con.getresponse()
258
259 self.assertTrue(
260 err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n'))
261
262 def test_err(self):
263 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
264 self.con.connect()
265
266 with support.captured_stderr() as err:
267 self.con.request('ERROR', '/')
268 self.con.getresponse()
269
270 lines = err.getvalue().split('\n')
271 self.assertTrue(lines[0].endswith('code 404, message File not found'))
272 self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -'))
273
274
Georg Brandlb533e262008-05-25 18:19:30 +0000275class SimpleHTTPServerTestCase(BaseTestCase):
276 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
277 pass
278
279 def setUp(self):
280 BaseTestCase.setUp(self)
281 self.cwd = os.getcwd()
282 basetempdir = tempfile.gettempdir()
283 os.chdir(basetempdir)
284 self.data = b'We are the knights who say Ni!'
285 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
286 self.tempdir_name = os.path.basename(self.tempdir)
Brett Cannon105df5d2010-10-29 23:43:42 +0000287 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
288 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000289
290 def tearDown(self):
291 try:
292 os.chdir(self.cwd)
293 try:
294 shutil.rmtree(self.tempdir)
295 except:
296 pass
297 finally:
298 BaseTestCase.tearDown(self)
299
300 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300301 def close_conn():
302 """Don't close reader yet so we can check if there was leftover
303 buffered input"""
304 nonlocal reader
305 reader = response.fp
306 response.fp = None
307 reader = None
308 response._close_conn = close_conn
309
Georg Brandlb533e262008-05-25 18:19:30 +0000310 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000311 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000312 self.assertEqual(response.status, status)
313 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000314 if data:
315 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300316 # Ensure the server has not set up a persistent connection, and has
317 # not sent any extra data
318 self.assertEqual(response.version, 10)
319 self.assertEqual(response.msg.get("Connection", "close"), "close")
320 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
321
322 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300323 return body
324
Ned Deily14183202015-01-05 01:02:30 -0800325 @support.requires_mac_ver(10, 5)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300326 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
327 'need support.TESTFN_UNDECODABLE')
328 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300329 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300330 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
331 with open(os.path.join(self.tempdir, filename), 'wb') as f:
332 f.write(support.TESTFN_UNDECODABLE)
333 response = self.request(self.tempdir_name + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300334 if sys.platform == 'darwin':
335 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
336 # UTF-8 into a percent-encoded value.
337 for name in os.listdir(self.tempdir):
338 if name != 'test': # Ignore a filename created in setUp().
339 filename = name
340 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200341 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300342 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
343 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300344 .encode(enc, 'surrogateescape'), body)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300345 self.assertIn(('>%s<' % html.escape(filename))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300346 .encode(enc, 'surrogateescape'), body)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300347 response = self.request(self.tempdir_name + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200348 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300349 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000350
351 def test_get(self):
352 #constructs the path relative to the root directory of the HTTPServer
353 response = self.request(self.tempdir_name + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200354 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700355 # check for trailing "/" which should return 404. See Issue17324
356 response = self.request(self.tempdir_name + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200357 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000358 response = self.request(self.tempdir_name + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200359 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000360 response = self.request(self.tempdir_name)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200361 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600362 response = self.request(self.tempdir_name + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200363 self.check_status_and_reason(response, HTTPStatus.OK)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600364 response = self.request(self.tempdir_name + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200365 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600366 self.assertEqual(response.getheader("Location"),
367 self.tempdir_name + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000368 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200369 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
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)
Berker Peksagb5754322015-07-22 19:25:37 +0300372
373 data = b"Dummy index file\r\n"
374 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
375 f.write(data)
376 response = self.request('/' + self.tempdir_name + '/')
377 self.check_status_and_reason(response, HTTPStatus.OK, data)
378
379 # chmod() doesn't work as expected on Windows, and filesystem
380 # permissions are ignored by root on Unix.
381 if os.name == 'posix' and os.geteuid() != 0:
382 os.chmod(self.tempdir, 0)
383 try:
Brett Cannon105df5d2010-10-29 23:43:42 +0000384 response = self.request(self.tempdir_name + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200385 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300386 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000387 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000388
389 def test_head(self):
390 response = self.request(
391 self.tempdir_name + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200392 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000393 self.assertEqual(response.getheader('content-length'),
394 str(len(self.data)))
395 self.assertEqual(response.getheader('content-type'),
396 'application/octet-stream')
397
398 def test_invalid_requests(self):
399 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200400 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000401 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400402 response = self.request('/', method='custom')
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 response = self.request('/', method='GETs')
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
407
408cgi_file1 = """\
409#!%s
410
411print("Content-type: text/html")
412print()
413print("Hello World")
414"""
415
416cgi_file2 = """\
417#!%s
418import cgi
419
420print("Content-type: text/html")
421print()
422
423form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000424print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
425 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000426"""
427
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100428
429@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
430 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000431class CGIHTTPServerTestCase(BaseTestCase):
432 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
433 pass
434
Antoine Pitroue768c392012-08-05 14:52:45 +0200435 linesep = os.linesep.encode('ascii')
436
Georg Brandlb533e262008-05-25 18:19:30 +0000437 def setUp(self):
438 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000439 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000440 self.parent_dir = tempfile.mkdtemp()
441 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700442 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000443 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700444 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400445 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000446 self.file1_path = None
447 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700448 self.file3_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000449
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000450 # The shebang line should be pure ASCII: use symlink if possible.
451 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000452 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000453 self.pythonexe = os.path.join(self.parent_dir, 'python')
454 os.symlink(sys.executable, self.pythonexe)
455 else:
456 self.pythonexe = sys.executable
457
Victor Stinner3218c312010-10-17 20:13:36 +0000458 try:
459 # The python executable path is written as the first line of the
460 # CGI Python script. The encoding cookie cannot be used, and so the
461 # path should be encodable to the default script encoding (utf-8)
462 self.pythonexe.encode('utf-8')
463 except UnicodeEncodeError:
464 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200465 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000466
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400467 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
468 with open(self.nocgi_path, 'w') as fp:
469 fp.write(cgi_file1 % self.pythonexe)
470 os.chmod(self.nocgi_path, 0o777)
471
Georg Brandlb533e262008-05-25 18:19:30 +0000472 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000473 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000474 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000475 os.chmod(self.file1_path, 0o777)
476
477 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000478 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000479 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000480 os.chmod(self.file2_path, 0o777)
481
Ned Deily915a30f2014-07-12 22:06:26 -0700482 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
483 with open(self.file3_path, 'w', encoding='utf-8') as file3:
484 file3.write(cgi_file1 % self.pythonexe)
485 os.chmod(self.file3_path, 0o777)
486
Georg Brandlb533e262008-05-25 18:19:30 +0000487 os.chdir(self.parent_dir)
488
489 def tearDown(self):
490 try:
491 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000492 if self.pythonexe != sys.executable:
493 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400494 if self.nocgi_path:
495 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000496 if self.file1_path:
497 os.remove(self.file1_path)
498 if self.file2_path:
499 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700500 if self.file3_path:
501 os.remove(self.file3_path)
502 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000503 os.rmdir(self.cgi_dir)
504 os.rmdir(self.parent_dir)
505 finally:
506 BaseTestCase.tearDown(self)
507
Senthil Kumarand70846b2012-04-12 02:34:32 +0800508 def test_url_collapse_path(self):
509 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000510 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800511 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000512 '..': IndexError,
513 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800514 '/': '//',
515 '//': '//',
516 '/\\': '//\\',
517 '/.//': '//',
518 'cgi-bin/file1.py': '/cgi-bin/file1.py',
519 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
520 'a': '//a',
521 '/a': '//a',
522 '//a': '//a',
523 './a': '//a',
524 './C:/': '/C:/',
525 '/a/b': '/a/b',
526 '/a/b/': '/a/b/',
527 '/a/b/.': '/a/b/',
528 '/a/b/c/..': '/a/b/',
529 '/a/b/c/../d': '/a/b/d',
530 '/a/b/c/../d/e/../f': '/a/b/d/f',
531 '/a/b/c/../d/e/../../f': '/a/b/f',
532 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000533 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800534 '/a/b/c/../d/e/../../../f': '/a/f',
535 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000536 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800537 '/a/b/c/../d/e/../../../../f/..': '//',
538 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000539 }
540 for path, expected in test_vectors.items():
541 if isinstance(expected, type) and issubclass(expected, Exception):
542 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800543 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000544 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800545 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000546 self.assertEqual(expected, actual,
547 msg='path = %r\nGot: %r\nWanted: %r' %
548 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000549
Georg Brandlb533e262008-05-25 18:19:30 +0000550 def test_headers_and_content(self):
551 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200552 self.assertEqual(
553 (res.read(), res.getheader('Content-type'), res.status),
554 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000555
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400556 def test_issue19435(self):
557 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200558 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400559
Georg Brandlb533e262008-05-25 18:19:30 +0000560 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000561 params = urllib.parse.urlencode(
562 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000563 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
564 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
565
Antoine Pitroue768c392012-08-05 14:52:45 +0200566 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000567
568 def test_invaliduri(self):
569 res = self.request('/cgi-bin/invalid')
570 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200571 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000572
573 def test_authorization(self):
574 headers = {b'Authorization' : b'Basic ' +
575 base64.b64encode(b'username:pass')}
576 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200577 self.assertEqual(
578 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
579 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000580
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000581 def test_no_leading_slash(self):
582 # http://bugs.python.org/issue2254
583 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200584 self.assertEqual(
585 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
586 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000587
Senthil Kumaran42713722010-10-03 17:55:45 +0000588 def test_os_environ_is_not_altered(self):
589 signature = "Test CGI Server"
590 os.environ['SERVER_SOFTWARE'] = signature
591 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200592 self.assertEqual(
593 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
594 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000595 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
596
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700597 def test_urlquote_decoding_in_cgi_check(self):
598 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200599 self.assertEqual(
600 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
601 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700602
Ned Deily915a30f2014-07-12 22:06:26 -0700603 def test_nested_cgi_path_issue21323(self):
604 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200605 self.assertEqual(
606 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
607 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700608
Georg Brandlb533e262008-05-25 18:19:30 +0000609
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000610class SocketlessRequestHandler(SimpleHTTPRequestHandler):
611 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000612 self.get_called = False
613 self.protocol_version = "HTTP/1.1"
614
615 def do_GET(self):
616 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200617 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000618 self.send_header('Content-Type', 'text/html')
619 self.end_headers()
620 self.wfile.write(b'<html><body>Data</body></html>\r\n')
621
622 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000623 pass
624
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000625class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
626 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200627 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000628 return False
629
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800630
631class AuditableBytesIO:
632
633 def __init__(self):
634 self.datas = []
635
636 def write(self, data):
637 self.datas.append(data)
638
639 def getData(self):
640 return b''.join(self.datas)
641
642 @property
643 def numWrites(self):
644 return len(self.datas)
645
646
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000647class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200648 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000649
650 Test the support for the Expect 100-continue header.
651 """
652
653 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
654
655 def setUp (self):
656 self.handler = SocketlessRequestHandler()
657
658 def send_typical_request(self, message):
659 input = BytesIO(message)
660 output = BytesIO()
661 self.handler.rfile = input
662 self.handler.wfile = output
663 self.handler.handle_one_request()
664 output.seek(0)
665 return output.readlines()
666
667 def verify_get_called(self):
668 self.assertTrue(self.handler.get_called)
669
670 def verify_expected_headers(self, headers):
671 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
672 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
673
674 def verify_http_server_response(self, response):
675 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200676 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000677
678 def test_http_1_1(self):
679 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
680 self.verify_http_server_response(result[0])
681 self.verify_expected_headers(result[1:-1])
682 self.verify_get_called()
683 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500684 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
685 self.assertEqual(self.handler.command, 'GET')
686 self.assertEqual(self.handler.path, '/')
687 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
688 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000689
690 def test_http_1_0(self):
691 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
692 self.verify_http_server_response(result[0])
693 self.verify_expected_headers(result[1:-1])
694 self.verify_get_called()
695 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500696 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
697 self.assertEqual(self.handler.command, 'GET')
698 self.assertEqual(self.handler.path, '/')
699 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
700 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000701
702 def test_http_0_9(self):
703 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
704 self.assertEqual(len(result), 1)
705 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
706 self.verify_get_called()
707
708 def test_with_continue_1_0(self):
709 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
710 self.verify_http_server_response(result[0])
711 self.verify_expected_headers(result[1:-1])
712 self.verify_get_called()
713 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500714 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
715 self.assertEqual(self.handler.command, 'GET')
716 self.assertEqual(self.handler.path, '/')
717 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
718 headers = (("Expect", "100-continue"),)
719 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000720
721 def test_with_continue_1_1(self):
722 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
723 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500724 self.assertEqual(result[1], b'\r\n')
725 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000726 self.verify_expected_headers(result[2:-1])
727 self.verify_get_called()
728 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500729 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
730 self.assertEqual(self.handler.command, 'GET')
731 self.assertEqual(self.handler.path, '/')
732 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
733 headers = (("Expect", "100-continue"),)
734 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000735
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800736 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000737
738 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800739 output = AuditableBytesIO()
740 handler = SocketlessRequestHandler()
741 handler.rfile = input
742 handler.wfile = output
743 handler.request_version = 'HTTP/1.1'
744 handler.requestline = ''
745 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000746
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800747 handler.send_error(418)
748 self.assertEqual(output.numWrites, 2)
749
750 def test_header_buffering_of_send_response_only(self):
751
752 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
753 output = AuditableBytesIO()
754 handler = SocketlessRequestHandler()
755 handler.rfile = input
756 handler.wfile = output
757 handler.request_version = 'HTTP/1.1'
758
759 handler.send_response_only(418)
760 self.assertEqual(output.numWrites, 0)
761 handler.end_headers()
762 self.assertEqual(output.numWrites, 1)
763
764 def test_header_buffering_of_send_header(self):
765
766 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
767 output = AuditableBytesIO()
768 handler = SocketlessRequestHandler()
769 handler.rfile = input
770 handler.wfile = output
771 handler.request_version = 'HTTP/1.1'
772
773 handler.send_header('Foo', 'foo')
774 handler.send_header('bar', 'bar')
775 self.assertEqual(output.numWrites, 0)
776 handler.end_headers()
777 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
778 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000779
780 def test_header_unbuffered_when_continue(self):
781
782 def _readAndReseek(f):
783 pos = f.tell()
784 f.seek(0)
785 data = f.read()
786 f.seek(pos)
787 return data
788
789 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
790 output = BytesIO()
791 self.handler.rfile = input
792 self.handler.wfile = output
793 self.handler.request_version = 'HTTP/1.1'
794
795 self.handler.handle_one_request()
796 self.assertNotEqual(_readAndReseek(output), b'')
797 result = _readAndReseek(output).split(b'\r\n')
798 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500799 self.assertEqual(result[1], b'')
800 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000801
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000802 def test_with_continue_rejected(self):
803 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
804 self.handler = RejectingSocketlessRequestHandler()
805 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
806 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
807 self.verify_expected_headers(result[1:-1])
808 # The expect handler should short circuit the usual get method by
809 # returning false here, so get_called should be false
810 self.assertFalse(self.handler.get_called)
811 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
812 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
813
Antoine Pitrouc4924372010-12-16 16:48:36 +0000814 def test_request_length(self):
815 # Issue #10714: huge request lines are discarded, to avoid Denial
816 # of Service attacks.
817 result = self.send_typical_request(b'GET ' + b'x' * 65537)
818 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
819 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500820 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000821
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000822 def test_header_length(self):
823 # Issue #6791: same for headers
824 result = self.send_typical_request(
825 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
826 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
827 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500828 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
829
830 def test_close_connection(self):
831 # handle_one_request() should be repeatedly called until
832 # it sets close_connection
833 def handle_one_request():
834 self.handler.close_connection = next(close_values)
835 self.handler.handle_one_request = handle_one_request
836
837 close_values = iter((True,))
838 self.handler.handle()
839 self.assertRaises(StopIteration, next, close_values)
840
841 close_values = iter((False, False, True))
842 self.handler.handle()
843 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000844
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000845class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
846 """ Test url parsing """
847 def setUp(self):
848 self.translated = os.getcwd()
849 self.translated = os.path.join(self.translated, 'filename')
850 self.handler = SocketlessRequestHandler()
851
852 def test_query_arguments(self):
853 path = self.handler.translate_path('/filename')
854 self.assertEqual(path, self.translated)
855 path = self.handler.translate_path('/filename?foo=bar')
856 self.assertEqual(path, self.translated)
857 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
858 self.assertEqual(path, self.translated)
859
860 def test_start_with_double_slash(self):
861 path = self.handler.translate_path('//filename')
862 self.assertEqual(path, self.translated)
863 path = self.handler.translate_path('//filename?foo=bar')
864 self.assertEqual(path, self.translated)
865
866
Berker Peksag366c5702015-02-13 20:48:15 +0200867class MiscTestCase(unittest.TestCase):
868 def test_all(self):
869 expected = []
870 blacklist = {'executable', 'nobody_uid', 'test'}
871 for name in dir(server):
872 if name.startswith('_') or name in blacklist:
873 continue
874 module_object = getattr(server, name)
875 if getattr(module_object, '__module__', None) == 'http.server':
876 expected.append(name)
877 self.assertCountEqual(server.__all__, expected)
878
879
Georg Brandlb533e262008-05-25 18:19:30 +0000880def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000881 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000882 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000883 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200884 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000885 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000886 BaseHTTPServerTestCase,
887 SimpleHTTPServerTestCase,
888 CGIHTTPServerTestCase,
889 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +0200890 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000891 )
Georg Brandlb533e262008-05-25 18:19:30 +0000892 finally:
893 os.chdir(cwd)
894
895if __name__ == '__main__':
896 test_main()