blob: 2cc94a9acbbb331f01270cf474651bb93af8cd74 [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):
41 self.server = HTTPServer(('', 0), self.request_handler)
42 self.test_object.PORT = self.server.socket.getsockname()[1]
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={}):
Georg Brandl24420152008-05-26 16:32:26 +000069 self.connection = http.client.HTTPConnection('localhost', 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')
103 self.end_headers()
104
Georg Brandlb533e262008-05-25 18:19:30 +0000105 def setUp(self):
106 BaseTestCase.setUp(self)
Georg Brandl24420152008-05-26 16:32:26 +0000107 self.con = http.client.HTTPConnection('localhost', self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000108 self.con.connect()
109
110 def test_command(self):
111 self.con.request('GET', '/')
112 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000113 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000114
115 def test_request_line_trimming(self):
116 self.con._http_vsn_str = 'HTTP/1.1\n'
117 self.con.putrequest('GET', '/')
118 self.con.endheaders()
119 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000120 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000121
122 def test_version_bogus(self):
123 self.con._http_vsn_str = 'FUBAR'
124 self.con.putrequest('GET', '/')
125 self.con.endheaders()
126 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000127 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000128
129 def test_version_digits(self):
130 self.con._http_vsn_str = 'HTTP/9.9.9'
131 self.con.putrequest('GET', '/')
132 self.con.endheaders()
133 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000134 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000135
136 def test_version_none_get(self):
137 self.con._http_vsn_str = ''
138 self.con.putrequest('GET', '/')
139 self.con.endheaders()
140 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000141 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000142
143 def test_version_none(self):
144 self.con._http_vsn_str = ''
145 self.con.putrequest('PUT', '/')
146 self.con.endheaders()
147 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000148 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000149
150 def test_version_invalid(self):
151 self.con._http_vsn = 99
152 self.con._http_vsn_str = 'HTTP/9.9'
153 self.con.putrequest('GET', '/')
154 self.con.endheaders()
155 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000156 self.assertEqual(res.status, 505)
Georg Brandlb533e262008-05-25 18:19:30 +0000157
158 def test_send_blank(self):
159 self.con._http_vsn_str = ''
160 self.con.putrequest('', '')
161 self.con.endheaders()
162 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000163 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000164
165 def test_header_close(self):
166 self.con.putrequest('GET', '/')
167 self.con.putheader('Connection', 'close')
168 self.con.endheaders()
169 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000170 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000171
172 def test_head_keep_alive(self):
173 self.con._http_vsn_str = 'HTTP/1.1'
174 self.con.putrequest('GET', '/')
175 self.con.putheader('Connection', 'keep-alive')
176 self.con.endheaders()
177 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000178 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000179
180 def test_handler(self):
181 self.con.request('TEST', '/')
182 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000183 self.assertEqual(res.status, 204)
Georg Brandlb533e262008-05-25 18:19:30 +0000184
185 def test_return_header_keep_alive(self):
186 self.con.request('KEEP', '/')
187 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000188 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000189 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000190 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000191
192 def test_internal_key_error(self):
193 self.con.request('KEYERROR', '/')
194 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000195 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000196
197 def test_return_custom_status(self):
198 self.con.request('CUSTOM', '/')
199 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000200 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000201
Armin Ronacher8d96d772011-01-22 13:13:05 +0000202 def test_latin1_header(self):
203 self.con.request('LATINONEHEADER', '/')
204 res = self.con.getresponse()
205 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
206
Georg Brandlb533e262008-05-25 18:19:30 +0000207
208class SimpleHTTPServerTestCase(BaseTestCase):
209 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
210 pass
211
212 def setUp(self):
213 BaseTestCase.setUp(self)
214 self.cwd = os.getcwd()
215 basetempdir = tempfile.gettempdir()
216 os.chdir(basetempdir)
217 self.data = b'We are the knights who say Ni!'
218 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
219 self.tempdir_name = os.path.basename(self.tempdir)
Brett Cannon105df5d2010-10-29 23:43:42 +0000220 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
221 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000222
223 def tearDown(self):
224 try:
225 os.chdir(self.cwd)
226 try:
227 shutil.rmtree(self.tempdir)
228 except:
229 pass
230 finally:
231 BaseTestCase.tearDown(self)
232
233 def check_status_and_reason(self, response, status, data=None):
234 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000235 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000236 self.assertEqual(response.status, status)
237 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000238 if data:
239 self.assertEqual(data, body)
240
241 def test_get(self):
242 #constructs the path relative to the root directory of the HTTPServer
243 response = self.request(self.tempdir_name + '/test')
244 self.check_status_and_reason(response, 200, data=self.data)
245 response = self.request(self.tempdir_name + '/')
246 self.check_status_and_reason(response, 200)
247 response = self.request(self.tempdir_name)
248 self.check_status_and_reason(response, 301)
249 response = self.request('/ThisDoesNotExist')
250 self.check_status_and_reason(response, 404)
251 response = self.request('/' + 'ThisDoesNotExist' + '/')
252 self.check_status_and_reason(response, 404)
Brett Cannon105df5d2010-10-29 23:43:42 +0000253 with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as f:
254 response = self.request('/' + self.tempdir_name + '/')
255 self.check_status_and_reason(response, 200)
256 if os.name == 'posix':
257 # chmod won't work as expected on Windows platforms
258 os.chmod(self.tempdir, 0)
259 response = self.request(self.tempdir_name + '/')
260 self.check_status_and_reason(response, 404)
261 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000262
263 def test_head(self):
264 response = self.request(
265 self.tempdir_name + '/test', method='HEAD')
266 self.check_status_and_reason(response, 200)
267 self.assertEqual(response.getheader('content-length'),
268 str(len(self.data)))
269 self.assertEqual(response.getheader('content-type'),
270 'application/octet-stream')
271
272 def test_invalid_requests(self):
273 response = self.request('/', method='FOO')
274 self.check_status_and_reason(response, 501)
275 # requests must be case sensitive,so this should fail too
276 response = self.request('/', method='get')
277 self.check_status_and_reason(response, 501)
278 response = self.request('/', method='GETs')
279 self.check_status_and_reason(response, 501)
280
281
282cgi_file1 = """\
283#!%s
284
285print("Content-type: text/html")
286print()
287print("Hello World")
288"""
289
290cgi_file2 = """\
291#!%s
292import cgi
293
294print("Content-type: text/html")
295print()
296
297form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000298print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
299 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000300"""
301
302class CGIHTTPServerTestCase(BaseTestCase):
303 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
304 pass
305
306 def setUp(self):
307 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000308 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000309 self.parent_dir = tempfile.mkdtemp()
310 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
311 os.mkdir(self.cgi_dir)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000312 self.file1_path = None
313 self.file2_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000314
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000315 # The shebang line should be pure ASCII: use symlink if possible.
316 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000317 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000318 self.pythonexe = os.path.join(self.parent_dir, 'python')
319 os.symlink(sys.executable, self.pythonexe)
320 else:
321 self.pythonexe = sys.executable
322
Victor Stinner3218c312010-10-17 20:13:36 +0000323 try:
324 # The python executable path is written as the first line of the
325 # CGI Python script. The encoding cookie cannot be used, and so the
326 # path should be encodable to the default script encoding (utf-8)
327 self.pythonexe.encode('utf-8')
328 except UnicodeEncodeError:
329 self.tearDown()
330 raise self.skipTest(
331 "Python executable path is not encodable to utf-8")
332
Georg Brandlb533e262008-05-25 18:19:30 +0000333 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000334 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000335 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000336 os.chmod(self.file1_path, 0o777)
337
338 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000339 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000340 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000341 os.chmod(self.file2_path, 0o777)
342
Georg Brandlb533e262008-05-25 18:19:30 +0000343 os.chdir(self.parent_dir)
344
345 def tearDown(self):
346 try:
347 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000348 if self.pythonexe != sys.executable:
349 os.remove(self.pythonexe)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000350 if self.file1_path:
351 os.remove(self.file1_path)
352 if self.file2_path:
353 os.remove(self.file2_path)
Georg Brandlb533e262008-05-25 18:19:30 +0000354 os.rmdir(self.cgi_dir)
355 os.rmdir(self.parent_dir)
356 finally:
357 BaseTestCase.tearDown(self)
358
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000359 def test_url_collapse_path_split(self):
360 test_vectors = {
361 '': ('/', ''),
362 '..': IndexError,
363 '/.//..': IndexError,
364 '/': ('/', ''),
365 '//': ('/', ''),
366 '/\\': ('/', '\\'),
367 '/.//': ('/', ''),
368 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
369 '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
370 'a': ('/', 'a'),
371 '/a': ('/', 'a'),
372 '//a': ('/', 'a'),
373 './a': ('/', 'a'),
374 './C:/': ('/C:', ''),
375 '/a/b': ('/a', 'b'),
376 '/a/b/': ('/a/b', ''),
377 '/a/b/c/..': ('/a/b', ''),
378 '/a/b/c/../d': ('/a/b', 'd'),
379 '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
380 '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
381 '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
382 '../a/b/c/../d/e/.././././..//f': IndexError,
383 '/a/b/c/../d/e/../../../f': ('/a', 'f'),
384 '/a/b/c/../d/e/../../../../f': ('/', 'f'),
385 '/a/b/c/../d/e/../../../../../f': IndexError,
386 '/a/b/c/../d/e/../../../../f/..': ('/', ''),
387 }
388 for path, expected in test_vectors.items():
389 if isinstance(expected, type) and issubclass(expected, Exception):
390 self.assertRaises(expected,
391 server._url_collapse_path_split, path)
392 else:
393 actual = server._url_collapse_path_split(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000394 self.assertEqual(expected, actual,
395 msg='path = %r\nGot: %r\nWanted: %r' %
396 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000397
Georg Brandlb533e262008-05-25 18:19:30 +0000398 def test_headers_and_content(self):
399 res = self.request('/cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000400 self.assertEqual((b'Hello World\n', 'text/html', 200),
401 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000402
403 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000404 params = urllib.parse.urlencode(
405 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000406 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
407 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
408
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000409 self.assertEqual(res.read(), b'1, python, 123456\n')
Georg Brandlb533e262008-05-25 18:19:30 +0000410
411 def test_invaliduri(self):
412 res = self.request('/cgi-bin/invalid')
413 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000414 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000415
416 def test_authorization(self):
417 headers = {b'Authorization' : b'Basic ' +
418 base64.b64encode(b'username:pass')}
419 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000420 self.assertEqual((b'Hello World\n', 'text/html', 200),
421 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000422
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000423 def test_no_leading_slash(self):
424 # http://bugs.python.org/issue2254
425 res = self.request('cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000426 self.assertEqual((b'Hello World\n', 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000427 (res.read(), res.getheader('Content-type'), res.status))
428
Senthil Kumaran42713722010-10-03 17:55:45 +0000429 def test_os_environ_is_not_altered(self):
430 signature = "Test CGI Server"
431 os.environ['SERVER_SOFTWARE'] = signature
432 res = self.request('/cgi-bin/file1.py')
433 self.assertEqual((b'Hello World\n', 'text/html', 200),
434 (res.read(), res.getheader('Content-type'), res.status))
435 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
436
Georg Brandlb533e262008-05-25 18:19:30 +0000437
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000438class SocketlessRequestHandler(SimpleHTTPRequestHandler):
439 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000440 self.get_called = False
441 self.protocol_version = "HTTP/1.1"
442
443 def do_GET(self):
444 self.get_called = True
445 self.send_response(200)
446 self.send_header('Content-Type', 'text/html')
447 self.end_headers()
448 self.wfile.write(b'<html><body>Data</body></html>\r\n')
449
450 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000451 pass
452
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000453class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
454 def handle_expect_100(self):
455 self.send_error(417)
456 return False
457
458class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
459 """Test the functionaility of the BaseHTTPServer.
460
461 Test the support for the Expect 100-continue header.
462 """
463
464 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
465
466 def setUp (self):
467 self.handler = SocketlessRequestHandler()
468
469 def send_typical_request(self, message):
470 input = BytesIO(message)
471 output = BytesIO()
472 self.handler.rfile = input
473 self.handler.wfile = output
474 self.handler.handle_one_request()
475 output.seek(0)
476 return output.readlines()
477
478 def verify_get_called(self):
479 self.assertTrue(self.handler.get_called)
480
481 def verify_expected_headers(self, headers):
482 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
483 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
484
485 def verify_http_server_response(self, response):
486 match = self.HTTPResponseMatch.search(response)
487 self.assertTrue(match is not None)
488
489 def test_http_1_1(self):
490 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
491 self.verify_http_server_response(result[0])
492 self.verify_expected_headers(result[1:-1])
493 self.verify_get_called()
494 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
495
496 def test_http_1_0(self):
497 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
498 self.verify_http_server_response(result[0])
499 self.verify_expected_headers(result[1:-1])
500 self.verify_get_called()
501 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
502
503 def test_http_0_9(self):
504 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
505 self.assertEqual(len(result), 1)
506 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
507 self.verify_get_called()
508
509 def test_with_continue_1_0(self):
510 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
511 self.verify_http_server_response(result[0])
512 self.verify_expected_headers(result[1:-1])
513 self.verify_get_called()
514 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
515
516 def test_with_continue_1_1(self):
517 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
518 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
519 self.assertEqual(result[1], b'HTTP/1.1 200 OK\r\n')
520 self.verify_expected_headers(result[2:-1])
521 self.verify_get_called()
522 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
523
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000524 def test_header_buffering(self):
525
526 def _readAndReseek(f):
527 pos = f.tell()
528 f.seek(0)
529 data = f.read()
530 f.seek(pos)
531 return data
532
533 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
534 output = BytesIO()
535 self.handler.rfile = input
536 self.handler.wfile = output
537 self.handler.request_version = 'HTTP/1.1'
538
539 self.handler.send_header('Foo', 'foo')
540 self.handler.send_header('bar', 'bar')
541 self.assertEqual(_readAndReseek(output), b'')
542 self.handler.end_headers()
543 self.assertEqual(_readAndReseek(output),
544 b'Foo: foo\r\nbar: bar\r\n\r\n')
545
546 def test_header_unbuffered_when_continue(self):
547
548 def _readAndReseek(f):
549 pos = f.tell()
550 f.seek(0)
551 data = f.read()
552 f.seek(pos)
553 return data
554
555 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
556 output = BytesIO()
557 self.handler.rfile = input
558 self.handler.wfile = output
559 self.handler.request_version = 'HTTP/1.1'
560
561 self.handler.handle_one_request()
562 self.assertNotEqual(_readAndReseek(output), b'')
563 result = _readAndReseek(output).split(b'\r\n')
564 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
565 self.assertEqual(result[1], b'HTTP/1.1 200 OK')
566
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000567 def test_with_continue_rejected(self):
568 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
569 self.handler = RejectingSocketlessRequestHandler()
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 417 Expectation Failed\r\n')
572 self.verify_expected_headers(result[1:-1])
573 # The expect handler should short circuit the usual get method by
574 # returning false here, so get_called should be false
575 self.assertFalse(self.handler.get_called)
576 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
577 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
578
Antoine Pitrouc4924372010-12-16 16:48:36 +0000579 def test_request_length(self):
580 # Issue #10714: huge request lines are discarded, to avoid Denial
581 # of Service attacks.
582 result = self.send_typical_request(b'GET ' + b'x' * 65537)
583 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
584 self.assertFalse(self.handler.get_called)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000585
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000586 def test_header_length(self):
587 # Issue #6791: same for headers
588 result = self.send_typical_request(
589 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
590 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
591 self.assertFalse(self.handler.get_called)
592
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000593class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
594 """ Test url parsing """
595 def setUp(self):
596 self.translated = os.getcwd()
597 self.translated = os.path.join(self.translated, 'filename')
598 self.handler = SocketlessRequestHandler()
599
600 def test_query_arguments(self):
601 path = self.handler.translate_path('/filename')
602 self.assertEqual(path, self.translated)
603 path = self.handler.translate_path('/filename?foo=bar')
604 self.assertEqual(path, self.translated)
605 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
606 self.assertEqual(path, self.translated)
607
608 def test_start_with_double_slash(self):
609 path = self.handler.translate_path('//filename')
610 self.assertEqual(path, self.translated)
611 path = self.handler.translate_path('//filename?foo=bar')
612 self.assertEqual(path, self.translated)
613
614
Georg Brandlb533e262008-05-25 18:19:30 +0000615def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000616 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000617 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000618 support.run_unittest(
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000619 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000620 BaseHTTPServerTestCase,
621 SimpleHTTPServerTestCase,
622 CGIHTTPServerTestCase,
623 SimpleHTTPRequestHandlerTestCase,
624 )
Georg Brandlb533e262008-05-25 18:19:30 +0000625 finally:
626 os.chdir(cwd)
627
628if __name__ == '__main__':
629 test_main()