blob: 1bbaf0ece334f17aec076b43d6aa6ce6971e305a [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()
Nick Coghlan6ead5522009-10-18 13:19:33 +000065 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000066 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000067
68 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010069 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000070 self.connection.request(method, uri, body, headers)
71 return self.connection.getresponse()
72
73
74class BaseHTTPServerTestCase(BaseTestCase):
75 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
76 protocol_version = 'HTTP/1.1'
77 default_request_version = 'HTTP/1.1'
78
79 def do_TEST(self):
80 self.send_response(204)
81 self.send_header('Content-Type', 'text/html')
82 self.send_header('Connection', 'close')
83 self.end_headers()
84
85 def do_KEEP(self):
86 self.send_response(204)
87 self.send_header('Content-Type', 'text/html')
88 self.send_header('Connection', 'keep-alive')
89 self.end_headers()
90
91 def do_KEYERROR(self):
92 self.send_error(999)
93
94 def do_CUSTOM(self):
95 self.send_response(999)
96 self.send_header('Content-Type', 'text/html')
97 self.send_header('Connection', 'close')
98 self.end_headers()
99
Armin Ronacher8d96d772011-01-22 13:13:05 +0000100 def do_LATINONEHEADER(self):
101 self.send_response(999)
102 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000103 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000104 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000105 body = self.headers['x-special-incoming'].encode('utf-8')
106 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000107
Georg Brandlb533e262008-05-25 18:19:30 +0000108 def setUp(self):
109 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100110 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000111 self.con.connect()
112
113 def test_command(self):
114 self.con.request('GET', '/')
115 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000116 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000117
118 def test_request_line_trimming(self):
119 self.con._http_vsn_str = 'HTTP/1.1\n'
120 self.con.putrequest('GET', '/')
121 self.con.endheaders()
122 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000123 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000124
125 def test_version_bogus(self):
126 self.con._http_vsn_str = 'FUBAR'
127 self.con.putrequest('GET', '/')
128 self.con.endheaders()
129 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000130 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000131
132 def test_version_digits(self):
133 self.con._http_vsn_str = 'HTTP/9.9.9'
134 self.con.putrequest('GET', '/')
135 self.con.endheaders()
136 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000137 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000138
139 def test_version_none_get(self):
140 self.con._http_vsn_str = ''
141 self.con.putrequest('GET', '/')
142 self.con.endheaders()
143 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000144 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000145
146 def test_version_none(self):
147 self.con._http_vsn_str = ''
148 self.con.putrequest('PUT', '/')
149 self.con.endheaders()
150 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000151 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000152
153 def test_version_invalid(self):
154 self.con._http_vsn = 99
155 self.con._http_vsn_str = 'HTTP/9.9'
156 self.con.putrequest('GET', '/')
157 self.con.endheaders()
158 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000159 self.assertEqual(res.status, 505)
Georg Brandlb533e262008-05-25 18:19:30 +0000160
161 def test_send_blank(self):
162 self.con._http_vsn_str = ''
163 self.con.putrequest('', '')
164 self.con.endheaders()
165 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000166 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000167
168 def test_header_close(self):
169 self.con.putrequest('GET', '/')
170 self.con.putheader('Connection', 'close')
171 self.con.endheaders()
172 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000173 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000174
175 def test_head_keep_alive(self):
176 self.con._http_vsn_str = 'HTTP/1.1'
177 self.con.putrequest('GET', '/')
178 self.con.putheader('Connection', 'keep-alive')
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_handler(self):
184 self.con.request('TEST', '/')
185 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000186 self.assertEqual(res.status, 204)
Georg Brandlb533e262008-05-25 18:19:30 +0000187
188 def test_return_header_keep_alive(self):
189 self.con.request('KEEP', '/')
190 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000191 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000192 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000193 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000194
195 def test_internal_key_error(self):
196 self.con.request('KEYERROR', '/')
197 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000198 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000199
200 def test_return_custom_status(self):
201 self.con.request('CUSTOM', '/')
202 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000203 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000204
Armin Ronacher8d96d772011-01-22 13:13:05 +0000205 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000206 self.con.request('LATINONEHEADER', '/', headers={
207 'X-Special-Incoming': 'Ärger mit Unicode'
208 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000209 res = self.con.getresponse()
210 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000211 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000212
Georg Brandlb533e262008-05-25 18:19:30 +0000213
214class SimpleHTTPServerTestCase(BaseTestCase):
215 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
216 pass
217
218 def setUp(self):
219 BaseTestCase.setUp(self)
220 self.cwd = os.getcwd()
221 basetempdir = tempfile.gettempdir()
222 os.chdir(basetempdir)
223 self.data = b'We are the knights who say Ni!'
224 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
225 self.tempdir_name = os.path.basename(self.tempdir)
Brett Cannon105df5d2010-10-29 23:43:42 +0000226 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
227 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000228
229 def tearDown(self):
230 try:
231 os.chdir(self.cwd)
232 try:
233 shutil.rmtree(self.tempdir)
234 except:
235 pass
236 finally:
237 BaseTestCase.tearDown(self)
238
239 def check_status_and_reason(self, response, status, data=None):
240 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000241 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000242 self.assertEqual(response.status, status)
243 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000244 if data:
245 self.assertEqual(data, body)
246
247 def test_get(self):
248 #constructs the path relative to the root directory of the HTTPServer
249 response = self.request(self.tempdir_name + '/test')
250 self.check_status_and_reason(response, 200, data=self.data)
251 response = self.request(self.tempdir_name + '/')
252 self.check_status_and_reason(response, 200)
253 response = self.request(self.tempdir_name)
254 self.check_status_and_reason(response, 301)
255 response = self.request('/ThisDoesNotExist')
256 self.check_status_and_reason(response, 404)
257 response = self.request('/' + 'ThisDoesNotExist' + '/')
258 self.check_status_and_reason(response, 404)
Brett Cannon105df5d2010-10-29 23:43:42 +0000259 with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as f:
260 response = self.request('/' + self.tempdir_name + '/')
261 self.check_status_and_reason(response, 200)
262 if os.name == 'posix':
263 # chmod won't work as expected on Windows platforms
264 os.chmod(self.tempdir, 0)
265 response = self.request(self.tempdir_name + '/')
266 self.check_status_and_reason(response, 404)
267 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000268
269 def test_head(self):
270 response = self.request(
271 self.tempdir_name + '/test', method='HEAD')
272 self.check_status_and_reason(response, 200)
273 self.assertEqual(response.getheader('content-length'),
274 str(len(self.data)))
275 self.assertEqual(response.getheader('content-type'),
276 'application/octet-stream')
277
278 def test_invalid_requests(self):
279 response = self.request('/', method='FOO')
280 self.check_status_and_reason(response, 501)
281 # requests must be case sensitive,so this should fail too
282 response = self.request('/', method='get')
283 self.check_status_and_reason(response, 501)
284 response = self.request('/', method='GETs')
285 self.check_status_and_reason(response, 501)
286
287
288cgi_file1 = """\
289#!%s
290
291print("Content-type: text/html")
292print()
293print("Hello World")
294"""
295
296cgi_file2 = """\
297#!%s
298import cgi
299
300print("Content-type: text/html")
301print()
302
303form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000304print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
305 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000306"""
307
308class CGIHTTPServerTestCase(BaseTestCase):
309 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
310 pass
311
312 def setUp(self):
313 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000314 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000315 self.parent_dir = tempfile.mkdtemp()
316 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
317 os.mkdir(self.cgi_dir)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000318 self.file1_path = None
319 self.file2_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000320
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000321 # The shebang line should be pure ASCII: use symlink if possible.
322 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000323 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000324 self.pythonexe = os.path.join(self.parent_dir, 'python')
325 os.symlink(sys.executable, self.pythonexe)
326 else:
327 self.pythonexe = sys.executable
328
Victor Stinner3218c312010-10-17 20:13:36 +0000329 try:
330 # The python executable path is written as the first line of the
331 # CGI Python script. The encoding cookie cannot be used, and so the
332 # path should be encodable to the default script encoding (utf-8)
333 self.pythonexe.encode('utf-8')
334 except UnicodeEncodeError:
335 self.tearDown()
336 raise self.skipTest(
337 "Python executable path is not encodable to utf-8")
338
Georg Brandlb533e262008-05-25 18:19:30 +0000339 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000340 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000341 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000342 os.chmod(self.file1_path, 0o777)
343
344 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000345 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000346 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000347 os.chmod(self.file2_path, 0o777)
348
Georg Brandlb533e262008-05-25 18:19:30 +0000349 os.chdir(self.parent_dir)
350
351 def tearDown(self):
352 try:
353 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000354 if self.pythonexe != sys.executable:
355 os.remove(self.pythonexe)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000356 if self.file1_path:
357 os.remove(self.file1_path)
358 if self.file2_path:
359 os.remove(self.file2_path)
Georg Brandlb533e262008-05-25 18:19:30 +0000360 os.rmdir(self.cgi_dir)
361 os.rmdir(self.parent_dir)
362 finally:
363 BaseTestCase.tearDown(self)
364
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000365 def test_url_collapse_path_split(self):
366 test_vectors = {
367 '': ('/', ''),
368 '..': IndexError,
369 '/.//..': IndexError,
370 '/': ('/', ''),
371 '//': ('/', ''),
372 '/\\': ('/', '\\'),
373 '/.//': ('/', ''),
374 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
375 '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
376 'a': ('/', 'a'),
377 '/a': ('/', 'a'),
378 '//a': ('/', 'a'),
379 './a': ('/', 'a'),
380 './C:/': ('/C:', ''),
381 '/a/b': ('/a', 'b'),
382 '/a/b/': ('/a/b', ''),
383 '/a/b/c/..': ('/a/b', ''),
384 '/a/b/c/../d': ('/a/b', 'd'),
385 '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
386 '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
387 '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
388 '../a/b/c/../d/e/.././././..//f': IndexError,
389 '/a/b/c/../d/e/../../../f': ('/a', 'f'),
390 '/a/b/c/../d/e/../../../../f': ('/', 'f'),
391 '/a/b/c/../d/e/../../../../../f': IndexError,
392 '/a/b/c/../d/e/../../../../f/..': ('/', ''),
393 }
394 for path, expected in test_vectors.items():
395 if isinstance(expected, type) and issubclass(expected, Exception):
396 self.assertRaises(expected,
397 server._url_collapse_path_split, path)
398 else:
399 actual = server._url_collapse_path_split(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000400 self.assertEqual(expected, actual,
401 msg='path = %r\nGot: %r\nWanted: %r' %
402 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000403
Georg Brandlb533e262008-05-25 18:19:30 +0000404 def test_headers_and_content(self):
405 res = self.request('/cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000406 self.assertEqual((b'Hello World\n', 'text/html', 200),
407 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000408
409 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000410 params = urllib.parse.urlencode(
411 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000412 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
413 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
414
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000415 self.assertEqual(res.read(), b'1, python, 123456\n')
Georg Brandlb533e262008-05-25 18:19:30 +0000416
417 def test_invaliduri(self):
418 res = self.request('/cgi-bin/invalid')
419 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000420 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000421
422 def test_authorization(self):
423 headers = {b'Authorization' : b'Basic ' +
424 base64.b64encode(b'username:pass')}
425 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000426 self.assertEqual((b'Hello World\n', 'text/html', 200),
427 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000428
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000429 def test_no_leading_slash(self):
430 # http://bugs.python.org/issue2254
431 res = self.request('cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000432 self.assertEqual((b'Hello World\n', 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000433 (res.read(), res.getheader('Content-type'), res.status))
434
Senthil Kumaran42713722010-10-03 17:55:45 +0000435 def test_os_environ_is_not_altered(self):
436 signature = "Test CGI Server"
437 os.environ['SERVER_SOFTWARE'] = signature
438 res = self.request('/cgi-bin/file1.py')
439 self.assertEqual((b'Hello World\n', 'text/html', 200),
440 (res.read(), res.getheader('Content-type'), res.status))
441 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
442
Georg Brandlb533e262008-05-25 18:19:30 +0000443
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000444class SocketlessRequestHandler(SimpleHTTPRequestHandler):
445 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000446 self.get_called = False
447 self.protocol_version = "HTTP/1.1"
448
449 def do_GET(self):
450 self.get_called = True
451 self.send_response(200)
452 self.send_header('Content-Type', 'text/html')
453 self.end_headers()
454 self.wfile.write(b'<html><body>Data</body></html>\r\n')
455
456 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000457 pass
458
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000459class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
460 def handle_expect_100(self):
461 self.send_error(417)
462 return False
463
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800464
465class AuditableBytesIO:
466
467 def __init__(self):
468 self.datas = []
469
470 def write(self, data):
471 self.datas.append(data)
472
473 def getData(self):
474 return b''.join(self.datas)
475
476 @property
477 def numWrites(self):
478 return len(self.datas)
479
480
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000481class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200482 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000483
484 Test the support for the Expect 100-continue header.
485 """
486
487 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
488
489 def setUp (self):
490 self.handler = SocketlessRequestHandler()
491
492 def send_typical_request(self, message):
493 input = BytesIO(message)
494 output = BytesIO()
495 self.handler.rfile = input
496 self.handler.wfile = output
497 self.handler.handle_one_request()
498 output.seek(0)
499 return output.readlines()
500
501 def verify_get_called(self):
502 self.assertTrue(self.handler.get_called)
503
504 def verify_expected_headers(self, headers):
505 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
506 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
507
508 def verify_http_server_response(self, response):
509 match = self.HTTPResponseMatch.search(response)
510 self.assertTrue(match is not None)
511
512 def test_http_1_1(self):
513 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
514 self.verify_http_server_response(result[0])
515 self.verify_expected_headers(result[1:-1])
516 self.verify_get_called()
517 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
518
519 def test_http_1_0(self):
520 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
521 self.verify_http_server_response(result[0])
522 self.verify_expected_headers(result[1:-1])
523 self.verify_get_called()
524 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
525
526 def test_http_0_9(self):
527 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
528 self.assertEqual(len(result), 1)
529 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
530 self.verify_get_called()
531
532 def test_with_continue_1_0(self):
533 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
534 self.verify_http_server_response(result[0])
535 self.verify_expected_headers(result[1:-1])
536 self.verify_get_called()
537 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
538
539 def test_with_continue_1_1(self):
540 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
541 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
542 self.assertEqual(result[1], b'HTTP/1.1 200 OK\r\n')
543 self.verify_expected_headers(result[2:-1])
544 self.verify_get_called()
545 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
546
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800547 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000548
549 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800550 output = AuditableBytesIO()
551 handler = SocketlessRequestHandler()
552 handler.rfile = input
553 handler.wfile = output
554 handler.request_version = 'HTTP/1.1'
555 handler.requestline = ''
556 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000557
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800558 handler.send_error(418)
559 self.assertEqual(output.numWrites, 2)
560
561 def test_header_buffering_of_send_response_only(self):
562
563 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
564 output = AuditableBytesIO()
565 handler = SocketlessRequestHandler()
566 handler.rfile = input
567 handler.wfile = output
568 handler.request_version = 'HTTP/1.1'
569
570 handler.send_response_only(418)
571 self.assertEqual(output.numWrites, 0)
572 handler.end_headers()
573 self.assertEqual(output.numWrites, 1)
574
575 def test_header_buffering_of_send_header(self):
576
577 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
578 output = AuditableBytesIO()
579 handler = SocketlessRequestHandler()
580 handler.rfile = input
581 handler.wfile = output
582 handler.request_version = 'HTTP/1.1'
583
584 handler.send_header('Foo', 'foo')
585 handler.send_header('bar', 'bar')
586 self.assertEqual(output.numWrites, 0)
587 handler.end_headers()
588 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
589 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000590
591 def test_header_unbuffered_when_continue(self):
592
593 def _readAndReseek(f):
594 pos = f.tell()
595 f.seek(0)
596 data = f.read()
597 f.seek(pos)
598 return data
599
600 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
601 output = BytesIO()
602 self.handler.rfile = input
603 self.handler.wfile = output
604 self.handler.request_version = 'HTTP/1.1'
605
606 self.handler.handle_one_request()
607 self.assertNotEqual(_readAndReseek(output), b'')
608 result = _readAndReseek(output).split(b'\r\n')
609 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
610 self.assertEqual(result[1], b'HTTP/1.1 200 OK')
611
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000612 def test_with_continue_rejected(self):
613 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
614 self.handler = RejectingSocketlessRequestHandler()
615 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
616 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
617 self.verify_expected_headers(result[1:-1])
618 # The expect handler should short circuit the usual get method by
619 # returning false here, so get_called should be false
620 self.assertFalse(self.handler.get_called)
621 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
622 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
623
Antoine Pitrouc4924372010-12-16 16:48:36 +0000624 def test_request_length(self):
625 # Issue #10714: huge request lines are discarded, to avoid Denial
626 # of Service attacks.
627 result = self.send_typical_request(b'GET ' + b'x' * 65537)
628 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
629 self.assertFalse(self.handler.get_called)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000630
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000631 def test_header_length(self):
632 # Issue #6791: same for headers
633 result = self.send_typical_request(
634 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
635 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
636 self.assertFalse(self.handler.get_called)
637
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000638class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
639 """ Test url parsing """
640 def setUp(self):
641 self.translated = os.getcwd()
642 self.translated = os.path.join(self.translated, 'filename')
643 self.handler = SocketlessRequestHandler()
644
645 def test_query_arguments(self):
646 path = self.handler.translate_path('/filename')
647 self.assertEqual(path, self.translated)
648 path = self.handler.translate_path('/filename?foo=bar')
649 self.assertEqual(path, self.translated)
650 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
651 self.assertEqual(path, self.translated)
652
653 def test_start_with_double_slash(self):
654 path = self.handler.translate_path('//filename')
655 self.assertEqual(path, self.translated)
656 path = self.handler.translate_path('//filename?foo=bar')
657 self.assertEqual(path, self.translated)
658
659
Georg Brandlb533e262008-05-25 18:19:30 +0000660def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000661 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000662 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000663 support.run_unittest(
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000664 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000665 BaseHTTPServerTestCase,
666 SimpleHTTPServerTestCase,
667 CGIHTTPServerTestCase,
668 SimpleHTTPRequestHandlerTestCase,
669 )
Georg Brandlb533e262008-05-25 18:19:30 +0000670 finally:
671 os.chdir(cwd)
672
673if __name__ == '__main__':
674 test_main()