blob: d78ae9a6bf1ff21fb9095686966fabd98e6154e8 [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
Antoine Pitroue768c392012-08-05 14:52:45 +0200316 linesep = os.linesep.encode('ascii')
317
Georg Brandlb533e262008-05-25 18:19:30 +0000318 def setUp(self):
319 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000320 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000321 self.parent_dir = tempfile.mkdtemp()
322 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
323 os.mkdir(self.cgi_dir)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000324 self.file1_path = None
325 self.file2_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000326
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000327 # The shebang line should be pure ASCII: use symlink if possible.
328 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000329 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000330 self.pythonexe = os.path.join(self.parent_dir, 'python')
331 os.symlink(sys.executable, self.pythonexe)
332 else:
333 self.pythonexe = sys.executable
334
Victor Stinner3218c312010-10-17 20:13:36 +0000335 try:
336 # The python executable path is written as the first line of the
337 # CGI Python script. The encoding cookie cannot be used, and so the
338 # path should be encodable to the default script encoding (utf-8)
339 self.pythonexe.encode('utf-8')
340 except UnicodeEncodeError:
341 self.tearDown()
342 raise self.skipTest(
343 "Python executable path is not encodable to utf-8")
344
Georg Brandlb533e262008-05-25 18:19:30 +0000345 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000346 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000347 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000348 os.chmod(self.file1_path, 0o777)
349
350 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000351 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000352 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000353 os.chmod(self.file2_path, 0o777)
354
Georg Brandlb533e262008-05-25 18:19:30 +0000355 os.chdir(self.parent_dir)
356
357 def tearDown(self):
358 try:
359 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000360 if self.pythonexe != sys.executable:
361 os.remove(self.pythonexe)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000362 if self.file1_path:
363 os.remove(self.file1_path)
364 if self.file2_path:
365 os.remove(self.file2_path)
Georg Brandlb533e262008-05-25 18:19:30 +0000366 os.rmdir(self.cgi_dir)
367 os.rmdir(self.parent_dir)
368 finally:
369 BaseTestCase.tearDown(self)
370
Senthil Kumarand70846b2012-04-12 02:34:32 +0800371 def test_url_collapse_path(self):
372 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000373 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800374 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000375 '..': IndexError,
376 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800377 '/': '//',
378 '//': '//',
379 '/\\': '//\\',
380 '/.//': '//',
381 'cgi-bin/file1.py': '/cgi-bin/file1.py',
382 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
383 'a': '//a',
384 '/a': '//a',
385 '//a': '//a',
386 './a': '//a',
387 './C:/': '/C:/',
388 '/a/b': '/a/b',
389 '/a/b/': '/a/b/',
390 '/a/b/.': '/a/b/',
391 '/a/b/c/..': '/a/b/',
392 '/a/b/c/../d': '/a/b/d',
393 '/a/b/c/../d/e/../f': '/a/b/d/f',
394 '/a/b/c/../d/e/../../f': '/a/b/f',
395 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000396 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800397 '/a/b/c/../d/e/../../../f': '/a/f',
398 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000399 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800400 '/a/b/c/../d/e/../../../../f/..': '//',
401 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000402 }
403 for path, expected in test_vectors.items():
404 if isinstance(expected, type) and issubclass(expected, Exception):
405 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800406 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000407 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800408 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000409 self.assertEqual(expected, actual,
410 msg='path = %r\nGot: %r\nWanted: %r' %
411 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000412
Georg Brandlb533e262008-05-25 18:19:30 +0000413 def test_headers_and_content(self):
414 res = self.request('/cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200415 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000416 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000417
418 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000419 params = urllib.parse.urlencode(
420 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000421 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
422 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
423
Antoine Pitroue768c392012-08-05 14:52:45 +0200424 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000425
426 def test_invaliduri(self):
427 res = self.request('/cgi-bin/invalid')
428 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000429 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000430
431 def test_authorization(self):
432 headers = {b'Authorization' : b'Basic ' +
433 base64.b64encode(b'username:pass')}
434 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Antoine Pitroue768c392012-08-05 14:52:45 +0200435 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000436 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000437
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000438 def test_no_leading_slash(self):
439 # http://bugs.python.org/issue2254
440 res = self.request('cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200441 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000442 (res.read(), res.getheader('Content-type'), res.status))
443
Senthil Kumaran42713722010-10-03 17:55:45 +0000444 def test_os_environ_is_not_altered(self):
445 signature = "Test CGI Server"
446 os.environ['SERVER_SOFTWARE'] = signature
447 res = self.request('/cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200448 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Senthil Kumaran42713722010-10-03 17:55:45 +0000449 (res.read(), res.getheader('Content-type'), res.status))
450 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
451
Georg Brandlb533e262008-05-25 18:19:30 +0000452
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000453class SocketlessRequestHandler(SimpleHTTPRequestHandler):
454 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000455 self.get_called = False
456 self.protocol_version = "HTTP/1.1"
457
458 def do_GET(self):
459 self.get_called = True
460 self.send_response(200)
461 self.send_header('Content-Type', 'text/html')
462 self.end_headers()
463 self.wfile.write(b'<html><body>Data</body></html>\r\n')
464
465 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000466 pass
467
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000468class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
469 def handle_expect_100(self):
470 self.send_error(417)
471 return False
472
473class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200474 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000475
476 Test the support for the Expect 100-continue header.
477 """
478
479 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
480
481 def setUp (self):
482 self.handler = SocketlessRequestHandler()
483
484 def send_typical_request(self, message):
485 input = BytesIO(message)
486 output = BytesIO()
487 self.handler.rfile = input
488 self.handler.wfile = output
489 self.handler.handle_one_request()
490 output.seek(0)
491 return output.readlines()
492
493 def verify_get_called(self):
494 self.assertTrue(self.handler.get_called)
495
496 def verify_expected_headers(self, headers):
497 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
498 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
499
500 def verify_http_server_response(self, response):
501 match = self.HTTPResponseMatch.search(response)
502 self.assertTrue(match is not None)
503
504 def test_http_1_1(self):
505 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
506 self.verify_http_server_response(result[0])
507 self.verify_expected_headers(result[1:-1])
508 self.verify_get_called()
509 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
510
511 def test_http_1_0(self):
512 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
513 self.verify_http_server_response(result[0])
514 self.verify_expected_headers(result[1:-1])
515 self.verify_get_called()
516 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
517
518 def test_http_0_9(self):
519 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
520 self.assertEqual(len(result), 1)
521 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
522 self.verify_get_called()
523
524 def test_with_continue_1_0(self):
525 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
526 self.verify_http_server_response(result[0])
527 self.verify_expected_headers(result[1:-1])
528 self.verify_get_called()
529 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
530
531 def test_with_continue_1_1(self):
532 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
533 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
534 self.assertEqual(result[1], b'HTTP/1.1 200 OK\r\n')
535 self.verify_expected_headers(result[2:-1])
536 self.verify_get_called()
537 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
538
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000539 def test_header_buffering(self):
540
541 def _readAndReseek(f):
542 pos = f.tell()
543 f.seek(0)
544 data = f.read()
545 f.seek(pos)
546 return data
547
548 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
549 output = BytesIO()
550 self.handler.rfile = input
551 self.handler.wfile = output
552 self.handler.request_version = 'HTTP/1.1'
553
554 self.handler.send_header('Foo', 'foo')
555 self.handler.send_header('bar', 'bar')
556 self.assertEqual(_readAndReseek(output), b'')
557 self.handler.end_headers()
558 self.assertEqual(_readAndReseek(output),
559 b'Foo: foo\r\nbar: bar\r\n\r\n')
560
561 def test_header_unbuffered_when_continue(self):
562
563 def _readAndReseek(f):
564 pos = f.tell()
565 f.seek(0)
566 data = f.read()
567 f.seek(pos)
568 return data
569
570 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
571 output = BytesIO()
572 self.handler.rfile = input
573 self.handler.wfile = output
574 self.handler.request_version = 'HTTP/1.1'
575
576 self.handler.handle_one_request()
577 self.assertNotEqual(_readAndReseek(output), b'')
578 result = _readAndReseek(output).split(b'\r\n')
579 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
580 self.assertEqual(result[1], b'HTTP/1.1 200 OK')
581
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000582 def test_with_continue_rejected(self):
583 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
584 self.handler = RejectingSocketlessRequestHandler()
585 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
586 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
587 self.verify_expected_headers(result[1:-1])
588 # The expect handler should short circuit the usual get method by
589 # returning false here, so get_called should be false
590 self.assertFalse(self.handler.get_called)
591 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
592 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
593
Antoine Pitrouc4924372010-12-16 16:48:36 +0000594 def test_request_length(self):
595 # Issue #10714: huge request lines are discarded, to avoid Denial
596 # of Service attacks.
597 result = self.send_typical_request(b'GET ' + b'x' * 65537)
598 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
599 self.assertFalse(self.handler.get_called)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000600
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000601 def test_header_length(self):
602 # Issue #6791: same for headers
603 result = self.send_typical_request(
604 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
605 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
606 self.assertFalse(self.handler.get_called)
607
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000608class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
609 """ Test url parsing """
610 def setUp(self):
611 self.translated = os.getcwd()
612 self.translated = os.path.join(self.translated, 'filename')
613 self.handler = SocketlessRequestHandler()
614
615 def test_query_arguments(self):
616 path = self.handler.translate_path('/filename')
617 self.assertEqual(path, self.translated)
618 path = self.handler.translate_path('/filename?foo=bar')
619 self.assertEqual(path, self.translated)
620 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
621 self.assertEqual(path, self.translated)
622
623 def test_start_with_double_slash(self):
624 path = self.handler.translate_path('//filename')
625 self.assertEqual(path, self.translated)
626 path = self.handler.translate_path('//filename?foo=bar')
627 self.assertEqual(path, self.translated)
628
629
Georg Brandlb533e262008-05-25 18:19:30 +0000630def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000631 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000632 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000633 support.run_unittest(
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000634 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000635 BaseHTTPServerTestCase,
636 SimpleHTTPServerTestCase,
637 CGIHTTPServerTestCase,
638 SimpleHTTPRequestHandlerTestCase,
639 )
Georg Brandlb533e262008-05-25 18:19:30 +0000640 finally:
641 os.chdir(cwd)
642
643if __name__ == '__main__':
644 test_main()