blob: 3856d00b2b38f63797aa9169bc3f5f15fe66502d [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)
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)
Martin Panterda3bb382016-04-11 00:40:08 +0000347 self.assertIn(('>%s<' % html.escape(filename, quote=False))
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
Martin Panterda3bb382016-04-11 00:40:08 +0000425 def test_html_escape_filename(self):
426 filename = '<test&>.txt'
427 fullpath = os.path.join(self.tempdir, filename)
428
429 try:
430 open(fullpath, 'w').close()
431 except OSError:
432 raise unittest.SkipTest('Can not create file %s on current file '
433 'system' % filename)
434
435 try:
436 response = self.request(self.base_url + '/')
437 body = self.check_status_and_reason(response, HTTPStatus.OK)
438 enc = response.headers.get_content_charset()
439 finally:
440 os.unlink(fullpath) # avoid affecting test_undecodable_filename
441
442 self.assertIsNotNone(enc)
443 html_text = '>%s<' % html.escape(filename, quote=False)
444 self.assertIn(html_text.encode(enc), body)
445
Georg Brandlb533e262008-05-25 18:19:30 +0000446
447cgi_file1 = """\
448#!%s
449
450print("Content-type: text/html")
451print()
452print("Hello World")
453"""
454
455cgi_file2 = """\
456#!%s
457import cgi
458
459print("Content-type: text/html")
460print()
461
462form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000463print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
464 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000465"""
466
Martin Pantera02e18a2015-10-03 05:38:07 +0000467cgi_file4 = """\
468#!%s
469import os
470
471print("Content-type: text/html")
472print()
473
474print(os.environ["%s"])
475"""
476
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100477
478@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
479 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000480class CGIHTTPServerTestCase(BaseTestCase):
481 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
482 pass
483
Antoine Pitroue768c392012-08-05 14:52:45 +0200484 linesep = os.linesep.encode('ascii')
485
Georg Brandlb533e262008-05-25 18:19:30 +0000486 def setUp(self):
487 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000488 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000489 self.parent_dir = tempfile.mkdtemp()
490 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deily915a30f2014-07-12 22:06:26 -0700491 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlb533e262008-05-25 18:19:30 +0000492 os.mkdir(self.cgi_dir)
Ned Deily915a30f2014-07-12 22:06:26 -0700493 os.mkdir(self.cgi_child_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400494 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000495 self.file1_path = None
496 self.file2_path = None
Ned Deily915a30f2014-07-12 22:06:26 -0700497 self.file3_path = None
Martin Pantera02e18a2015-10-03 05:38:07 +0000498 self.file4_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000499
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000500 # The shebang line should be pure ASCII: use symlink if possible.
501 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000502 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000503 self.pythonexe = os.path.join(self.parent_dir, 'python')
504 os.symlink(sys.executable, self.pythonexe)
505 else:
506 self.pythonexe = sys.executable
507
Victor Stinner3218c312010-10-17 20:13:36 +0000508 try:
509 # The python executable path is written as the first line of the
510 # CGI Python script. The encoding cookie cannot be used, and so the
511 # path should be encodable to the default script encoding (utf-8)
512 self.pythonexe.encode('utf-8')
513 except UnicodeEncodeError:
514 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200515 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000516
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400517 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
518 with open(self.nocgi_path, 'w') as fp:
519 fp.write(cgi_file1 % self.pythonexe)
520 os.chmod(self.nocgi_path, 0o777)
521
Georg Brandlb533e262008-05-25 18:19:30 +0000522 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000523 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000524 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000525 os.chmod(self.file1_path, 0o777)
526
527 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000528 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000529 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000530 os.chmod(self.file2_path, 0o777)
531
Ned Deily915a30f2014-07-12 22:06:26 -0700532 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
533 with open(self.file3_path, 'w', encoding='utf-8') as file3:
534 file3.write(cgi_file1 % self.pythonexe)
535 os.chmod(self.file3_path, 0o777)
536
Martin Pantera02e18a2015-10-03 05:38:07 +0000537 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
538 with open(self.file4_path, 'w', encoding='utf-8') as file4:
539 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
540 os.chmod(self.file4_path, 0o777)
541
Georg Brandlb533e262008-05-25 18:19:30 +0000542 os.chdir(self.parent_dir)
543
544 def tearDown(self):
545 try:
546 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000547 if self.pythonexe != sys.executable:
548 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400549 if self.nocgi_path:
550 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000551 if self.file1_path:
552 os.remove(self.file1_path)
553 if self.file2_path:
554 os.remove(self.file2_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700555 if self.file3_path:
556 os.remove(self.file3_path)
Martin Pantera02e18a2015-10-03 05:38:07 +0000557 if self.file4_path:
558 os.remove(self.file4_path)
Ned Deily915a30f2014-07-12 22:06:26 -0700559 os.rmdir(self.cgi_child_dir)
Georg Brandlb533e262008-05-25 18:19:30 +0000560 os.rmdir(self.cgi_dir)
561 os.rmdir(self.parent_dir)
562 finally:
563 BaseTestCase.tearDown(self)
564
Senthil Kumarand70846b2012-04-12 02:34:32 +0800565 def test_url_collapse_path(self):
566 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000567 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800568 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000569 '..': IndexError,
570 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800571 '/': '//',
572 '//': '//',
573 '/\\': '//\\',
574 '/.//': '//',
575 'cgi-bin/file1.py': '/cgi-bin/file1.py',
576 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
577 'a': '//a',
578 '/a': '//a',
579 '//a': '//a',
580 './a': '//a',
581 './C:/': '/C:/',
582 '/a/b': '/a/b',
583 '/a/b/': '/a/b/',
584 '/a/b/.': '/a/b/',
585 '/a/b/c/..': '/a/b/',
586 '/a/b/c/../d': '/a/b/d',
587 '/a/b/c/../d/e/../f': '/a/b/d/f',
588 '/a/b/c/../d/e/../../f': '/a/b/f',
589 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000590 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800591 '/a/b/c/../d/e/../../../f': '/a/f',
592 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000593 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800594 '/a/b/c/../d/e/../../../../f/..': '//',
595 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000596 }
597 for path, expected in test_vectors.items():
598 if isinstance(expected, type) and issubclass(expected, Exception):
599 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800600 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000601 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800602 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000603 self.assertEqual(expected, actual,
604 msg='path = %r\nGot: %r\nWanted: %r' %
605 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000606
Georg Brandlb533e262008-05-25 18:19:30 +0000607 def test_headers_and_content(self):
608 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200609 self.assertEqual(
610 (res.read(), res.getheader('Content-type'), res.status),
611 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK))
Georg Brandlb533e262008-05-25 18:19:30 +0000612
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400613 def test_issue19435(self):
614 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200615 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400616
Georg Brandlb533e262008-05-25 18:19:30 +0000617 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000618 params = urllib.parse.urlencode(
619 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000620 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
621 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
622
Antoine Pitroue768c392012-08-05 14:52:45 +0200623 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000624
625 def test_invaliduri(self):
626 res = self.request('/cgi-bin/invalid')
627 res.read()
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200628 self.assertEqual(res.status, HTTPStatus.NOT_FOUND)
Georg Brandlb533e262008-05-25 18:19:30 +0000629
630 def test_authorization(self):
631 headers = {b'Authorization' : b'Basic ' +
632 base64.b64encode(b'username:pass')}
633 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200634 self.assertEqual(
635 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
636 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000637
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000638 def test_no_leading_slash(self):
639 # http://bugs.python.org/issue2254
640 res = self.request('cgi-bin/file1.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))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000644
Senthil Kumaran42713722010-10-03 17:55:45 +0000645 def test_os_environ_is_not_altered(self):
646 signature = "Test CGI Server"
647 os.environ['SERVER_SOFTWARE'] = signature
648 res = self.request('/cgi-bin/file1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200649 self.assertEqual(
650 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
651 (res.read(), res.getheader('Content-type'), res.status))
Senthil Kumaran42713722010-10-03 17:55:45 +0000652 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
653
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700654 def test_urlquote_decoding_in_cgi_check(self):
655 res = self.request('/cgi-bin%2ffile1.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200656 self.assertEqual(
657 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
658 (res.read(), res.getheader('Content-type'), res.status))
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700659
Ned Deily915a30f2014-07-12 22:06:26 -0700660 def test_nested_cgi_path_issue21323(self):
661 res = self.request('/cgi-bin/child-dir/file3.py')
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200662 self.assertEqual(
663 (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK),
664 (res.read(), res.getheader('Content-type'), res.status))
Ned Deily915a30f2014-07-12 22:06:26 -0700665
Martin Pantera02e18a2015-10-03 05:38:07 +0000666 def test_query_with_multiple_question_mark(self):
667 res = self.request('/cgi-bin/file4.py?a=b?c=d')
668 self.assertEqual(
Martin Pantereb1fee92015-10-03 06:07:22 +0000669 (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK),
Martin Pantera02e18a2015-10-03 05:38:07 +0000670 (res.read(), res.getheader('Content-type'), res.status))
671
Martin Pantercb29e8c2015-10-03 05:55:46 +0000672 def test_query_with_continuous_slashes(self):
673 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
674 self.assertEqual(
675 (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep,
Martin Pantereb1fee92015-10-03 06:07:22 +0000676 'text/html', HTTPStatus.OK),
Martin Pantercb29e8c2015-10-03 05:55:46 +0000677 (res.read(), res.getheader('Content-type'), res.status))
678
Georg Brandlb533e262008-05-25 18:19:30 +0000679
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000680class SocketlessRequestHandler(SimpleHTTPRequestHandler):
681 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000682 self.get_called = False
683 self.protocol_version = "HTTP/1.1"
684
685 def do_GET(self):
686 self.get_called = True
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200687 self.send_response(HTTPStatus.OK)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000688 self.send_header('Content-Type', 'text/html')
689 self.end_headers()
690 self.wfile.write(b'<html><body>Data</body></html>\r\n')
691
692 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000693 pass
694
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000695class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
696 def handle_expect_100(self):
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200697 self.send_error(HTTPStatus.EXPECTATION_FAILED)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000698 return False
699
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800700
701class AuditableBytesIO:
702
703 def __init__(self):
704 self.datas = []
705
706 def write(self, data):
707 self.datas.append(data)
708
709 def getData(self):
710 return b''.join(self.datas)
711
712 @property
713 def numWrites(self):
714 return len(self.datas)
715
716
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000717class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200718 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000719
720 Test the support for the Expect 100-continue header.
721 """
722
723 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
724
725 def setUp (self):
726 self.handler = SocketlessRequestHandler()
727
728 def send_typical_request(self, message):
729 input = BytesIO(message)
730 output = BytesIO()
731 self.handler.rfile = input
732 self.handler.wfile = output
733 self.handler.handle_one_request()
734 output.seek(0)
735 return output.readlines()
736
737 def verify_get_called(self):
738 self.assertTrue(self.handler.get_called)
739
740 def verify_expected_headers(self, headers):
741 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
742 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
743
744 def verify_http_server_response(self, response):
745 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200746 self.assertIsNotNone(match)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000747
748 def test_http_1_1(self):
749 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
750 self.verify_http_server_response(result[0])
751 self.verify_expected_headers(result[1:-1])
752 self.verify_get_called()
753 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500754 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
755 self.assertEqual(self.handler.command, 'GET')
756 self.assertEqual(self.handler.path, '/')
757 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
758 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000759
760 def test_http_1_0(self):
761 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
762 self.verify_http_server_response(result[0])
763 self.verify_expected_headers(result[1:-1])
764 self.verify_get_called()
765 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500766 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
767 self.assertEqual(self.handler.command, 'GET')
768 self.assertEqual(self.handler.path, '/')
769 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
770 self.assertSequenceEqual(self.handler.headers.items(), ())
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000771
772 def test_http_0_9(self):
773 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
774 self.assertEqual(len(result), 1)
775 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
776 self.verify_get_called()
777
778 def test_with_continue_1_0(self):
779 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
780 self.verify_http_server_response(result[0])
781 self.verify_expected_headers(result[1:-1])
782 self.verify_get_called()
783 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500784 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0')
785 self.assertEqual(self.handler.command, 'GET')
786 self.assertEqual(self.handler.path, '/')
787 self.assertEqual(self.handler.request_version, 'HTTP/1.0')
788 headers = (("Expect", "100-continue"),)
789 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000790
791 def test_with_continue_1_1(self):
792 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
793 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
Benjamin Peterson04424232014-01-18 21:50:18 -0500794 self.assertEqual(result[1], b'\r\n')
795 self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n')
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000796 self.verify_expected_headers(result[2:-1])
797 self.verify_get_called()
798 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
Benjamin Peterson70e28472015-02-17 21:11:10 -0500799 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
800 self.assertEqual(self.handler.command, 'GET')
801 self.assertEqual(self.handler.path, '/')
802 self.assertEqual(self.handler.request_version, 'HTTP/1.1')
803 headers = (("Expect", "100-continue"),)
804 self.assertSequenceEqual(self.handler.headers.items(), headers)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000805
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800806 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000807
808 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800809 output = AuditableBytesIO()
810 handler = SocketlessRequestHandler()
811 handler.rfile = input
812 handler.wfile = output
813 handler.request_version = 'HTTP/1.1'
814 handler.requestline = ''
815 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000816
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800817 handler.send_error(418)
818 self.assertEqual(output.numWrites, 2)
819
820 def test_header_buffering_of_send_response_only(self):
821
822 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
823 output = AuditableBytesIO()
824 handler = SocketlessRequestHandler()
825 handler.rfile = input
826 handler.wfile = output
827 handler.request_version = 'HTTP/1.1'
828
829 handler.send_response_only(418)
830 self.assertEqual(output.numWrites, 0)
831 handler.end_headers()
832 self.assertEqual(output.numWrites, 1)
833
834 def test_header_buffering_of_send_header(self):
835
836 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
837 output = AuditableBytesIO()
838 handler = SocketlessRequestHandler()
839 handler.rfile = input
840 handler.wfile = output
841 handler.request_version = 'HTTP/1.1'
842
843 handler.send_header('Foo', 'foo')
844 handler.send_header('bar', 'bar')
845 self.assertEqual(output.numWrites, 0)
846 handler.end_headers()
847 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
848 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000849
850 def test_header_unbuffered_when_continue(self):
851
852 def _readAndReseek(f):
853 pos = f.tell()
854 f.seek(0)
855 data = f.read()
856 f.seek(pos)
857 return data
858
859 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
860 output = BytesIO()
861 self.handler.rfile = input
862 self.handler.wfile = output
863 self.handler.request_version = 'HTTP/1.1'
864
865 self.handler.handle_one_request()
866 self.assertNotEqual(_readAndReseek(output), b'')
867 result = _readAndReseek(output).split(b'\r\n')
868 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
Benjamin Peterson04424232014-01-18 21:50:18 -0500869 self.assertEqual(result[1], b'')
870 self.assertEqual(result[2], b'HTTP/1.1 200 OK')
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000871
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000872 def test_with_continue_rejected(self):
873 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
874 self.handler = RejectingSocketlessRequestHandler()
875 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
876 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
877 self.verify_expected_headers(result[1:-1])
878 # The expect handler should short circuit the usual get method by
879 # returning false here, so get_called should be false
880 self.assertFalse(self.handler.get_called)
881 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
882 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
883
Antoine Pitrouc4924372010-12-16 16:48:36 +0000884 def test_request_length(self):
885 # Issue #10714: huge request lines are discarded, to avoid Denial
886 # of Service attacks.
887 result = self.send_typical_request(b'GET ' + b'x' * 65537)
888 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
889 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500890 self.assertIsInstance(self.handler.requestline, str)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000891
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000892 def test_header_length(self):
893 # Issue #6791: same for headers
894 result = self.send_typical_request(
895 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
Martin Panter50badad2016-04-03 01:28:53 +0000896 self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n')
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000897 self.assertFalse(self.handler.get_called)
Benjamin Peterson70e28472015-02-17 21:11:10 -0500898 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
899
Martin Panteracc03192016-04-03 00:45:46 +0000900 def test_too_many_headers(self):
901 result = self.send_typical_request(
902 b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n')
903 self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n')
904 self.assertFalse(self.handler.get_called)
905 self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1')
906
Martin Panterda3bb382016-04-11 00:40:08 +0000907 def test_html_escape_on_error(self):
908 result = self.send_typical_request(
909 b'<script>alert("hello")</script> / HTTP/1.1')
910 result = b''.join(result)
911 text = '<script>alert("hello")</script>'
912 self.assertIn(html.escape(text, quote=False).encode('ascii'), result)
913
Benjamin Peterson70e28472015-02-17 21:11:10 -0500914 def test_close_connection(self):
915 # handle_one_request() should be repeatedly called until
916 # it sets close_connection
917 def handle_one_request():
918 self.handler.close_connection = next(close_values)
919 self.handler.handle_one_request = handle_one_request
920
921 close_values = iter((True,))
922 self.handler.handle()
923 self.assertRaises(StopIteration, next, close_values)
924
925 close_values = iter((False, False, True))
926 self.handler.handle()
927 self.assertRaises(StopIteration, next, close_values)
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000928
Berker Peksag04bc5b92016-03-14 06:06:03 +0200929 def test_date_time_string(self):
930 now = time.time()
931 # this is the old code that formats the timestamp
932 year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now)
933 expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
934 self.handler.weekdayname[wd],
935 day,
936 self.handler.monthname[month],
937 year, hh, mm, ss
938 )
939 self.assertEqual(self.handler.date_time_string(timestamp=now), expected)
940
941
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000942class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
943 """ Test url parsing """
944 def setUp(self):
945 self.translated = os.getcwd()
946 self.translated = os.path.join(self.translated, 'filename')
947 self.handler = SocketlessRequestHandler()
948
949 def test_query_arguments(self):
950 path = self.handler.translate_path('/filename')
951 self.assertEqual(path, self.translated)
952 path = self.handler.translate_path('/filename?foo=bar')
953 self.assertEqual(path, self.translated)
954 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
955 self.assertEqual(path, self.translated)
956
957 def test_start_with_double_slash(self):
958 path = self.handler.translate_path('//filename')
959 self.assertEqual(path, self.translated)
960 path = self.handler.translate_path('//filename?foo=bar')
961 self.assertEqual(path, self.translated)
962
963
Berker Peksag366c5702015-02-13 20:48:15 +0200964class MiscTestCase(unittest.TestCase):
965 def test_all(self):
966 expected = []
967 blacklist = {'executable', 'nobody_uid', 'test'}
968 for name in dir(server):
969 if name.startswith('_') or name in blacklist:
970 continue
971 module_object = getattr(server, name)
972 if getattr(module_object, '__module__', None) == 'http.server':
973 expected.append(name)
974 self.assertCountEqual(server.__all__, expected)
975
976
Georg Brandlb533e262008-05-25 18:19:30 +0000977def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000978 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000979 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000980 support.run_unittest(
Serhiy Storchakac0a23e62015-03-07 11:51:37 +0200981 RequestHandlerLoggingTestCase,
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000982 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000983 BaseHTTPServerTestCase,
984 SimpleHTTPServerTestCase,
985 CGIHTTPServerTestCase,
986 SimpleHTTPRequestHandlerTestCase,
Berker Peksag366c5702015-02-13 20:48:15 +0200987 MiscTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000988 )
Georg Brandlb533e262008-05-25 18:19:30 +0000989 finally:
990 os.chdir(cwd)
991
992if __name__ == '__main__':
993 test_main()