blob: cc15dd680d8ffeb61b150e9eb0a3857c9050547d [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)
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100262 # chmod() doesn't work as expected on Windows, and filesystem
263 # permissions are ignored by root on Unix.
264 if os.name == 'posix' and os.geteuid() != 0:
Brett Cannon105df5d2010-10-29 23:43:42 +0000265 os.chmod(self.tempdir, 0)
266 response = self.request(self.tempdir_name + '/')
267 self.check_status_and_reason(response, 404)
268 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000269
270 def test_head(self):
271 response = self.request(
272 self.tempdir_name + '/test', method='HEAD')
273 self.check_status_and_reason(response, 200)
274 self.assertEqual(response.getheader('content-length'),
275 str(len(self.data)))
276 self.assertEqual(response.getheader('content-type'),
277 'application/octet-stream')
278
279 def test_invalid_requests(self):
280 response = self.request('/', method='FOO')
281 self.check_status_and_reason(response, 501)
282 # requests must be case sensitive,so this should fail too
283 response = self.request('/', method='get')
284 self.check_status_and_reason(response, 501)
285 response = self.request('/', method='GETs')
286 self.check_status_and_reason(response, 501)
287
288
289cgi_file1 = """\
290#!%s
291
292print("Content-type: text/html")
293print()
294print("Hello World")
295"""
296
297cgi_file2 = """\
298#!%s
299import cgi
300
301print("Content-type: text/html")
302print()
303
304form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000305print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
306 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000307"""
308
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100309
310@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
311 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000312class CGIHTTPServerTestCase(BaseTestCase):
313 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
314 pass
315
316 def setUp(self):
317 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000318 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000319 self.parent_dir = tempfile.mkdtemp()
320 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
321 os.mkdir(self.cgi_dir)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000322 self.file1_path = None
323 self.file2_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000324
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000325 # The shebang line should be pure ASCII: use symlink if possible.
326 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000327 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000328 self.pythonexe = os.path.join(self.parent_dir, 'python')
329 os.symlink(sys.executable, self.pythonexe)
330 else:
331 self.pythonexe = sys.executable
332
Victor Stinner3218c312010-10-17 20:13:36 +0000333 try:
334 # The python executable path is written as the first line of the
335 # CGI Python script. The encoding cookie cannot be used, and so the
336 # path should be encodable to the default script encoding (utf-8)
337 self.pythonexe.encode('utf-8')
338 except UnicodeEncodeError:
339 self.tearDown()
340 raise self.skipTest(
341 "Python executable path is not encodable to utf-8")
342
Georg Brandlb533e262008-05-25 18:19:30 +0000343 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000344 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000345 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000346 os.chmod(self.file1_path, 0o777)
347
348 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000349 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000350 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000351 os.chmod(self.file2_path, 0o777)
352
Georg Brandlb533e262008-05-25 18:19:30 +0000353 os.chdir(self.parent_dir)
354
355 def tearDown(self):
356 try:
357 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000358 if self.pythonexe != sys.executable:
359 os.remove(self.pythonexe)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000360 if self.file1_path:
361 os.remove(self.file1_path)
362 if self.file2_path:
363 os.remove(self.file2_path)
Georg Brandlb533e262008-05-25 18:19:30 +0000364 os.rmdir(self.cgi_dir)
365 os.rmdir(self.parent_dir)
366 finally:
367 BaseTestCase.tearDown(self)
368
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000369 def test_url_collapse_path_split(self):
370 test_vectors = {
371 '': ('/', ''),
372 '..': IndexError,
373 '/.//..': IndexError,
374 '/': ('/', ''),
375 '//': ('/', ''),
376 '/\\': ('/', '\\'),
377 '/.//': ('/', ''),
378 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
379 '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
380 'a': ('/', 'a'),
381 '/a': ('/', 'a'),
382 '//a': ('/', 'a'),
383 './a': ('/', 'a'),
384 './C:/': ('/C:', ''),
385 '/a/b': ('/a', 'b'),
386 '/a/b/': ('/a/b', ''),
387 '/a/b/c/..': ('/a/b', ''),
388 '/a/b/c/../d': ('/a/b', 'd'),
389 '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
390 '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
391 '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
392 '../a/b/c/../d/e/.././././..//f': IndexError,
393 '/a/b/c/../d/e/../../../f': ('/a', 'f'),
394 '/a/b/c/../d/e/../../../../f': ('/', 'f'),
395 '/a/b/c/../d/e/../../../../../f': IndexError,
396 '/a/b/c/../d/e/../../../../f/..': ('/', ''),
397 }
398 for path, expected in test_vectors.items():
399 if isinstance(expected, type) and issubclass(expected, Exception):
400 self.assertRaises(expected,
401 server._url_collapse_path_split, path)
402 else:
403 actual = server._url_collapse_path_split(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000404 self.assertEqual(expected, actual,
405 msg='path = %r\nGot: %r\nWanted: %r' %
406 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000407
Georg Brandlb533e262008-05-25 18:19:30 +0000408 def test_headers_and_content(self):
409 res = self.request('/cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000410 self.assertEqual((b'Hello World\n', 'text/html', 200),
411 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000412
413 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000414 params = urllib.parse.urlencode(
415 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000416 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
417 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
418
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000419 self.assertEqual(res.read(), b'1, python, 123456\n')
Georg Brandlb533e262008-05-25 18:19:30 +0000420
421 def test_invaliduri(self):
422 res = self.request('/cgi-bin/invalid')
423 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000424 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000425
426 def test_authorization(self):
427 headers = {b'Authorization' : b'Basic ' +
428 base64.b64encode(b'username:pass')}
429 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000430 self.assertEqual((b'Hello World\n', 'text/html', 200),
431 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000432
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000433 def test_no_leading_slash(self):
434 # http://bugs.python.org/issue2254
435 res = self.request('cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000436 self.assertEqual((b'Hello World\n', 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000437 (res.read(), res.getheader('Content-type'), res.status))
438
Senthil Kumaran42713722010-10-03 17:55:45 +0000439 def test_os_environ_is_not_altered(self):
440 signature = "Test CGI Server"
441 os.environ['SERVER_SOFTWARE'] = signature
442 res = self.request('/cgi-bin/file1.py')
443 self.assertEqual((b'Hello World\n', 'text/html', 200),
444 (res.read(), res.getheader('Content-type'), res.status))
445 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
446
Georg Brandlb533e262008-05-25 18:19:30 +0000447
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000448class SocketlessRequestHandler(SimpleHTTPRequestHandler):
449 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000450 self.get_called = False
451 self.protocol_version = "HTTP/1.1"
452
453 def do_GET(self):
454 self.get_called = True
455 self.send_response(200)
456 self.send_header('Content-Type', 'text/html')
457 self.end_headers()
458 self.wfile.write(b'<html><body>Data</body></html>\r\n')
459
460 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000461 pass
462
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000463class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
464 def handle_expect_100(self):
465 self.send_error(417)
466 return False
467
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800468
469class AuditableBytesIO:
470
471 def __init__(self):
472 self.datas = []
473
474 def write(self, data):
475 self.datas.append(data)
476
477 def getData(self):
478 return b''.join(self.datas)
479
480 @property
481 def numWrites(self):
482 return len(self.datas)
483
484
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000485class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200486 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000487
488 Test the support for the Expect 100-continue header.
489 """
490
491 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
492
493 def setUp (self):
494 self.handler = SocketlessRequestHandler()
495
496 def send_typical_request(self, message):
497 input = BytesIO(message)
498 output = BytesIO()
499 self.handler.rfile = input
500 self.handler.wfile = output
501 self.handler.handle_one_request()
502 output.seek(0)
503 return output.readlines()
504
505 def verify_get_called(self):
506 self.assertTrue(self.handler.get_called)
507
508 def verify_expected_headers(self, headers):
509 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
510 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
511
512 def verify_http_server_response(self, response):
513 match = self.HTTPResponseMatch.search(response)
514 self.assertTrue(match is not None)
515
516 def test_http_1_1(self):
517 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
518 self.verify_http_server_response(result[0])
519 self.verify_expected_headers(result[1:-1])
520 self.verify_get_called()
521 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
522
523 def test_http_1_0(self):
524 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
525 self.verify_http_server_response(result[0])
526 self.verify_expected_headers(result[1:-1])
527 self.verify_get_called()
528 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
529
530 def test_http_0_9(self):
531 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
532 self.assertEqual(len(result), 1)
533 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
534 self.verify_get_called()
535
536 def test_with_continue_1_0(self):
537 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
538 self.verify_http_server_response(result[0])
539 self.verify_expected_headers(result[1:-1])
540 self.verify_get_called()
541 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
542
543 def test_with_continue_1_1(self):
544 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
545 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
546 self.assertEqual(result[1], b'HTTP/1.1 200 OK\r\n')
547 self.verify_expected_headers(result[2:-1])
548 self.verify_get_called()
549 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
550
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800551 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000552
553 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800554 output = AuditableBytesIO()
555 handler = SocketlessRequestHandler()
556 handler.rfile = input
557 handler.wfile = output
558 handler.request_version = 'HTTP/1.1'
559 handler.requestline = ''
560 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000561
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800562 handler.send_error(418)
563 self.assertEqual(output.numWrites, 2)
564
565 def test_header_buffering_of_send_response_only(self):
566
567 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
568 output = AuditableBytesIO()
569 handler = SocketlessRequestHandler()
570 handler.rfile = input
571 handler.wfile = output
572 handler.request_version = 'HTTP/1.1'
573
574 handler.send_response_only(418)
575 self.assertEqual(output.numWrites, 0)
576 handler.end_headers()
577 self.assertEqual(output.numWrites, 1)
578
579 def test_header_buffering_of_send_header(self):
580
581 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
582 output = AuditableBytesIO()
583 handler = SocketlessRequestHandler()
584 handler.rfile = input
585 handler.wfile = output
586 handler.request_version = 'HTTP/1.1'
587
588 handler.send_header('Foo', 'foo')
589 handler.send_header('bar', 'bar')
590 self.assertEqual(output.numWrites, 0)
591 handler.end_headers()
592 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
593 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000594
595 def test_header_unbuffered_when_continue(self):
596
597 def _readAndReseek(f):
598 pos = f.tell()
599 f.seek(0)
600 data = f.read()
601 f.seek(pos)
602 return data
603
604 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
605 output = BytesIO()
606 self.handler.rfile = input
607 self.handler.wfile = output
608 self.handler.request_version = 'HTTP/1.1'
609
610 self.handler.handle_one_request()
611 self.assertNotEqual(_readAndReseek(output), b'')
612 result = _readAndReseek(output).split(b'\r\n')
613 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
614 self.assertEqual(result[1], b'HTTP/1.1 200 OK')
615
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000616 def test_with_continue_rejected(self):
617 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
618 self.handler = RejectingSocketlessRequestHandler()
619 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
620 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
621 self.verify_expected_headers(result[1:-1])
622 # The expect handler should short circuit the usual get method by
623 # returning false here, so get_called should be false
624 self.assertFalse(self.handler.get_called)
625 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
626 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
627
Antoine Pitrouc4924372010-12-16 16:48:36 +0000628 def test_request_length(self):
629 # Issue #10714: huge request lines are discarded, to avoid Denial
630 # of Service attacks.
631 result = self.send_typical_request(b'GET ' + b'x' * 65537)
632 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
633 self.assertFalse(self.handler.get_called)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000634
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000635 def test_header_length(self):
636 # Issue #6791: same for headers
637 result = self.send_typical_request(
638 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
639 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
640 self.assertFalse(self.handler.get_called)
641
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000642class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
643 """ Test url parsing """
644 def setUp(self):
645 self.translated = os.getcwd()
646 self.translated = os.path.join(self.translated, 'filename')
647 self.handler = SocketlessRequestHandler()
648
649 def test_query_arguments(self):
650 path = self.handler.translate_path('/filename')
651 self.assertEqual(path, self.translated)
652 path = self.handler.translate_path('/filename?foo=bar')
653 self.assertEqual(path, self.translated)
654 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
655 self.assertEqual(path, self.translated)
656
657 def test_start_with_double_slash(self):
658 path = self.handler.translate_path('//filename')
659 self.assertEqual(path, self.translated)
660 path = self.handler.translate_path('//filename?foo=bar')
661 self.assertEqual(path, self.translated)
662
663
Georg Brandlb533e262008-05-25 18:19:30 +0000664def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000665 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000666 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000667 support.run_unittest(
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000668 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000669 BaseHTTPServerTestCase,
670 SimpleHTTPServerTestCase,
671 CGIHTTPServerTestCase,
672 SimpleHTTPRequestHandlerTestCase,
673 )
Georg Brandlb533e262008-05-25 18:19:30 +0000674 finally:
675 os.chdir(cwd)
676
677if __name__ == '__main__':
678 test_main()