blob: c5db620421d45578a5620d5444c99b66ef4413fc [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()
Antoine Pitrouf7270822012-09-30 01:05:30 +020065 self.thread = None
Nick Coghlan6ead5522009-10-18 13:19:33 +000066 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000067 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000068
69 def request(self, uri, method='GET', body=None, headers={}):
Antoine Pitroucb342182011-03-21 00:26:51 +010070 self.connection = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000071 self.connection.request(method, uri, body, headers)
72 return self.connection.getresponse()
73
74
75class BaseHTTPServerTestCase(BaseTestCase):
76 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
77 protocol_version = 'HTTP/1.1'
78 default_request_version = 'HTTP/1.1'
79
80 def do_TEST(self):
81 self.send_response(204)
82 self.send_header('Content-Type', 'text/html')
83 self.send_header('Connection', 'close')
84 self.end_headers()
85
86 def do_KEEP(self):
87 self.send_response(204)
88 self.send_header('Content-Type', 'text/html')
89 self.send_header('Connection', 'keep-alive')
90 self.end_headers()
91
92 def do_KEYERROR(self):
93 self.send_error(999)
94
Senthil Kumaran52d27202012-10-10 23:16:21 -070095 def do_NOTFOUND(self):
96 self.send_error(404)
97
Georg Brandlb533e262008-05-25 18:19:30 +000098 def do_CUSTOM(self):
99 self.send_response(999)
100 self.send_header('Content-Type', 'text/html')
101 self.send_header('Connection', 'close')
102 self.end_headers()
103
Armin Ronacher8d96d772011-01-22 13:13:05 +0000104 def do_LATINONEHEADER(self):
105 self.send_response(999)
106 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000107 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000108 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000109 body = self.headers['x-special-incoming'].encode('utf-8')
110 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000111
Georg Brandlb533e262008-05-25 18:19:30 +0000112 def setUp(self):
113 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100114 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000115 self.con.connect()
116
117 def test_command(self):
118 self.con.request('GET', '/')
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_request_line_trimming(self):
123 self.con._http_vsn_str = 'HTTP/1.1\n'
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, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000128
129 def test_version_bogus(self):
130 self.con._http_vsn_str = 'FUBAR'
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_digits(self):
137 self.con._http_vsn_str = 'HTTP/9.9.9'
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, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000142
143 def test_version_none_get(self):
144 self.con._http_vsn_str = ''
145 self.con.putrequest('GET', '/')
146 self.con.endheaders()
147 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000148 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000149
150 def test_version_none(self):
151 self.con._http_vsn_str = ''
152 self.con.putrequest('PUT', '/')
153 self.con.endheaders()
154 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000155 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000156
157 def test_version_invalid(self):
158 self.con._http_vsn = 99
159 self.con._http_vsn_str = 'HTTP/9.9'
160 self.con.putrequest('GET', '/')
161 self.con.endheaders()
162 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000163 self.assertEqual(res.status, 505)
Georg Brandlb533e262008-05-25 18:19:30 +0000164
165 def test_send_blank(self):
166 self.con._http_vsn_str = ''
167 self.con.putrequest('', '')
168 self.con.endheaders()
169 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000170 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000171
172 def test_header_close(self):
173 self.con.putrequest('GET', '/')
174 self.con.putheader('Connection', 'close')
175 self.con.endheaders()
176 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000177 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000178
179 def test_head_keep_alive(self):
180 self.con._http_vsn_str = 'HTTP/1.1'
181 self.con.putrequest('GET', '/')
182 self.con.putheader('Connection', 'keep-alive')
183 self.con.endheaders()
184 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000185 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000186
187 def test_handler(self):
188 self.con.request('TEST', '/')
189 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000190 self.assertEqual(res.status, 204)
Georg Brandlb533e262008-05-25 18:19:30 +0000191
192 def test_return_header_keep_alive(self):
193 self.con.request('KEEP', '/')
194 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000195 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000196 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000197 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000198
199 def test_internal_key_error(self):
200 self.con.request('KEYERROR', '/')
201 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000202 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000203
204 def test_return_custom_status(self):
205 self.con.request('CUSTOM', '/')
206 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000207 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000208
Armin Ronacher8d96d772011-01-22 13:13:05 +0000209 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000210 self.con.request('LATINONEHEADER', '/', headers={
211 'X-Special-Incoming': 'Ärger mit Unicode'
212 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000213 res = self.con.getresponse()
214 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000215 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000216
Senthil Kumaran52d27202012-10-10 23:16:21 -0700217 def test_error_content_length(self):
218 # Issue #16088: standard error responses should have a content-length
219 self.con.request('NOTFOUND', '/')
220 res = self.con.getresponse()
221 self.assertEqual(res.status, 404)
222 data = res.read()
Senthil Kumaran52d27202012-10-10 23:16:21 -0700223 self.assertEqual(int(res.getheader('Content-Length')), len(data))
224
Georg Brandlb533e262008-05-25 18:19:30 +0000225
226class SimpleHTTPServerTestCase(BaseTestCase):
227 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
228 pass
229
230 def setUp(self):
231 BaseTestCase.setUp(self)
232 self.cwd = os.getcwd()
233 basetempdir = tempfile.gettempdir()
234 os.chdir(basetempdir)
235 self.data = b'We are the knights who say Ni!'
236 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
237 self.tempdir_name = os.path.basename(self.tempdir)
Brett Cannon105df5d2010-10-29 23:43:42 +0000238 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
239 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000240
241 def tearDown(self):
242 try:
243 os.chdir(self.cwd)
244 try:
245 shutil.rmtree(self.tempdir)
246 except:
247 pass
248 finally:
249 BaseTestCase.tearDown(self)
250
251 def check_status_and_reason(self, response, status, data=None):
252 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000253 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000254 self.assertEqual(response.status, status)
255 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000256 if data:
257 self.assertEqual(data, body)
258
259 def test_get(self):
260 #constructs the path relative to the root directory of the HTTPServer
261 response = self.request(self.tempdir_name + '/test')
262 self.check_status_and_reason(response, 200, data=self.data)
263 response = self.request(self.tempdir_name + '/')
264 self.check_status_and_reason(response, 200)
265 response = self.request(self.tempdir_name)
266 self.check_status_and_reason(response, 301)
267 response = self.request('/ThisDoesNotExist')
268 self.check_status_and_reason(response, 404)
269 response = self.request('/' + 'ThisDoesNotExist' + '/')
270 self.check_status_and_reason(response, 404)
Brett Cannon105df5d2010-10-29 23:43:42 +0000271 with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as f:
272 response = self.request('/' + self.tempdir_name + '/')
273 self.check_status_and_reason(response, 200)
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100274 # chmod() doesn't work as expected on Windows, and filesystem
275 # permissions are ignored by root on Unix.
276 if os.name == 'posix' and os.geteuid() != 0:
Brett Cannon105df5d2010-10-29 23:43:42 +0000277 os.chmod(self.tempdir, 0)
278 response = self.request(self.tempdir_name + '/')
279 self.check_status_and_reason(response, 404)
280 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000281
282 def test_head(self):
283 response = self.request(
284 self.tempdir_name + '/test', method='HEAD')
285 self.check_status_and_reason(response, 200)
286 self.assertEqual(response.getheader('content-length'),
287 str(len(self.data)))
288 self.assertEqual(response.getheader('content-type'),
289 'application/octet-stream')
290
291 def test_invalid_requests(self):
292 response = self.request('/', method='FOO')
293 self.check_status_and_reason(response, 501)
294 # requests must be case sensitive,so this should fail too
295 response = self.request('/', method='get')
296 self.check_status_and_reason(response, 501)
297 response = self.request('/', method='GETs')
298 self.check_status_and_reason(response, 501)
299
300
301cgi_file1 = """\
302#!%s
303
304print("Content-type: text/html")
305print()
306print("Hello World")
307"""
308
309cgi_file2 = """\
310#!%s
311import cgi
312
313print("Content-type: text/html")
314print()
315
316form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000317print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
318 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000319"""
320
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100321
322@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
323 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000324class CGIHTTPServerTestCase(BaseTestCase):
325 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
326 pass
327
Antoine Pitroue768c392012-08-05 14:52:45 +0200328 linesep = os.linesep.encode('ascii')
329
Georg Brandlb533e262008-05-25 18:19:30 +0000330 def setUp(self):
331 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000332 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000333 self.parent_dir = tempfile.mkdtemp()
334 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
335 os.mkdir(self.cgi_dir)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000336 self.file1_path = None
337 self.file2_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000338
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000339 # The shebang line should be pure ASCII: use symlink if possible.
340 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000341 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000342 self.pythonexe = os.path.join(self.parent_dir, 'python')
343 os.symlink(sys.executable, self.pythonexe)
344 else:
345 self.pythonexe = sys.executable
346
Victor Stinner3218c312010-10-17 20:13:36 +0000347 try:
348 # The python executable path is written as the first line of the
349 # CGI Python script. The encoding cookie cannot be used, and so the
350 # path should be encodable to the default script encoding (utf-8)
351 self.pythonexe.encode('utf-8')
352 except UnicodeEncodeError:
353 self.tearDown()
354 raise self.skipTest(
355 "Python executable path is not encodable to utf-8")
356
Georg Brandlb533e262008-05-25 18:19:30 +0000357 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000358 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000359 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000360 os.chmod(self.file1_path, 0o777)
361
362 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000363 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000364 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000365 os.chmod(self.file2_path, 0o777)
366
Georg Brandlb533e262008-05-25 18:19:30 +0000367 os.chdir(self.parent_dir)
368
369 def tearDown(self):
370 try:
371 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000372 if self.pythonexe != sys.executable:
373 os.remove(self.pythonexe)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000374 if self.file1_path:
375 os.remove(self.file1_path)
376 if self.file2_path:
377 os.remove(self.file2_path)
Georg Brandlb533e262008-05-25 18:19:30 +0000378 os.rmdir(self.cgi_dir)
379 os.rmdir(self.parent_dir)
380 finally:
381 BaseTestCase.tearDown(self)
382
Senthil Kumarand70846b2012-04-12 02:34:32 +0800383 def test_url_collapse_path(self):
384 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000385 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800386 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000387 '..': IndexError,
388 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800389 '/': '//',
390 '//': '//',
391 '/\\': '//\\',
392 '/.//': '//',
393 'cgi-bin/file1.py': '/cgi-bin/file1.py',
394 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
395 'a': '//a',
396 '/a': '//a',
397 '//a': '//a',
398 './a': '//a',
399 './C:/': '/C:/',
400 '/a/b': '/a/b',
401 '/a/b/': '/a/b/',
402 '/a/b/.': '/a/b/',
403 '/a/b/c/..': '/a/b/',
404 '/a/b/c/../d': '/a/b/d',
405 '/a/b/c/../d/e/../f': '/a/b/d/f',
406 '/a/b/c/../d/e/../../f': '/a/b/f',
407 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000408 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800409 '/a/b/c/../d/e/../../../f': '/a/f',
410 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000411 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800412 '/a/b/c/../d/e/../../../../f/..': '//',
413 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000414 }
415 for path, expected in test_vectors.items():
416 if isinstance(expected, type) and issubclass(expected, Exception):
417 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800418 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000419 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800420 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000421 self.assertEqual(expected, actual,
422 msg='path = %r\nGot: %r\nWanted: %r' %
423 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000424
Georg Brandlb533e262008-05-25 18:19:30 +0000425 def test_headers_and_content(self):
426 res = self.request('/cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200427 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000428 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000429
430 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000431 params = urllib.parse.urlencode(
432 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000433 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
434 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
435
Antoine Pitroue768c392012-08-05 14:52:45 +0200436 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000437
438 def test_invaliduri(self):
439 res = self.request('/cgi-bin/invalid')
440 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000441 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000442
443 def test_authorization(self):
444 headers = {b'Authorization' : b'Basic ' +
445 base64.b64encode(b'username:pass')}
446 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Antoine Pitroue768c392012-08-05 14:52:45 +0200447 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000448 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000449
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000450 def test_no_leading_slash(self):
451 # http://bugs.python.org/issue2254
452 res = self.request('cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200453 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000454 (res.read(), res.getheader('Content-type'), res.status))
455
Senthil Kumaran42713722010-10-03 17:55:45 +0000456 def test_os_environ_is_not_altered(self):
457 signature = "Test CGI Server"
458 os.environ['SERVER_SOFTWARE'] = signature
459 res = self.request('/cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200460 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Senthil Kumaran42713722010-10-03 17:55:45 +0000461 (res.read(), res.getheader('Content-type'), res.status))
462 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
463
Georg Brandlb533e262008-05-25 18:19:30 +0000464
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000465class SocketlessRequestHandler(SimpleHTTPRequestHandler):
466 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000467 self.get_called = False
468 self.protocol_version = "HTTP/1.1"
469
470 def do_GET(self):
471 self.get_called = True
472 self.send_response(200)
473 self.send_header('Content-Type', 'text/html')
474 self.end_headers()
475 self.wfile.write(b'<html><body>Data</body></html>\r\n')
476
477 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000478 pass
479
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000480class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
481 def handle_expect_100(self):
482 self.send_error(417)
483 return False
484
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800485
486class AuditableBytesIO:
487
488 def __init__(self):
489 self.datas = []
490
491 def write(self, data):
492 self.datas.append(data)
493
494 def getData(self):
495 return b''.join(self.datas)
496
497 @property
498 def numWrites(self):
499 return len(self.datas)
500
501
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000502class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200503 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000504
505 Test the support for the Expect 100-continue header.
506 """
507
508 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
509
510 def setUp (self):
511 self.handler = SocketlessRequestHandler()
512
513 def send_typical_request(self, message):
514 input = BytesIO(message)
515 output = BytesIO()
516 self.handler.rfile = input
517 self.handler.wfile = output
518 self.handler.handle_one_request()
519 output.seek(0)
520 return output.readlines()
521
522 def verify_get_called(self):
523 self.assertTrue(self.handler.get_called)
524
525 def verify_expected_headers(self, headers):
526 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
527 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
528
529 def verify_http_server_response(self, response):
530 match = self.HTTPResponseMatch.search(response)
531 self.assertTrue(match is not None)
532
533 def test_http_1_1(self):
534 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
535 self.verify_http_server_response(result[0])
536 self.verify_expected_headers(result[1:-1])
537 self.verify_get_called()
538 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
539
540 def test_http_1_0(self):
541 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
542 self.verify_http_server_response(result[0])
543 self.verify_expected_headers(result[1:-1])
544 self.verify_get_called()
545 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
546
547 def test_http_0_9(self):
548 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
549 self.assertEqual(len(result), 1)
550 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
551 self.verify_get_called()
552
553 def test_with_continue_1_0(self):
554 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
555 self.verify_http_server_response(result[0])
556 self.verify_expected_headers(result[1:-1])
557 self.verify_get_called()
558 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
559
560 def test_with_continue_1_1(self):
561 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
562 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
563 self.assertEqual(result[1], b'HTTP/1.1 200 OK\r\n')
564 self.verify_expected_headers(result[2:-1])
565 self.verify_get_called()
566 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
567
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800568 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000569
570 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800571 output = AuditableBytesIO()
572 handler = SocketlessRequestHandler()
573 handler.rfile = input
574 handler.wfile = output
575 handler.request_version = 'HTTP/1.1'
576 handler.requestline = ''
577 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000578
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800579 handler.send_error(418)
580 self.assertEqual(output.numWrites, 2)
581
582 def test_header_buffering_of_send_response_only(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_response_only(418)
592 self.assertEqual(output.numWrites, 0)
593 handler.end_headers()
594 self.assertEqual(output.numWrites, 1)
595
596 def test_header_buffering_of_send_header(self):
597
598 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
599 output = AuditableBytesIO()
600 handler = SocketlessRequestHandler()
601 handler.rfile = input
602 handler.wfile = output
603 handler.request_version = 'HTTP/1.1'
604
605 handler.send_header('Foo', 'foo')
606 handler.send_header('bar', 'bar')
607 self.assertEqual(output.numWrites, 0)
608 handler.end_headers()
609 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
610 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000611
612 def test_header_unbuffered_when_continue(self):
613
614 def _readAndReseek(f):
615 pos = f.tell()
616 f.seek(0)
617 data = f.read()
618 f.seek(pos)
619 return data
620
621 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
622 output = BytesIO()
623 self.handler.rfile = input
624 self.handler.wfile = output
625 self.handler.request_version = 'HTTP/1.1'
626
627 self.handler.handle_one_request()
628 self.assertNotEqual(_readAndReseek(output), b'')
629 result = _readAndReseek(output).split(b'\r\n')
630 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
631 self.assertEqual(result[1], b'HTTP/1.1 200 OK')
632
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000633 def test_with_continue_rejected(self):
634 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
635 self.handler = RejectingSocketlessRequestHandler()
636 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
637 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
638 self.verify_expected_headers(result[1:-1])
639 # The expect handler should short circuit the usual get method by
640 # returning false here, so get_called should be false
641 self.assertFalse(self.handler.get_called)
642 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
643 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
644
Antoine Pitrouc4924372010-12-16 16:48:36 +0000645 def test_request_length(self):
646 # Issue #10714: huge request lines are discarded, to avoid Denial
647 # of Service attacks.
648 result = self.send_typical_request(b'GET ' + b'x' * 65537)
649 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
650 self.assertFalse(self.handler.get_called)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000651
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000652 def test_header_length(self):
653 # Issue #6791: same for headers
654 result = self.send_typical_request(
655 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
656 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
657 self.assertFalse(self.handler.get_called)
658
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000659class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
660 """ Test url parsing """
661 def setUp(self):
662 self.translated = os.getcwd()
663 self.translated = os.path.join(self.translated, 'filename')
664 self.handler = SocketlessRequestHandler()
665
666 def test_query_arguments(self):
667 path = self.handler.translate_path('/filename')
668 self.assertEqual(path, self.translated)
669 path = self.handler.translate_path('/filename?foo=bar')
670 self.assertEqual(path, self.translated)
671 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
672 self.assertEqual(path, self.translated)
673
674 def test_start_with_double_slash(self):
675 path = self.handler.translate_path('//filename')
676 self.assertEqual(path, self.translated)
677 path = self.handler.translate_path('//filename?foo=bar')
678 self.assertEqual(path, self.translated)
679
680
Georg Brandlb533e262008-05-25 18:19:30 +0000681def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000682 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000683 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000684 support.run_unittest(
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000685 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000686 BaseHTTPServerTestCase,
687 SimpleHTTPServerTestCase,
688 CGIHTTPServerTestCase,
689 SimpleHTTPRequestHandlerTestCase,
690 )
Georg Brandlb533e262008-05-25 18:19:30 +0000691 finally:
692 os.chdir(cwd)
693
694if __name__ == '__main__':
695 test_main()