blob: 1430ff22035da265561a3bf8bcf74a8101933756 [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
Senthil Kumarand70846b2012-04-12 02:34:32 +0800369 def test_url_collapse_path(self):
370 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000371 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800372 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000373 '..': IndexError,
374 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800375 '/': '//',
376 '//': '//',
377 '/\\': '//\\',
378 '/.//': '//',
379 'cgi-bin/file1.py': '/cgi-bin/file1.py',
380 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
381 'a': '//a',
382 '/a': '//a',
383 '//a': '//a',
384 './a': '//a',
385 './C:/': '/C:/',
386 '/a/b': '/a/b',
387 '/a/b/': '/a/b/',
388 '/a/b/.': '/a/b/',
389 '/a/b/c/..': '/a/b/',
390 '/a/b/c/../d': '/a/b/d',
391 '/a/b/c/../d/e/../f': '/a/b/d/f',
392 '/a/b/c/../d/e/../../f': '/a/b/f',
393 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000394 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800395 '/a/b/c/../d/e/../../../f': '/a/f',
396 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000397 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800398 '/a/b/c/../d/e/../../../../f/..': '//',
399 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000400 }
401 for path, expected in test_vectors.items():
402 if isinstance(expected, type) and issubclass(expected, Exception):
403 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800404 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000405 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800406 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000407 self.assertEqual(expected, actual,
408 msg='path = %r\nGot: %r\nWanted: %r' %
409 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000410
Georg Brandlb533e262008-05-25 18:19:30 +0000411 def test_headers_and_content(self):
412 res = self.request('/cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000413 self.assertEqual((b'Hello World\n', 'text/html', 200),
414 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000415
416 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000417 params = urllib.parse.urlencode(
418 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000419 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
420 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
421
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000422 self.assertEqual(res.read(), b'1, python, 123456\n')
Georg Brandlb533e262008-05-25 18:19:30 +0000423
424 def test_invaliduri(self):
425 res = self.request('/cgi-bin/invalid')
426 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000427 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000428
429 def test_authorization(self):
430 headers = {b'Authorization' : b'Basic ' +
431 base64.b64encode(b'username:pass')}
432 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000433 self.assertEqual((b'Hello World\n', 'text/html', 200),
434 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000435
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000436 def test_no_leading_slash(self):
437 # http://bugs.python.org/issue2254
438 res = self.request('cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000439 self.assertEqual((b'Hello World\n', 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000440 (res.read(), res.getheader('Content-type'), res.status))
441
Senthil Kumaran42713722010-10-03 17:55:45 +0000442 def test_os_environ_is_not_altered(self):
443 signature = "Test CGI Server"
444 os.environ['SERVER_SOFTWARE'] = signature
445 res = self.request('/cgi-bin/file1.py')
446 self.assertEqual((b'Hello World\n', 'text/html', 200),
447 (res.read(), res.getheader('Content-type'), res.status))
448 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
449
Georg Brandlb533e262008-05-25 18:19:30 +0000450
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000451class SocketlessRequestHandler(SimpleHTTPRequestHandler):
452 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000453 self.get_called = False
454 self.protocol_version = "HTTP/1.1"
455
456 def do_GET(self):
457 self.get_called = True
458 self.send_response(200)
459 self.send_header('Content-Type', 'text/html')
460 self.end_headers()
461 self.wfile.write(b'<html><body>Data</body></html>\r\n')
462
463 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000464 pass
465
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000466class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
467 def handle_expect_100(self):
468 self.send_error(417)
469 return False
470
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800471
472class AuditableBytesIO:
473
474 def __init__(self):
475 self.datas = []
476
477 def write(self, data):
478 self.datas.append(data)
479
480 def getData(self):
481 return b''.join(self.datas)
482
483 @property
484 def numWrites(self):
485 return len(self.datas)
486
487
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000488class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200489 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000490
491 Test the support for the Expect 100-continue header.
492 """
493
494 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
495
496 def setUp (self):
497 self.handler = SocketlessRequestHandler()
498
499 def send_typical_request(self, message):
500 input = BytesIO(message)
501 output = BytesIO()
502 self.handler.rfile = input
503 self.handler.wfile = output
504 self.handler.handle_one_request()
505 output.seek(0)
506 return output.readlines()
507
508 def verify_get_called(self):
509 self.assertTrue(self.handler.get_called)
510
511 def verify_expected_headers(self, headers):
512 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
513 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
514
515 def verify_http_server_response(self, response):
516 match = self.HTTPResponseMatch.search(response)
517 self.assertTrue(match is not None)
518
519 def test_http_1_1(self):
520 result = self.send_typical_request(b'GET / HTTP/1.1\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_1_0(self):
527 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
528 self.verify_http_server_response(result[0])
529 self.verify_expected_headers(result[1:-1])
530 self.verify_get_called()
531 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
532
533 def test_http_0_9(self):
534 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
535 self.assertEqual(len(result), 1)
536 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
537 self.verify_get_called()
538
539 def test_with_continue_1_0(self):
540 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
541 self.verify_http_server_response(result[0])
542 self.verify_expected_headers(result[1:-1])
543 self.verify_get_called()
544 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
545
546 def test_with_continue_1_1(self):
547 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
548 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
549 self.assertEqual(result[1], b'HTTP/1.1 200 OK\r\n')
550 self.verify_expected_headers(result[2:-1])
551 self.verify_get_called()
552 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
553
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800554 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000555
556 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800557 output = AuditableBytesIO()
558 handler = SocketlessRequestHandler()
559 handler.rfile = input
560 handler.wfile = output
561 handler.request_version = 'HTTP/1.1'
562 handler.requestline = ''
563 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000564
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800565 handler.send_error(418)
566 self.assertEqual(output.numWrites, 2)
567
568 def test_header_buffering_of_send_response_only(self):
569
570 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
571 output = AuditableBytesIO()
572 handler = SocketlessRequestHandler()
573 handler.rfile = input
574 handler.wfile = output
575 handler.request_version = 'HTTP/1.1'
576
577 handler.send_response_only(418)
578 self.assertEqual(output.numWrites, 0)
579 handler.end_headers()
580 self.assertEqual(output.numWrites, 1)
581
582 def test_header_buffering_of_send_header(self):
583
584 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
585 output = AuditableBytesIO()
586 handler = SocketlessRequestHandler()
587 handler.rfile = input
588 handler.wfile = output
589 handler.request_version = 'HTTP/1.1'
590
591 handler.send_header('Foo', 'foo')
592 handler.send_header('bar', 'bar')
593 self.assertEqual(output.numWrites, 0)
594 handler.end_headers()
595 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
596 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000597
598 def test_header_unbuffered_when_continue(self):
599
600 def _readAndReseek(f):
601 pos = f.tell()
602 f.seek(0)
603 data = f.read()
604 f.seek(pos)
605 return data
606
607 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
608 output = BytesIO()
609 self.handler.rfile = input
610 self.handler.wfile = output
611 self.handler.request_version = 'HTTP/1.1'
612
613 self.handler.handle_one_request()
614 self.assertNotEqual(_readAndReseek(output), b'')
615 result = _readAndReseek(output).split(b'\r\n')
616 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
617 self.assertEqual(result[1], b'HTTP/1.1 200 OK')
618
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000619 def test_with_continue_rejected(self):
620 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
621 self.handler = RejectingSocketlessRequestHandler()
622 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
623 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
624 self.verify_expected_headers(result[1:-1])
625 # The expect handler should short circuit the usual get method by
626 # returning false here, so get_called should be false
627 self.assertFalse(self.handler.get_called)
628 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
629 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
630
Antoine Pitrouc4924372010-12-16 16:48:36 +0000631 def test_request_length(self):
632 # Issue #10714: huge request lines are discarded, to avoid Denial
633 # of Service attacks.
634 result = self.send_typical_request(b'GET ' + b'x' * 65537)
635 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
636 self.assertFalse(self.handler.get_called)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000637
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000638 def test_header_length(self):
639 # Issue #6791: same for headers
640 result = self.send_typical_request(
641 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
642 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
643 self.assertFalse(self.handler.get_called)
644
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000645class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
646 """ Test url parsing """
647 def setUp(self):
648 self.translated = os.getcwd()
649 self.translated = os.path.join(self.translated, 'filename')
650 self.handler = SocketlessRequestHandler()
651
652 def test_query_arguments(self):
653 path = self.handler.translate_path('/filename')
654 self.assertEqual(path, self.translated)
655 path = self.handler.translate_path('/filename?foo=bar')
656 self.assertEqual(path, self.translated)
657 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
658 self.assertEqual(path, self.translated)
659
660 def test_start_with_double_slash(self):
661 path = self.handler.translate_path('//filename')
662 self.assertEqual(path, self.translated)
663 path = self.handler.translate_path('//filename?foo=bar')
664 self.assertEqual(path, self.translated)
665
666
Georg Brandlb533e262008-05-25 18:19:30 +0000667def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000668 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000669 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000670 support.run_unittest(
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000671 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000672 BaseHTTPServerTestCase,
673 SimpleHTTPServerTestCase,
674 CGIHTTPServerTestCase,
675 SimpleHTTPRequestHandlerTestCase,
676 )
Georg Brandlb533e262008-05-25 18:19:30 +0000677 finally:
678 os.chdir(cwd)
679
680if __name__ == '__main__':
681 test_main()