blob: 5d44825cc8fe02b0f188f65c72afb95ac28b8203 [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
Berker Peksag04bc5b92016-03-14 06:06:03 +020020import time
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)
Brett Cannon105df5d2010-10-29 23:43:42 +0000288 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
289 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000290
291 def tearDown(self):
292 try:
293 os.chdir(self.cwd)
294 try:
295 shutil.rmtree(self.tempdir)
296 except:
297 pass
298 finally:
299 BaseTestCase.tearDown(self)
300
301 def check_status_and_reason(self, response, status, data=None):
Berker Peksagb5754322015-07-22 19:25:37 +0300302 def close_conn():
303 """Don't close reader yet so we can check if there was leftover
304 buffered input"""
305 nonlocal reader
306 reader = response.fp
307 response.fp = None
308 reader = None
309 response._close_conn = close_conn
310
Georg Brandlb533e262008-05-25 18:19:30 +0000311 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000312 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000313 self.assertEqual(response.status, status)
314 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000315 if data:
316 self.assertEqual(data, body)
Berker Peksagb5754322015-07-22 19:25:37 +0300317 # Ensure the server has not set up a persistent connection, and has
318 # not sent any extra data
319 self.assertEqual(response.version, 10)
320 self.assertEqual(response.msg.get("Connection", "close"), "close")
321 self.assertEqual(reader.read(30), b'', 'Connection should be closed')
322
323 reader.close()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300324 return body
325
Ned Deily14183202015-01-05 01:02:30 -0800326 @support.requires_mac_ver(10, 5)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300327 @unittest.skipUnless(support.TESTFN_UNDECODABLE,
328 'need support.TESTFN_UNDECODABLE')
329 def test_undecodable_filename(self):
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300330 enc = sys.getfilesystemencoding()
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300331 filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt'
332 with open(os.path.join(self.tempdir, filename), 'wb') as f:
333 f.write(support.TESTFN_UNDECODABLE)
334 response = self.request(self.tempdir_name + '/')
Serhiy Storchakad9e95282014-08-17 16:57:39 +0300335 if sys.platform == 'darwin':
336 # On Mac OS the HFS+ filesystem replaces bytes that aren't valid
337 # UTF-8 into a percent-encoded value.
338 for name in os.listdir(self.tempdir):
339 if name != 'test': # Ignore a filename created in setUp().
340 filename = name
341 break
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200342 body = self.check_status_and_reason(response, HTTPStatus.OK)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300343 quotedname = urllib.parse.quote(filename, errors='surrogatepass')
344 self.assertIn(('href="%s"' % quotedname)
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300345 .encode(enc, 'surrogateescape'), body)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300346 self.assertIn(('>%s<' % html.escape(filename))
Serhiy Storchakaa64ce5d2014-08-17 12:20:02 +0300347 .encode(enc, 'surrogateescape'), body)
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300348 response = self.request(self.tempdir_name + '/' + quotedname)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200349 self.check_status_and_reason(response, HTTPStatus.OK,
Serhiy Storchakacb5bc402014-08-17 08:22:11 +0300350 data=support.TESTFN_UNDECODABLE)
Georg Brandlb533e262008-05-25 18:19:30 +0000351
352 def test_get(self):
353 #constructs the path relative to the root directory of the HTTPServer
354 response = self.request(self.tempdir_name + '/test')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200355 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
Senthil Kumaran72c238e2013-09-13 00:21:18 -0700356 # check for trailing "/" which should return 404. See Issue17324
357 response = self.request(self.tempdir_name + '/test/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200358 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000359 response = self.request(self.tempdir_name + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200360 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000361 response = self.request(self.tempdir_name)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200362 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600363 response = self.request(self.tempdir_name + '/?hi=2')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200364 self.check_status_and_reason(response, HTTPStatus.OK)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600365 response = self.request(self.tempdir_name + '?hi=1')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200366 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
Benjamin Peterson94cb7a22014-12-26 10:53:43 -0600367 self.assertEqual(response.getheader("Location"),
368 self.tempdir_name + "/?hi=1")
Georg Brandlb533e262008-05-25 18:19:30 +0000369 response = self.request('/ThisDoesNotExist')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200370 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000371 response = self.request('/' + 'ThisDoesNotExist' + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200372 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300373
374 data = b"Dummy index file\r\n"
375 with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f:
376 f.write(data)
377 response = self.request('/' + self.tempdir_name + '/')
378 self.check_status_and_reason(response, HTTPStatus.OK, data)
379
380 # chmod() doesn't work as expected on Windows, and filesystem
381 # permissions are ignored by root on Unix.
382 if os.name == 'posix' and os.geteuid() != 0:
383 os.chmod(self.tempdir, 0)
384 try:
Brett Cannon105df5d2010-10-29 23:43:42 +0000385 response = self.request(self.tempdir_name + '/')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200386 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
Berker Peksagb5754322015-07-22 19:25:37 +0300387 finally:
Brett Cannon105df5d2010-10-29 23:43:42 +0000388 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000389
390 def test_head(self):
391 response = self.request(
392 self.tempdir_name + '/test', method='HEAD')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200393 self.check_status_and_reason(response, HTTPStatus.OK)
Georg Brandlb533e262008-05-25 18:19:30 +0000394 self.assertEqual(response.getheader('content-length'),
395 str(len(self.data)))
396 self.assertEqual(response.getheader('content-type'),
397 'application/octet-stream')
398
399 def test_invalid_requests(self):
400 response = self.request('/', method='FOO')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200401 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000402 # requests must be case sensitive,so this should fail too
Terry Jan Reedydd09efd2014-10-18 17:10:09 -0400403 response = self.request('/', method='custom')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200404 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000405 response = self.request('/', method='GETs')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200406 self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED)
Georg Brandlb533e262008-05-25 18:19:30 +0000407
408
409cgi_file1 = """\
410#!%s
411
412print("Content-type: text/html")
413print()
414print("Hello World")
415"""
416
417cgi_file2 = """\
418#!%s
419import cgi
420
421print("Content-type: text/html")
422print()
423
424form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000425print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
426 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000427"""
428
Martin Pantera02e18a2015-10-03 05:38:07 +0000429cgi_file4 = """\
430#!%s
431import os
432
433print("Content-type: text/html")
434print()
435
436print(os.environ["%s"])
437"""
438
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100439
440@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
441 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000442class CGIHTTPServerTestCase(BaseTestCase):
443 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
444 pass
445
Antoine Pitroue768c392012-08-05 14:52:45 +0200446 linesep = os.linesep.encode('ascii')
447
Georg Brandlb533e262008-05-25 18:19:30 +0000448 def setUp(self):
449 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000450 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000451 self.parent_dir = tempfile.mkdtemp()
452 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700453 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000454 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700455 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400456 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000457 self.file1_path = None
458 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700459 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000460 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000461
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000462 # The shebang line should be pure ASCII: use symlink if possible.
463 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000464 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000465 self.pythonexe = os.path.join(self.parent_dir, 'python')
466 os.symlink(sys.executable, self.pythonexe)
467 else:
468 self.pythonexe = sys.executable
469
Victor Stinner3218c312010-10-17 20:13:36 +0000470 try:
471 # The python executable path is written as the first line of the
472 # CGI Python script. The encoding cookie cannot be used, and so the
473 # path should be encodable to the default script encoding (utf-8)
474 self.pythonexe.encode('utf-8')
475 except UnicodeEncodeError:
476 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200477 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000478
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400479 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
480 with open(self.nocgi_path, 'w') as fp:
481 fp.write(cgi_file1 % self.pythonexe)
482 os.chmod(self.nocgi_path, 0o777)
483
Georg Brandlb533e262008-05-25 18:19:30 +0000484 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000485 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000486 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000487 os.chmod(self.file1_path, 0o777)
488
489 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000490 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000491 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000492 os.chmod(self.file2_path, 0o777)
493
Ned Deily915a30f2014-07-12 22:06:26 -0700494 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
495 with open(self.file3_path, 'w', encoding='utf-8') as file3:
496 file3.write(cgi_file1 % self.pythonexe)
497 os.chmod(self.file3_path, 0o777)
498
Martin Pantera02e18a2015-10-03 05:38:07 +0000499 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
500 with open(self.file4_path, 'w', encoding='utf-8') as file4:
501 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
502 os.chmod(self.file4_path, 0o777)
503
Georg Brandlb533e262008-05-25 18:19:30 +0000504 os.chdir(self.parent_dir)
505
506 def tearDown(self):
507 try:
508 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000509 if self.pythonexe != sys.executable:
510 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400511 if self.nocgi_path:
512 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000513 if self.file1_path:
514 os.remove(self.file1_path)
515 if self.file2_path:
516 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700517 if self.file3_path:
518 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000519 if self.file4_path:
520 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700521 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000522 os.rmdir(self.cgi_dir)
523 os.rmdir(self.parent_dir)
524 finally:
525 BaseTestCase.tearDown(self)
526
Senthil Kumarand70846b2012-04-12 02:34:32 +0800527 def test_url_collapse_path(self):
528 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000529 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800530 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000531 '..': IndexError,
532 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800533 '/': '//',
534 '//': '//',
535 '/\\': '//\\',
536 '/.//': '//',
537 'cgi-bin/file1.py': '/cgi-bin/file1.py',
538 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
539 'a': '//a',
540 '/a': '//a',
541 '//a': '//a',
542 './a': '//a',
543 './C:/': '/C:/',
544 '/a/b': '/a/b',
545 '/a/b/': '/a/b/',
546 '/a/b/.': '/a/b/',
547 '/a/b/c/..': '/a/b/',
548 '/a/b/c/../d': '/a/b/d',
549 '/a/b/c/../d/e/../f': '/a/b/d/f',
550 '/a/b/c/../d/e/../../f': '/a/b/f',
551 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000552 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800553 '/a/b/c/../d/e/../../../f': '/a/f',
554 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000555 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800556 '/a/b/c/../d/e/../../../../f/..': '//',
557 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000558 }
559 for path, expected in test_vectors.items():
560 if isinstance(expected, type) and issubclass(expected, Exception):
561 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800562 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000563 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800564 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000565 self.assertEqual(expected, actual,
566 msg='path = %r\nGot: %r\nWanted: %r' %
567 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000568
Georg Brandlb533e262008-05-25 18:19:30 +0000569 def test_headers_and_content(self):
570 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200571 self.assertEqual(
572 (res.read(), res.getheader('Content-type'), res.status),
573 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000574
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400575 def test_issue19435(self):
576 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200577 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400578
Georg Brandlb533e262008-05-25 18:19:30 +0000579 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000580 params = urllib.parse.urlencode(
581 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000582 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
583 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
584
Antoine Pitroue768c392012-08-05 14:52:45 +0200585 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000586
587 def test_invaliduri(self):
588 res = self.request('/cgi-bin/invalid')
589 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200590 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000591
592 def test_authorization(self):
593 headers = {b'Authorization' : b'Basic ' +
594 base64.b64encode(b'username:pass')}
595 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200596 self.assertEqual(
597 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
598 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000599
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000600 def test_no_leading_slash(self):
601 # http://bugs.python.org/issue2254
602 res = self.request('cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200603 self.assertEqual(
604 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
605 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000606
Senthil Kumaran42713722010-10-03 17:55:45 +0000607 def test_os_environ_is_not_altered(self):
608 signature = "Test CGI Server"
609 os.environ['SERVER_SOFTWARE'] = signature
610 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200611 self.assertEqual(
612 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
613 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000614 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
615
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700616 def test_urlquote_decoding_in_cgi_check(self):
617 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200618 self.assertEqual(
619 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
620 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700621
Ned Deily915a30f2014-07-12 22:06:26 -0700622 def test_nested_cgi_path_issue21323(self):
623 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200624 self.assertEqual(
625 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
626 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700627
Martin Pantera02e18a2015-10-03 05:38:07 +0000628 def test_query_with_multiple_question_mark(self):
629 res = self.request('/cgi-bin/file4.py?a=b?c=d')
630 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000631 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000632 (res.read(), res.getheader('Content-type'), res.status))
633
Martin Pantercb29e8c2015-10-03 05:55:46 +0000634 def test_query_with_continuous_slashes(self):
635 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
636 self.assertEqual(
637 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000638 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000639 (res.read(), res.getheader('Content-type'), res.status))
640
Georg Brandlb533e262008-05-25 18:19:30 +0000641
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000642class SocketlessRequestHandler(SimpleHTTPRequestHandler):
643 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000644 self.get_called = False
645 self.protocol_version = "HTTP/1.1"
646
647 def do_GET(self):
648 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200649 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000650 self.send_header('Content-Type', 'text/html')
651 self.end_headers()
652 self.wfile.write(b'<html><body>Data</body></html>\r\n')
653
654 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000655 pass
656
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000657class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
658 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200659 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000660 return False
661
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800662
663class AuditableBytesIO:
664
665 def __init__(self):
666 self.datas = []
667
668 def write(self, data):
669 self.datas.append(data)
670
671 def getData(self):
672 return b''.join(self.datas)
673
674 @property
675 def numWrites(self):
676 return len(self.datas)
677
678
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000679class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200680 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000681
682 Test the support for the Expect 100-continue header.
683 """
684
685 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
686
687 def setUp (self):
688 self.handler = SocketlessRequestHandler()
689
690 def send_typical_request(self, message):
691 input = BytesIO(message)
692 output = BytesIO()
693 self.handler.rfile = input
694 self.handler.wfile = output
695 self.handler.handle_one_request()
696 output.seek(0)
697 return output.readlines()
698
699 def verify_get_called(self):
700 self.assertTrue(self.handler.get_called)
701
702 def verify_expected_headers(self, headers):
703 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
704 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
705
706 def verify_http_server_response(self, response):
707 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200708 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000709
710 def test_http_1_1(self):
711 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
712 self.verify_http_server_response(result[0])
713 self.verify_expected_headers(result[1:-1])
714 self.verify_get_called()
715 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500716 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
717 self.assertEqual(self.handler.command, 'GET')
718 self.assertEqual(self.handler.path, '/')
719 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
720 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000721
722 def test_http_1_0(self):
723 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
724 self.verify_http_server_response(result[0])
725 self.verify_expected_headers(result[1:-1])
726 self.verify_get_called()
727 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500728 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
729 self.assertEqual(self.handler.command, 'GET')
730 self.assertEqual(self.handler.path, '/')
731 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
732 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000733
734 def test_http_0_9(self):
735 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
736 self.assertEqual(len(result), 1)
737 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
738 self.verify_get_called()
739
740 def test_with_continue_1_0(self):
741 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
742 self.verify_http_server_response(result[0])
743 self.verify_expected_headers(result[1:-1])
744 self.verify_get_called()
745 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500746 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
747 self.assertEqual(self.handler.command, 'GET')
748 self.assertEqual(self.handler.path, '/')
749 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
750 headers = (("Expect", "100-continue"),)
751 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000752
753 def test_with_continue_1_1(self):
754 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
755 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500756 self.assertEqual(result[1], b'\r\n')
757 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000758 self.verify_expected_headers(result[2:-1])
759 self.verify_get_called()
760 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500761 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
762 self.assertEqual(self.handler.command, 'GET')
763 self.assertEqual(self.handler.path, '/')
764 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
765 headers = (("Expect", "100-continue"),)
766 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000767
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800768 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000769
770 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800771 output = AuditableBytesIO()
772 handler = SocketlessRequestHandler()
773 handler.rfile = input
774 handler.wfile = output
775 handler.request_version = 'HTTP/1.1'
776 handler.requestline = ''
777 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000778
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800779 handler.send_error(418)
780 self.assertEqual(output.numWrites, 2)
781
782 def test_header_buffering_of_send_response_only(self):
783
784 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
785 output = AuditableBytesIO()
786 handler = SocketlessRequestHandler()
787 handler.rfile = input
788 handler.wfile = output
789 handler.request_version = 'HTTP/1.1'
790
791 handler.send_response_only(418)
792 self.assertEqual(output.numWrites, 0)
793 handler.end_headers()
794 self.assertEqual(output.numWrites, 1)
795
796 def test_header_buffering_of_send_header(self):
797
798 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
799 output = AuditableBytesIO()
800 handler = SocketlessRequestHandler()
801 handler.rfile = input
802 handler.wfile = output
803 handler.request_version = 'HTTP/1.1'
804
805 handler.send_header('Foo', 'foo')
806 handler.send_header('bar', 'bar')
807 self.assertEqual(output.numWrites, 0)
808 handler.end_headers()
809 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
810 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000811
812 def test_header_unbuffered_when_continue(self):
813
814 def _readAndReseek(f):
815 pos = f.tell()
816 f.seek(0)
817 data = f.read()
818 f.seek(pos)
819 return data
820
821 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
822 output = BytesIO()
823 self.handler.rfile = input
824 self.handler.wfile = output
825 self.handler.request_version = 'HTTP/1.1'
826
827 self.handler.handle_one_request()
828 self.assertNotEqual(_readAndReseek(output), b'')
829 result = _readAndReseek(output).split(b'\r\n')
830 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500831 self.assertEqual(result[1], b'')
832 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000833
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000834 def test_with_continue_rejected(self):
835 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
836 self.handler = RejectingSocketlessRequestHandler()
837 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
838 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
839 self.verify_expected_headers(result[1:-1])
840 # The expect handler should short circuit the usual get method by
841 # returning false here, so get_called should be false
842 self.assertFalse(self.handler.get_called)
843 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
844 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
845
Antoine Pitrouc4924372010-12-16 16:48:36 +0000846 def test_request_length(self):
847 # Issue #10714: huge request lines are discarded, to avoid Denial
848 # of Service attacks.
849 result = self.send_typical_request(b'GET ' + b'x' * 65537)
850 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
851 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500852 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000853
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000854 def test_header_length(self):
855 # Issue #6791: same for headers
856 result = self.send_typical_request(
857 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
858 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
859 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500860 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
861
862 def test_close_connection(self):
863 # handle_one_request() should be repeatedly called until
864 # it sets close_connection
865 def handle_one_request():
866 self.handler.close_connection = next(close_values)
867 self.handler.handle_one_request = handle_one_request
868
869 close_values = iter((True,))
870 self.handler.handle()
871 self.assertRaises(StopIteration, next, close_values)
872
873 close_values = iter((False, False, True))
874 self.handler.handle()
875 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000876
Berker Peksag04bc5b92016-03-14 06:06:03 +0200877 def test_date_time_string(self):
878 now = time.time()
879 # this is the old code that formats the timestamp
880 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
881 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
882 self.handler.weekdayname[wd],
883 day,
884 self.handler.monthname[month],
885 year, hh, mm, ss
886 )
887 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
888
889
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000890class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
891 """ Test url parsing """
892 def setUp(self):
893 self.translated = os.getcwd()
894 self.translated = os.path.join(self.translated, 'filename')
895 self.handler = SocketlessRequestHandler()
896
897 def test_query_arguments(self):
898 path = self.handler.translate_path('/filename')
899 self.assertEqual(path, self.translated)
900 path = self.handler.translate_path('/filename?foo=bar')
901 self.assertEqual(path, self.translated)
902 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
903 self.assertEqual(path, self.translated)
904
905 def test_start_with_double_slash(self):
906 path = self.handler.translate_path('//filename')
907 self.assertEqual(path, self.translated)
908 path = self.handler.translate_path('//filename?foo=bar')
909 self.assertEqual(path, self.translated)
910
911
Berker Peksag366c5702015-02-13 20:48:15 +0200912class MiscTestCase(unittest.TestCase):
913 def test_all(self):
914 expected = []
915 blacklist = {'executable', 'nobody_uid', 'test'}
916 for name in dir(server):
917 if name.startswith('_') or name in blacklist:
918 continue
919 module_object = getattr(server, name)
920 if getattr(module_object, '__module__', None) == 'http.server':
921 expected.append(name)
922 self.assertCountEqual(server.__all__, expected)
923
924
Georg Brandlb533e262008-05-25 18:19:30 +0000925def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000926 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000927 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000928 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200929 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000930 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000931 BaseHTTPServerTestCase,
932 SimpleHTTPServerTestCase,
933 CGIHTTPServerTestCase,
934 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +0200935 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000936 )
Georg Brandlb533e262008-05-25 18:19:30 +0000937 finally:
938 os.chdir(cwd)
939
940if __name__ == '__main__':
941 test_main()