blob: ec751cce38b2ddd88e380a3b611db3781ec5213b [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
Benjamin Petersonad71f0f2009-04-11 20:12:10 +00009from http import server
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
Georg Brandl24420152008-05-26 16:32:26 +000017import http.client
Georg Brandlb533e262008-05-25 18:19:30 +000018import tempfile
Senthil Kumaran0f476d42010-09-30 06:09:18 +000019from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000020
21import unittest
22from test import support
Victor Stinner45df8202010-04-28 22:31:17 +000023threading = support.import_module('threading')
Georg Brandlb533e262008-05-25 18:19:30 +000024
Georg Brandlb533e262008-05-25 18:19:30 +000025class NoLogRequestHandler:
26 def log_message(self, *args):
27 # don't write log messages to stderr
28 pass
29
Barry Warsaw820c1202008-06-12 04:06:45 +000030 def read(self, n=None):
31 return ''
32
Georg Brandlb533e262008-05-25 18:19:30 +000033
34class TestServerThread(threading.Thread):
35 def __init__(self, test_object, request_handler):
36 threading.Thread.__init__(self)
37 self.request_handler = request_handler
38 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000039
40 def run(self):
Antoine Pitroucb342182011-03-21 00:26:51 +010041 self.server = HTTPServer(('localhost', 0), self.request_handler)
42 self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000043 self.test_object.server_started.set()
44 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000045 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000046 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000047 finally:
48 self.server.server_close()
49
50 def stop(self):
51 self.server.shutdown()
52
53
54class BaseTestCase(unittest.TestCase):
55 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000056 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000057 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000058 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000059 self.thread = TestServerThread(self, self.request_handler)
60 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000061 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000062
63 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000064 self.thread.stop()
Antoine Pitrouf7270822012-09-30 01:05:30 +020065 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000066 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000067 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000068
69 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010070 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000071 self.connection.request(method, uri, body, headers)
72 return self.connection.getresponse()
73
74
75class BaseHTTPServerTestCase(BaseTestCase):
76 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
77 protocol_version = 'HTTP/1.1'
78 default_request_version = 'HTTP/1.1'
79
80 def do_TEST(self):
81 self.send_response(204)
82 self.send_header('Content-Type', 'text/html')
83 self.send_header('Connection', 'close')
84 self.end_headers()
85
86 def do_KEEP(self):
87 self.send_response(204)
88 self.send_header('Content-Type', 'text/html')
89 self.send_header('Connection', 'keep-alive')
90 self.end_headers()
91
92 def do_KEYERROR(self):
93 self.send_error(999)
94
Senthil Kumaran52d27202012-10-10 23:16:21 -070095 def do_NOTFOUND(self):
96 self.send_error(404)
97
Senthil Kumaran26886442013-03-15 07:53:21 -070098 def do_EXPLAINERROR(self):
99 self.send_error(999, "Short Message",
100 "This is a long \n explaination")
101
Georg Brandlb533e262008-05-25 18:19:30 +0000102 def do_CUSTOM(self):
103 self.send_response(999)
104 self.send_header('Content-Type', 'text/html')
105 self.send_header('Connection', 'close')
106 self.end_headers()
107
Armin Ronacher8d96d772011-01-22 13:13:05 +0000108 def do_LATINONEHEADER(self):
109 self.send_response(999)
110 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000111 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000112 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000113 body = self.headers['x-special-incoming'].encode('utf-8')
114 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000115
Georg Brandlb533e262008-05-25 18:19:30 +0000116 def setUp(self):
117 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100118 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000119 self.con.connect()
120
121 def test_command(self):
122 self.con.request('GET', '/')
123 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000124 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000125
126 def test_request_line_trimming(self):
127 self.con._http_vsn_str = 'HTTP/1.1\n'
128 self.con.putrequest('GET', '/')
129 self.con.endheaders()
130 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000131 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000132
133 def test_version_bogus(self):
134 self.con._http_vsn_str = 'FUBAR'
135 self.con.putrequest('GET', '/')
136 self.con.endheaders()
137 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000138 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000139
140 def test_version_digits(self):
141 self.con._http_vsn_str = 'HTTP/9.9.9'
142 self.con.putrequest('GET', '/')
143 self.con.endheaders()
144 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000145 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000146
147 def test_version_none_get(self):
148 self.con._http_vsn_str = ''
149 self.con.putrequest('GET', '/')
150 self.con.endheaders()
151 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000152 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000153
154 def test_version_none(self):
155 self.con._http_vsn_str = ''
156 self.con.putrequest('PUT', '/')
157 self.con.endheaders()
158 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000159 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000160
161 def test_version_invalid(self):
162 self.con._http_vsn = 99
163 self.con._http_vsn_str = 'HTTP/9.9'
164 self.con.putrequest('GET', '/')
165 self.con.endheaders()
166 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000167 self.assertEqual(res.status, 505)
Georg Brandlb533e262008-05-25 18:19:30 +0000168
169 def test_send_blank(self):
170 self.con._http_vsn_str = ''
171 self.con.putrequest('', '')
172 self.con.endheaders()
173 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000174 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000175
176 def test_header_close(self):
177 self.con.putrequest('GET', '/')
178 self.con.putheader('Connection', 'close')
179 self.con.endheaders()
180 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000181 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000182
183 def test_head_keep_alive(self):
184 self.con._http_vsn_str = 'HTTP/1.1'
185 self.con.putrequest('GET', '/')
186 self.con.putheader('Connection', 'keep-alive')
187 self.con.endheaders()
188 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000189 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000190
191 def test_handler(self):
192 self.con.request('TEST', '/')
193 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000194 self.assertEqual(res.status, 204)
Georg Brandlb533e262008-05-25 18:19:30 +0000195
196 def test_return_header_keep_alive(self):
197 self.con.request('KEEP', '/')
198 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000199 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000200 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000201 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000202
203 def test_internal_key_error(self):
204 self.con.request('KEYERROR', '/')
205 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000206 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000207
208 def test_return_custom_status(self):
209 self.con.request('CUSTOM', '/')
210 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000211 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000212
Senthil Kumaran26886442013-03-15 07:53:21 -0700213 def test_return_explain_error(self):
214 self.con.request('EXPLAINERROR', '/')
215 res = self.con.getresponse()
216 self.assertEqual(res.status, 999)
217 self.assertTrue(int(res.getheader('Content-Length')))
218
Armin Ronacher8d96d772011-01-22 13:13:05 +0000219 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000220 self.con.request('LATINONEHEADER', '/', headers={
221 'X-Special-Incoming': 'Ärger mit Unicode'
222 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000223 res = self.con.getresponse()
224 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000225 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000226
Senthil Kumaran52d27202012-10-10 23:16:21 -0700227 def test_error_content_length(self):
228 # Issue #16088: standard error responses should have a content-length
229 self.con.request('NOTFOUND', '/')
230 res = self.con.getresponse()
231 self.assertEqual(res.status, 404)
232 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700233 self.assertEqual(int(res.getheader('Content-Length')), len(data))
234
Georg Brandlb533e262008-05-25 18:19:30 +0000235
236class SimpleHTTPServerTestCase(BaseTestCase):
237 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
238 pass
239
240 def setUp(self):
241 BaseTestCase.setUp(self)
242 self.cwd = os.getcwd()
243 basetempdir = tempfile.gettempdir()
244 os.chdir(basetempdir)
245 self.data = b'We are the knights who say Ni!'
246 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
247 self.tempdir_name = os.path.basename(self.tempdir)
Brett Cannon105df5d2010-10-29 23:43:42 +0000248 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
249 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000250
251 def tearDown(self):
252 try:
253 os.chdir(self.cwd)
254 try:
255 shutil.rmtree(self.tempdir)
256 except:
257 pass
258 finally:
259 BaseTestCase.tearDown(self)
260
261 def check_status_and_reason(self, response, status, data=None):
262 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000263 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000264 self.assertEqual(response.status, status)
265 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000266 if data:
267 self.assertEqual(data, body)
268
269 def test_get(self):
270 #constructs the path relative to the root directory of the HTTPServer
271 response = self.request(self.tempdir_name + '/test')
272 self.check_status_and_reason(response, 200, data=self.data)
273 response = self.request(self.tempdir_name + '/')
274 self.check_status_and_reason(response, 200)
275 response = self.request(self.tempdir_name)
276 self.check_status_and_reason(response, 301)
277 response = self.request('/ThisDoesNotExist')
278 self.check_status_and_reason(response, 404)
279 response = self.request('/' + 'ThisDoesNotExist' + '/')
280 self.check_status_and_reason(response, 404)
Brett Cannon105df5d2010-10-29 23:43:42 +0000281 with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as f:
282 response = self.request('/' + self.tempdir_name + '/')
283 self.check_status_and_reason(response, 200)
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100284 # chmod() doesn't work as expected on Windows, and filesystem
285 # permissions are ignored by root on Unix.
286 if os.name == 'posix' and os.geteuid() != 0:
Brett Cannon105df5d2010-10-29 23:43:42 +0000287 os.chmod(self.tempdir, 0)
288 response = self.request(self.tempdir_name + '/')
289 self.check_status_and_reason(response, 404)
290 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000291
292 def test_head(self):
293 response = self.request(
294 self.tempdir_name + '/test', method='HEAD')
295 self.check_status_and_reason(response, 200)
296 self.assertEqual(response.getheader('content-length'),
297 str(len(self.data)))
298 self.assertEqual(response.getheader('content-type'),
299 'application/octet-stream')
300
301 def test_invalid_requests(self):
302 response = self.request('/', method='FOO')
303 self.check_status_and_reason(response, 501)
304 # requests must be case sensitive,so this should fail too
305 response = self.request('/', method='get')
306 self.check_status_and_reason(response, 501)
307 response = self.request('/', method='GETs')
308 self.check_status_and_reason(response, 501)
309
310
311cgi_file1 = """\
312#!%s
313
314print("Content-type: text/html")
315print()
316print("Hello World")
317"""
318
319cgi_file2 = """\
320#!%s
321import cgi
322
323print("Content-type: text/html")
324print()
325
326form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000327print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
328 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000329"""
330
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100331
332@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
333 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000334class CGIHTTPServerTestCase(BaseTestCase):
335 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
336 pass
337
Antoine Pitroue768c392012-08-05 14:52:45 +0200338 linesep = os.linesep.encode('ascii')
339
Georg Brandlb533e262008-05-25 18:19:30 +0000340 def setUp(self):
341 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000342 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000343 self.parent_dir = tempfile.mkdtemp()
344 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
345 os.mkdir(self.cgi_dir)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000346 self.file1_path = None
347 self.file2_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000348
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000349 # The shebang line should be pure ASCII: use symlink if possible.
350 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000351 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000352 self.pythonexe = os.path.join(self.parent_dir, 'python')
353 os.symlink(sys.executable, self.pythonexe)
354 else:
355 self.pythonexe = sys.executable
356
Victor Stinner3218c312010-10-17 20:13:36 +0000357 try:
358 # The python executable path is written as the first line of the
359 # CGI Python script. The encoding cookie cannot be used, and so the
360 # path should be encodable to the default script encoding (utf-8)
361 self.pythonexe.encode('utf-8')
362 except UnicodeEncodeError:
363 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200364 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000365
Georg Brandlb533e262008-05-25 18:19:30 +0000366 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000367 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000368 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000369 os.chmod(self.file1_path, 0o777)
370
371 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000372 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000373 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000374 os.chmod(self.file2_path, 0o777)
375
Georg Brandlb533e262008-05-25 18:19:30 +0000376 os.chdir(self.parent_dir)
377
378 def tearDown(self):
379 try:
380 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000381 if self.pythonexe != sys.executable:
382 os.remove(self.pythonexe)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000383 if self.file1_path:
384 os.remove(self.file1_path)
385 if self.file2_path:
386 os.remove(self.file2_path)
Georg Brandlb533e262008-05-25 18:19:30 +0000387 os.rmdir(self.cgi_dir)
388 os.rmdir(self.parent_dir)
389 finally:
390 BaseTestCase.tearDown(self)
391
Senthil Kumarand70846b2012-04-12 02:34:32 +0800392 def test_url_collapse_path(self):
393 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000394 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800395 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000396 '..': IndexError,
397 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800398 '/': '//',
399 '//': '//',
400 '/\\': '//\\',
401 '/.//': '//',
402 'cgi-bin/file1.py': '/cgi-bin/file1.py',
403 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
404 'a': '//a',
405 '/a': '//a',
406 '//a': '//a',
407 './a': '//a',
408 './C:/': '/C:/',
409 '/a/b': '/a/b',
410 '/a/b/': '/a/b/',
411 '/a/b/.': '/a/b/',
412 '/a/b/c/..': '/a/b/',
413 '/a/b/c/../d': '/a/b/d',
414 '/a/b/c/../d/e/../f': '/a/b/d/f',
415 '/a/b/c/../d/e/../../f': '/a/b/f',
416 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000417 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800418 '/a/b/c/../d/e/../../../f': '/a/f',
419 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000420 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800421 '/a/b/c/../d/e/../../../../f/..': '//',
422 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000423 }
424 for path, expected in test_vectors.items():
425 if isinstance(expected, type) and issubclass(expected, Exception):
426 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800427 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000428 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800429 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000430 self.assertEqual(expected, actual,
431 msg='path = %r\nGot: %r\nWanted: %r' %
432 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000433
Georg Brandlb533e262008-05-25 18:19:30 +0000434 def test_headers_and_content(self):
435 res = self.request('/cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200436 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000437 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000438
439 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000440 params = urllib.parse.urlencode(
441 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000442 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
443 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
444
Antoine Pitroue768c392012-08-05 14:52:45 +0200445 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000446
447 def test_invaliduri(self):
448 res = self.request('/cgi-bin/invalid')
449 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000450 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000451
452 def test_authorization(self):
453 headers = {b'Authorization' : b'Basic ' +
454 base64.b64encode(b'username:pass')}
455 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Antoine Pitroue768c392012-08-05 14:52:45 +0200456 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000457 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000458
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000459 def test_no_leading_slash(self):
460 # http://bugs.python.org/issue2254
461 res = self.request('cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200462 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000463 (res.read(), res.getheader('Content-type'), res.status))
464
Senthil Kumaran42713722010-10-03 17:55:45 +0000465 def test_os_environ_is_not_altered(self):
466 signature = "Test CGI Server"
467 os.environ['SERVER_SOFTWARE'] = signature
468 res = self.request('/cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200469 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Senthil Kumaran42713722010-10-03 17:55:45 +0000470 (res.read(), res.getheader('Content-type'), res.status))
471 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
472
Georg Brandlb533e262008-05-25 18:19:30 +0000473
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000474class SocketlessRequestHandler(SimpleHTTPRequestHandler):
475 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000476 self.get_called = False
477 self.protocol_version = "HTTP/1.1"
478
479 def do_GET(self):
480 self.get_called = True
481 self.send_response(200)
482 self.send_header('Content-Type', 'text/html')
483 self.end_headers()
484 self.wfile.write(b'<html><body>Data</body></html>\r\n')
485
486 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000487 pass
488
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000489class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
490 def handle_expect_100(self):
491 self.send_error(417)
492 return False
493
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800494
495class AuditableBytesIO:
496
497 def __init__(self):
498 self.datas = []
499
500 def write(self, data):
501 self.datas.append(data)
502
503 def getData(self):
504 return b''.join(self.datas)
505
506 @property
507 def numWrites(self):
508 return len(self.datas)
509
510
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000511class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200512 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000513
514 Test the support for the Expect 100-continue header.
515 """
516
517 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
518
519 def setUp (self):
520 self.handler = SocketlessRequestHandler()
521
522 def send_typical_request(self, message):
523 input = BytesIO(message)
524 output = BytesIO()
525 self.handler.rfile = input
526 self.handler.wfile = output
527 self.handler.handle_one_request()
528 output.seek(0)
529 return output.readlines()
530
531 def verify_get_called(self):
532 self.assertTrue(self.handler.get_called)
533
534 def verify_expected_headers(self, headers):
535 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
536 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
537
538 def verify_http_server_response(self, response):
539 match = self.HTTPResponseMatch.search(response)
540 self.assertTrue(match is not None)
541
542 def test_http_1_1(self):
543 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
544 self.verify_http_server_response(result[0])
545 self.verify_expected_headers(result[1:-1])
546 self.verify_get_called()
547 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
548
549 def test_http_1_0(self):
550 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
551 self.verify_http_server_response(result[0])
552 self.verify_expected_headers(result[1:-1])
553 self.verify_get_called()
554 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
555
556 def test_http_0_9(self):
557 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
558 self.assertEqual(len(result), 1)
559 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
560 self.verify_get_called()
561
562 def test_with_continue_1_0(self):
563 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
564 self.verify_http_server_response(result[0])
565 self.verify_expected_headers(result[1:-1])
566 self.verify_get_called()
567 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
568
569 def test_with_continue_1_1(self):
570 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
571 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
572 self.assertEqual(result[1], b'HTTP/1.1 200 OK\r\n')
573 self.verify_expected_headers(result[2:-1])
574 self.verify_get_called()
575 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
576
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800577 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000578
579 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800580 output = AuditableBytesIO()
581 handler = SocketlessRequestHandler()
582 handler.rfile = input
583 handler.wfile = output
584 handler.request_version = 'HTTP/1.1'
585 handler.requestline = ''
586 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000587
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800588 handler.send_error(418)
589 self.assertEqual(output.numWrites, 2)
590
591 def test_header_buffering_of_send_response_only(self):
592
593 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
594 output = AuditableBytesIO()
595 handler = SocketlessRequestHandler()
596 handler.rfile = input
597 handler.wfile = output
598 handler.request_version = 'HTTP/1.1'
599
600 handler.send_response_only(418)
601 self.assertEqual(output.numWrites, 0)
602 handler.end_headers()
603 self.assertEqual(output.numWrites, 1)
604
605 def test_header_buffering_of_send_header(self):
606
607 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
608 output = AuditableBytesIO()
609 handler = SocketlessRequestHandler()
610 handler.rfile = input
611 handler.wfile = output
612 handler.request_version = 'HTTP/1.1'
613
614 handler.send_header('Foo', 'foo')
615 handler.send_header('bar', 'bar')
616 self.assertEqual(output.numWrites, 0)
617 handler.end_headers()
618 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
619 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000620
621 def test_header_unbuffered_when_continue(self):
622
623 def _readAndReseek(f):
624 pos = f.tell()
625 f.seek(0)
626 data = f.read()
627 f.seek(pos)
628 return data
629
630 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
631 output = BytesIO()
632 self.handler.rfile = input
633 self.handler.wfile = output
634 self.handler.request_version = 'HTTP/1.1'
635
636 self.handler.handle_one_request()
637 self.assertNotEqual(_readAndReseek(output), b'')
638 result = _readAndReseek(output).split(b'\r\n')
639 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
640 self.assertEqual(result[1], b'HTTP/1.1 200 OK')
641
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000642 def test_with_continue_rejected(self):
643 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
644 self.handler = RejectingSocketlessRequestHandler()
645 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
646 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
647 self.verify_expected_headers(result[1:-1])
648 # The expect handler should short circuit the usual get method by
649 # returning false here, so get_called should be false
650 self.assertFalse(self.handler.get_called)
651 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
652 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
653
Antoine Pitrouc4924372010-12-16 16:48:36 +0000654 def test_request_length(self):
655 # Issue #10714: huge request lines are discarded, to avoid Denial
656 # of Service attacks.
657 result = self.send_typical_request(b'GET ' + b'x' * 65537)
658 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
659 self.assertFalse(self.handler.get_called)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000660
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000661 def test_header_length(self):
662 # Issue #6791: same for headers
663 result = self.send_typical_request(
664 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
665 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
666 self.assertFalse(self.handler.get_called)
667
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000668class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
669 """ Test url parsing """
670 def setUp(self):
671 self.translated = os.getcwd()
672 self.translated = os.path.join(self.translated, 'filename')
673 self.handler = SocketlessRequestHandler()
674
675 def test_query_arguments(self):
676 path = self.handler.translate_path('/filename')
677 self.assertEqual(path, self.translated)
678 path = self.handler.translate_path('/filename?foo=bar')
679 self.assertEqual(path, self.translated)
680 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
681 self.assertEqual(path, self.translated)
682
683 def test_start_with_double_slash(self):
684 path = self.handler.translate_path('//filename')
685 self.assertEqual(path, self.translated)
686 path = self.handler.translate_path('//filename?foo=bar')
687 self.assertEqual(path, self.translated)
688
689
Georg Brandlb533e262008-05-25 18:19:30 +0000690def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000691 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000692 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000693 support.run_unittest(
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000694 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000695 BaseHTTPServerTestCase,
696 SimpleHTTPServerTestCase,
697 CGIHTTPServerTestCase,
698 SimpleHTTPRequestHandlerTestCase,
699 )
Georg Brandlb533e262008-05-25 18:19:30 +0000700 finally:
701 os.chdir(cwd)
702
703if __name__ == '__main__':
704 test_main()