blob: 92306aebfcfec6c6d79e95bd4a4ff83e04f61ae0 [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()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200354 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000355
Georg Brandlb533e262008-05-25 18:19:30 +0000356 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000357 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000358 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000359 os.chmod(self.file1_path, 0o777)
360
361 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000362 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000363 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000364 os.chmod(self.file2_path, 0o777)
365
Georg Brandlb533e262008-05-25 18:19:30 +0000366 os.chdir(self.parent_dir)
367
368 def tearDown(self):
369 try:
370 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000371 if self.pythonexe != sys.executable:
372 os.remove(self.pythonexe)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000373 if self.file1_path:
374 os.remove(self.file1_path)
375 if self.file2_path:
376 os.remove(self.file2_path)
Georg Brandlb533e262008-05-25 18:19:30 +0000377 os.rmdir(self.cgi_dir)
378 os.rmdir(self.parent_dir)
379 finally:
380 BaseTestCase.tearDown(self)
381
Senthil Kumarand70846b2012-04-12 02:34:32 +0800382 def test_url_collapse_path(self):
383 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000384 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800385 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000386 '..': IndexError,
387 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800388 '/': '//',
389 '//': '//',
390 '/\\': '//\\',
391 '/.//': '//',
392 'cgi-bin/file1.py': '/cgi-bin/file1.py',
393 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
394 'a': '//a',
395 '/a': '//a',
396 '//a': '//a',
397 './a': '//a',
398 './C:/': '/C:/',
399 '/a/b': '/a/b',
400 '/a/b/': '/a/b/',
401 '/a/b/.': '/a/b/',
402 '/a/b/c/..': '/a/b/',
403 '/a/b/c/../d': '/a/b/d',
404 '/a/b/c/../d/e/../f': '/a/b/d/f',
405 '/a/b/c/../d/e/../../f': '/a/b/f',
406 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000407 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800408 '/a/b/c/../d/e/../../../f': '/a/f',
409 '/a/b/c/../d/e/../../../../f': '//f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000410 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800411 '/a/b/c/../d/e/../../../../f/..': '//',
412 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000413 }
414 for path, expected in test_vectors.items():
415 if isinstance(expected, type) and issubclass(expected, Exception):
416 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800417 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000418 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800419 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000420 self.assertEqual(expected, actual,
421 msg='path = %r\nGot: %r\nWanted: %r' %
422 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000423
Georg Brandlb533e262008-05-25 18:19:30 +0000424 def test_headers_and_content(self):
425 res = self.request('/cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200426 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000427 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000428
429 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000430 params = urllib.parse.urlencode(
431 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000432 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
433 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
434
Antoine Pitroue768c392012-08-05 14:52:45 +0200435 self.assertEqual(res.read(), b'1, python, 123456' + self.linesep)
Georg Brandlb533e262008-05-25 18:19:30 +0000436
437 def test_invaliduri(self):
438 res = self.request('/cgi-bin/invalid')
439 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000440 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000441
442 def test_authorization(self):
443 headers = {b'Authorization' : b'Basic ' +
444 base64.b64encode(b'username:pass')}
445 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Antoine Pitroue768c392012-08-05 14:52:45 +0200446 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000447 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000448
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000449 def test_no_leading_slash(self):
450 # http://bugs.python.org/issue2254
451 res = self.request('cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200452 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000453 (res.read(), res.getheader('Content-type'), res.status))
454
Senthil Kumaran42713722010-10-03 17:55:45 +0000455 def test_os_environ_is_not_altered(self):
456 signature = "Test CGI Server"
457 os.environ['SERVER_SOFTWARE'] = signature
458 res = self.request('/cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200459 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Senthil Kumaran42713722010-10-03 17:55:45 +0000460 (res.read(), res.getheader('Content-type'), res.status))
461 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
462
Georg Brandlb533e262008-05-25 18:19:30 +0000463
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000464class SocketlessRequestHandler(SimpleHTTPRequestHandler):
465 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000466 self.get_called = False
467 self.protocol_version = "HTTP/1.1"
468
469 def do_GET(self):
470 self.get_called = True
471 self.send_response(200)
472 self.send_header('Content-Type', 'text/html')
473 self.end_headers()
474 self.wfile.write(b'<html><body>Data</body></html>\r\n')
475
476 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000477 pass
478
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000479class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
480 def handle_expect_100(self):
481 self.send_error(417)
482 return False
483
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800484
485class AuditableBytesIO:
486
487 def __init__(self):
488 self.datas = []
489
490 def write(self, data):
491 self.datas.append(data)
492
493 def getData(self):
494 return b''.join(self.datas)
495
496 @property
497 def numWrites(self):
498 return len(self.datas)
499
500
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000501class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200502 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000503
504 Test the support for the Expect 100-continue header.
505 """
506
507 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
508
509 def setUp (self):
510 self.handler = SocketlessRequestHandler()
511
512 def send_typical_request(self, message):
513 input = BytesIO(message)
514 output = BytesIO()
515 self.handler.rfile = input
516 self.handler.wfile = output
517 self.handler.handle_one_request()
518 output.seek(0)
519 return output.readlines()
520
521 def verify_get_called(self):
522 self.assertTrue(self.handler.get_called)
523
524 def verify_expected_headers(self, headers):
525 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
526 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
527
528 def verify_http_server_response(self, response):
529 match = self.HTTPResponseMatch.search(response)
530 self.assertTrue(match is not None)
531
532 def test_http_1_1(self):
533 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
534 self.verify_http_server_response(result[0])
535 self.verify_expected_headers(result[1:-1])
536 self.verify_get_called()
537 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
538
539 def test_http_1_0(self):
540 result = self.send_typical_request(b'GET / HTTP/1.0\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_http_0_9(self):
547 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
548 self.assertEqual(len(result), 1)
549 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
550 self.verify_get_called()
551
552 def test_with_continue_1_0(self):
553 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
554 self.verify_http_server_response(result[0])
555 self.verify_expected_headers(result[1:-1])
556 self.verify_get_called()
557 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
558
559 def test_with_continue_1_1(self):
560 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
561 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
562 self.assertEqual(result[1], b'HTTP/1.1 200 OK\r\n')
563 self.verify_expected_headers(result[2:-1])
564 self.verify_get_called()
565 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
566
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800567 def test_header_buffering_of_send_error(self):
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000568
569 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800570 output = AuditableBytesIO()
571 handler = SocketlessRequestHandler()
572 handler.rfile = input
573 handler.wfile = output
574 handler.request_version = 'HTTP/1.1'
575 handler.requestline = ''
576 handler.command = None
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000577
Senthil Kumaranc7ae19b2011-05-09 23:25:02 +0800578 handler.send_error(418)
579 self.assertEqual(output.numWrites, 2)
580
581 def test_header_buffering_of_send_response_only(self):
582
583 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
584 output = AuditableBytesIO()
585 handler = SocketlessRequestHandler()
586 handler.rfile = input
587 handler.wfile = output
588 handler.request_version = 'HTTP/1.1'
589
590 handler.send_response_only(418)
591 self.assertEqual(output.numWrites, 0)
592 handler.end_headers()
593 self.assertEqual(output.numWrites, 1)
594
595 def test_header_buffering_of_send_header(self):
596
597 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
598 output = AuditableBytesIO()
599 handler = SocketlessRequestHandler()
600 handler.rfile = input
601 handler.wfile = output
602 handler.request_version = 'HTTP/1.1'
603
604 handler.send_header('Foo', 'foo')
605 handler.send_header('bar', 'bar')
606 self.assertEqual(output.numWrites, 0)
607 handler.end_headers()
608 self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n')
609 self.assertEqual(output.numWrites, 1)
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000610
611 def test_header_unbuffered_when_continue(self):
612
613 def _readAndReseek(f):
614 pos = f.tell()
615 f.seek(0)
616 data = f.read()
617 f.seek(pos)
618 return data
619
620 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
621 output = BytesIO()
622 self.handler.rfile = input
623 self.handler.wfile = output
624 self.handler.request_version = 'HTTP/1.1'
625
626 self.handler.handle_one_request()
627 self.assertNotEqual(_readAndReseek(output), b'')
628 result = _readAndReseek(output).split(b'\r\n')
629 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
630 self.assertEqual(result[1], b'HTTP/1.1 200 OK')
631
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000632 def test_with_continue_rejected(self):
633 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
634 self.handler = RejectingSocketlessRequestHandler()
635 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
636 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
637 self.verify_expected_headers(result[1:-1])
638 # The expect handler should short circuit the usual get method by
639 # returning false here, so get_called should be false
640 self.assertFalse(self.handler.get_called)
641 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
642 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
643
Antoine Pitrouc4924372010-12-16 16:48:36 +0000644 def test_request_length(self):
645 # Issue #10714: huge request lines are discarded, to avoid Denial
646 # of Service attacks.
647 result = self.send_typical_request(b'GET ' + b'x' * 65537)
648 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
649 self.assertFalse(self.handler.get_called)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000650
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000651 def test_header_length(self):
652 # Issue #6791: same for headers
653 result = self.send_typical_request(
654 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
655 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
656 self.assertFalse(self.handler.get_called)
657
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000658class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
659 """ Test url parsing """
660 def setUp(self):
661 self.translated = os.getcwd()
662 self.translated = os.path.join(self.translated, 'filename')
663 self.handler = SocketlessRequestHandler()
664
665 def test_query_arguments(self):
666 path = self.handler.translate_path('/filename')
667 self.assertEqual(path, self.translated)
668 path = self.handler.translate_path('/filename?foo=bar')
669 self.assertEqual(path, self.translated)
670 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
671 self.assertEqual(path, self.translated)
672
673 def test_start_with_double_slash(self):
674 path = self.handler.translate_path('//filename')
675 self.assertEqual(path, self.translated)
676 path = self.handler.translate_path('//filename?foo=bar')
677 self.assertEqual(path, self.translated)
678
679
Georg Brandlb533e262008-05-25 18:19:30 +0000680def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000681 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000682 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000683 support.run_unittest(
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000684 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000685 BaseHTTPServerTestCase,
686 SimpleHTTPServerTestCase,
687 CGIHTTPServerTestCase,
688 SimpleHTTPRequestHandlerTestCase,
689 )
Georg Brandlb533e262008-05-25 18:19:30 +0000690 finally:
691 os.chdir(cwd)
692
693if __name__ == '__main__':
694 test_main()