blob: bed55e815366360699b21f491cef05c427da59a7 [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
95 def do_CUSTOM(self):
96 self.send_response(999)
97 self.send_header('Content-Type', 'text/html')
98 self.send_header('Connection', 'close')
99 self.end_headers()
100
Armin Ronacher8d96d772011-01-22 13:13:05 +0000101 def do_LATINONEHEADER(self):
102 self.send_response(999)
103 self.send_header('X-Special', 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000104 self.send_header('Connection', 'close')
Armin Ronacher8d96d772011-01-22 13:13:05 +0000105 self.end_headers()
Armin Ronacher59531282011-01-22 13:44:22 +0000106 body = self.headers['x-special-incoming'].encode('utf-8')
107 self.wfile.write(body)
Armin Ronacher8d96d772011-01-22 13:13:05 +0000108
Georg Brandlb533e262008-05-25 18:19:30 +0000109 def setUp(self):
110 BaseTestCase.setUp(self)
Antoine Pitroucb342182011-03-21 00:26:51 +0100111 self.con = http.client.HTTPConnection(self.HOST, self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000112 self.con.connect()
113
114 def test_command(self):
115 self.con.request('GET', '/')
116 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000117 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000118
119 def test_request_line_trimming(self):
120 self.con._http_vsn_str = 'HTTP/1.1\n'
121 self.con.putrequest('GET', '/')
122 self.con.endheaders()
123 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000124 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000125
126 def test_version_bogus(self):
127 self.con._http_vsn_str = 'FUBAR'
128 self.con.putrequest('GET', '/')
129 self.con.endheaders()
130 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000131 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000132
133 def test_version_digits(self):
134 self.con._http_vsn_str = 'HTTP/9.9.9'
135 self.con.putrequest('GET', '/')
136 self.con.endheaders()
137 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000138 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000139
140 def test_version_none_get(self):
141 self.con._http_vsn_str = ''
142 self.con.putrequest('GET', '/')
143 self.con.endheaders()
144 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000145 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000146
147 def test_version_none(self):
148 self.con._http_vsn_str = ''
149 self.con.putrequest('PUT', '/')
150 self.con.endheaders()
151 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000152 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000153
154 def test_version_invalid(self):
155 self.con._http_vsn = 99
156 self.con._http_vsn_str = 'HTTP/9.9'
157 self.con.putrequest('GET', '/')
158 self.con.endheaders()
159 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000160 self.assertEqual(res.status, 505)
Georg Brandlb533e262008-05-25 18:19:30 +0000161
162 def test_send_blank(self):
163 self.con._http_vsn_str = ''
164 self.con.putrequest('', '')
165 self.con.endheaders()
166 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000167 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000168
169 def test_header_close(self):
170 self.con.putrequest('GET', '/')
171 self.con.putheader('Connection', 'close')
172 self.con.endheaders()
173 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000174 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000175
176 def test_head_keep_alive(self):
177 self.con._http_vsn_str = 'HTTP/1.1'
178 self.con.putrequest('GET', '/')
179 self.con.putheader('Connection', 'keep-alive')
180 self.con.endheaders()
181 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000182 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000183
184 def test_handler(self):
185 self.con.request('TEST', '/')
186 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000187 self.assertEqual(res.status, 204)
Georg Brandlb533e262008-05-25 18:19:30 +0000188
189 def test_return_header_keep_alive(self):
190 self.con.request('KEEP', '/')
191 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000192 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000193 self.con.request('TEST', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000194 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000195
196 def test_internal_key_error(self):
197 self.con.request('KEYERROR', '/')
198 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000199 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000200
201 def test_return_custom_status(self):
202 self.con.request('CUSTOM', '/')
203 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000204 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000205
Armin Ronacher8d96d772011-01-22 13:13:05 +0000206 def test_latin1_header(self):
Armin Ronacher59531282011-01-22 13:44:22 +0000207 self.con.request('LATINONEHEADER', '/', headers={
208 'X-Special-Incoming': 'Ärger mit Unicode'
209 })
Armin Ronacher8d96d772011-01-22 13:13:05 +0000210 res = self.con.getresponse()
211 self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
Armin Ronacher59531282011-01-22 13:44:22 +0000212 self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
Armin Ronacher8d96d772011-01-22 13:13:05 +0000213
Georg Brandlb533e262008-05-25 18:19:30 +0000214
215class SimpleHTTPServerTestCase(BaseTestCase):
216 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
217 pass
218
219 def setUp(self):
220 BaseTestCase.setUp(self)
221 self.cwd = os.getcwd()
222 basetempdir = tempfile.gettempdir()
223 os.chdir(basetempdir)
224 self.data = b'We are the knights who say Ni!'
225 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
226 self.tempdir_name = os.path.basename(self.tempdir)
Brett Cannon105df5d2010-10-29 23:43:42 +0000227 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
228 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000229
230 def tearDown(self):
231 try:
232 os.chdir(self.cwd)
233 try:
234 shutil.rmtree(self.tempdir)
235 except:
236 pass
237 finally:
238 BaseTestCase.tearDown(self)
239
240 def check_status_and_reason(self, response, status, data=None):
241 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000242 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000243 self.assertEqual(response.status, status)
244 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000245 if data:
246 self.assertEqual(data, body)
247
248 def test_get(self):
249 #constructs the path relative to the root directory of the HTTPServer
250 response = self.request(self.tempdir_name + '/test')
251 self.check_status_and_reason(response, 200, data=self.data)
252 response = self.request(self.tempdir_name + '/')
253 self.check_status_and_reason(response, 200)
254 response = self.request(self.tempdir_name)
255 self.check_status_and_reason(response, 301)
256 response = self.request('/ThisDoesNotExist')
257 self.check_status_and_reason(response, 404)
258 response = self.request('/' + 'ThisDoesNotExist' + '/')
259 self.check_status_and_reason(response, 404)
Brett Cannon105df5d2010-10-29 23:43:42 +0000260 with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as f:
261 response = self.request('/' + self.tempdir_name + '/')
262 self.check_status_and_reason(response, 200)
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100263 # chmod() doesn't work as expected on Windows, and filesystem
264 # permissions are ignored by root on Unix.
265 if os.name == 'posix' and os.geteuid() != 0:
Brett Cannon105df5d2010-10-29 23:43:42 +0000266 os.chmod(self.tempdir, 0)
267 response = self.request(self.tempdir_name + '/')
268 self.check_status_and_reason(response, 404)
269 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000270
271 def test_head(self):
272 response = self.request(
273 self.tempdir_name + '/test', method='HEAD')
274 self.check_status_and_reason(response, 200)
275 self.assertEqual(response.getheader('content-length'),
276 str(len(self.data)))
277 self.assertEqual(response.getheader('content-type'),
278 'application/octet-stream')
279
280 def test_invalid_requests(self):
281 response = self.request('/', method='FOO')
282 self.check_status_and_reason(response, 501)
283 # requests must be case sensitive,so this should fail too
284 response = self.request('/', method='get')
285 self.check_status_and_reason(response, 501)
286 response = self.request('/', method='GETs')
287 self.check_status_and_reason(response, 501)
288
289
290cgi_file1 = """\
291#!%s
292
293print("Content-type: text/html")
294print()
295print("Hello World")
296"""
297
298cgi_file2 = """\
299#!%s
300import cgi
301
302print("Content-type: text/html")
303print()
304
305form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000306print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
307 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000308"""
309
Charles-François Natalif7ed9fc2011-11-02 19:35:14 +0100310
311@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
312 "This test can't be run reliably as root (issue #13308).")
Georg Brandlb533e262008-05-25 18:19:30 +0000313class CGIHTTPServerTestCase(BaseTestCase):
314 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
315 pass
316
Antoine Pitroue768c392012-08-05 14:52:45 +0200317 linesep = os.linesep.encode('ascii')
318
Georg Brandlb533e262008-05-25 18:19:30 +0000319 def setUp(self):
320 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000321 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000322 self.parent_dir = tempfile.mkdtemp()
323 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
324 os.mkdir(self.cgi_dir)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400325 self.nocgi_path = None
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000326 self.file1_path = None
327 self.file2_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000328
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000329 # The shebang line should be pure ASCII: use symlink if possible.
330 # See issue #7668.
Brian Curtin3b4499c2010-12-28 14:31:47 +0000331 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000332 self.pythonexe = os.path.join(self.parent_dir, 'python')
333 os.symlink(sys.executable, self.pythonexe)
334 else:
335 self.pythonexe = sys.executable
336
Victor Stinner3218c312010-10-17 20:13:36 +0000337 try:
338 # The python executable path is written as the first line of the
339 # CGI Python script. The encoding cookie cannot be used, and so the
340 # path should be encodable to the default script encoding (utf-8)
341 self.pythonexe.encode('utf-8')
342 except UnicodeEncodeError:
343 self.tearDown()
Serhiy Storchaka0b4591e2013-02-04 15:45:00 +0200344 self.skipTest("Python executable path is not encodable to utf-8")
Victor Stinner3218c312010-10-17 20:13:36 +0000345
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400346 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
347 with open(self.nocgi_path, 'w') as fp:
348 fp.write(cgi_file1 % self.pythonexe)
349 os.chmod(self.nocgi_path, 0o777)
350
Georg Brandlb533e262008-05-25 18:19:30 +0000351 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000352 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000353 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000354 os.chmod(self.file1_path, 0o777)
355
356 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000357 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000358 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000359 os.chmod(self.file2_path, 0o777)
360
Georg Brandlb533e262008-05-25 18:19:30 +0000361 os.chdir(self.parent_dir)
362
363 def tearDown(self):
364 try:
365 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000366 if self.pythonexe != sys.executable:
367 os.remove(self.pythonexe)
Benjamin Peterson35aca892013-10-30 12:48:59 -0400368 if self.nocgi_path:
369 os.remove(self.nocgi_path)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000370 if self.file1_path:
371 os.remove(self.file1_path)
372 if self.file2_path:
373 os.remove(self.file2_path)
Georg Brandlb533e262008-05-25 18:19:30 +0000374 os.rmdir(self.cgi_dir)
375 os.rmdir(self.parent_dir)
376 finally:
377 BaseTestCase.tearDown(self)
378
Senthil Kumarand70846b2012-04-12 02:34:32 +0800379 def test_url_collapse_path(self):
380 # verify tail is the last portion and head is the rest on proper urls
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000381 test_vectors = {
Senthil Kumarand70846b2012-04-12 02:34:32 +0800382 '': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000383 '..': IndexError,
384 '/.//..': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800385 '/': '//',
386 '//': '//',
387 '/\\': '//\\',
388 '/.//': '//',
389 'cgi-bin/file1.py': '/cgi-bin/file1.py',
390 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
391 'a': '//a',
392 '/a': '//a',
393 '//a': '//a',
394 './a': '//a',
395 './C:/': '/C:/',
396 '/a/b': '/a/b',
397 '/a/b/': '/a/b/',
398 '/a/b/.': '/a/b/',
399 '/a/b/c/..': '/a/b/',
400 '/a/b/c/../d': '/a/b/d',
401 '/a/b/c/../d/e/../f': '/a/b/d/f',
402 '/a/b/c/../d/e/../../f': '/a/b/f',
403 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000404 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800405 '/a/b/c/../d/e/../../../f': '/a/f',
406 '/a/b/c/../d/e/../../../../f': '//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/..': '//',
409 '/a/b/c/../d/e/../../../../f/../.': '//',
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000410 }
411 for path, expected in test_vectors.items():
412 if isinstance(expected, type) and issubclass(expected, Exception):
413 self.assertRaises(expected,
Senthil Kumarand70846b2012-04-12 02:34:32 +0800414 server._url_collapse_path, path)
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000415 else:
Senthil Kumarand70846b2012-04-12 02:34:32 +0800416 actual = server._url_collapse_path(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000417 self.assertEqual(expected, actual,
418 msg='path = %r\nGot: %r\nWanted: %r' %
419 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000420
Georg Brandlb533e262008-05-25 18:19:30 +0000421 def test_headers_and_content(self):
422 res = self.request('/cgi-bin/file1.py')
Antoine Pitroue768c392012-08-05 14:52:45 +0200423 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000424 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000425
Benjamin Peterson04e9de42013-10-30 12:43:09 -0400426 def test_issue19435(self):
427 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
428 self.assertEqual(res.status, 404)
429
Georg Brandlb533e262008-05-25 18:19:30 +0000430 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
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700464 def test_urlquote_decoding_in_cgi_check(self):
465 res = self.request('/cgi-bin%2ffile1.py')
Benjamin Peterson314dc122014-06-16 23:15:50 -0700466 self.assertEqual((b'Hello World' + self.linesep, 'text/html', 200),
Benjamin Peterson73b8b1c2014-06-14 18:36:29 -0700467 (res.read(), res.getheader('Content-type'), res.status))
468
Georg Brandlb533e262008-05-25 18:19:30 +0000469
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000470class SocketlessRequestHandler(SimpleHTTPRequestHandler):
471 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000472 self.get_called = False
473 self.protocol_version = "HTTP/1.1"
474
475 def do_GET(self):
476 self.get_called = True
477 self.send_response(200)
478 self.send_header('Content-Type', 'text/html')
479 self.end_headers()
480 self.wfile.write(b'<html><body>Data</body></html>\r\n')
481
482 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000483 pass
484
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000485class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
486 def handle_expect_100(self):
487 self.send_error(417)
488 return False
489
490class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melotti3b3499b2011-03-16 11:35:38 +0200491 """Test the functionality of the BaseHTTPServer.
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000492
493 Test the support for the Expect 100-continue header.
494 """
495
496 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
497
498 def setUp (self):
499 self.handler = SocketlessRequestHandler()
500
501 def send_typical_request(self, message):
502 input = BytesIO(message)
503 output = BytesIO()
504 self.handler.rfile = input
505 self.handler.wfile = output
506 self.handler.handle_one_request()
507 output.seek(0)
508 return output.readlines()
509
510 def verify_get_called(self):
511 self.assertTrue(self.handler.get_called)
512
513 def verify_expected_headers(self, headers):
514 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
515 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
516
517 def verify_http_server_response(self, response):
518 match = self.HTTPResponseMatch.search(response)
519 self.assertTrue(match is not None)
520
521 def test_http_1_1(self):
522 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
523 self.verify_http_server_response(result[0])
524 self.verify_expected_headers(result[1:-1])
525 self.verify_get_called()
526 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
527
528 def test_http_1_0(self):
529 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
530 self.verify_http_server_response(result[0])
531 self.verify_expected_headers(result[1:-1])
532 self.verify_get_called()
533 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
534
535 def test_http_0_9(self):
536 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
537 self.assertEqual(len(result), 1)
538 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
539 self.verify_get_called()
540
541 def test_with_continue_1_0(self):
542 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
543 self.verify_http_server_response(result[0])
544 self.verify_expected_headers(result[1:-1])
545 self.verify_get_called()
546 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
547
548 def test_with_continue_1_1(self):
549 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
550 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
551 self.assertEqual(result[1], b'HTTP/1.1 200 OK\r\n')
552 self.verify_expected_headers(result[2:-1])
553 self.verify_get_called()
554 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
555
Senthil Kumarane4dad4f2010-11-21 14:36:14 +0000556 def test_header_buffering(self):
557
558 def _readAndReseek(f):
559 pos = f.tell()
560 f.seek(0)
561 data = f.read()
562 f.seek(pos)
563 return data
564
565 input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
566 output = BytesIO()
567 self.handler.rfile = input
568 self.handler.wfile = output
569 self.handler.request_version = 'HTTP/1.1'
570
571 self.handler.send_header('Foo', 'foo')
572 self.handler.send_header('bar', 'bar')
573 self.assertEqual(_readAndReseek(output), b'')
574 self.handler.end_headers()
575 self.assertEqual(_readAndReseek(output),
576 b'Foo: foo\r\nbar: bar\r\n\r\n')
577
578 def test_header_unbuffered_when_continue(self):
579
580 def _readAndReseek(f):
581 pos = f.tell()
582 f.seek(0)
583 data = f.read()
584 f.seek(pos)
585 return data
586
587 input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
588 output = BytesIO()
589 self.handler.rfile = input
590 self.handler.wfile = output
591 self.handler.request_version = 'HTTP/1.1'
592
593 self.handler.handle_one_request()
594 self.assertNotEqual(_readAndReseek(output), b'')
595 result = _readAndReseek(output).split(b'\r\n')
596 self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
597 self.assertEqual(result[1], b'HTTP/1.1 200 OK')
598
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000599 def test_with_continue_rejected(self):
600 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
601 self.handler = RejectingSocketlessRequestHandler()
602 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
603 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
604 self.verify_expected_headers(result[1:-1])
605 # The expect handler should short circuit the usual get method by
606 # returning false here, so get_called should be false
607 self.assertFalse(self.handler.get_called)
608 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
609 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
610
Antoine Pitrouc4924372010-12-16 16:48:36 +0000611 def test_request_length(self):
612 # Issue #10714: huge request lines are discarded, to avoid Denial
613 # of Service attacks.
614 result = self.send_typical_request(b'GET ' + b'x' * 65537)
615 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
616 self.assertFalse(self.handler.get_called)
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000617
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000618 def test_header_length(self):
619 # Issue #6791: same for headers
620 result = self.send_typical_request(
621 b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
622 self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
623 self.assertFalse(self.handler.get_called)
624
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000625class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
626 """ Test url parsing """
627 def setUp(self):
628 self.translated = os.getcwd()
629 self.translated = os.path.join(self.translated, 'filename')
630 self.handler = SocketlessRequestHandler()
631
632 def test_query_arguments(self):
633 path = self.handler.translate_path('/filename')
634 self.assertEqual(path, self.translated)
635 path = self.handler.translate_path('/filename?foo=bar')
636 self.assertEqual(path, self.translated)
637 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
638 self.assertEqual(path, self.translated)
639
640 def test_start_with_double_slash(self):
641 path = self.handler.translate_path('//filename')
642 self.assertEqual(path, self.translated)
643 path = self.handler.translate_path('//filename?foo=bar')
644 self.assertEqual(path, self.translated)
645
646
Georg Brandlb533e262008-05-25 18:19:30 +0000647def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000648 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000649 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000650 support.run_unittest(
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000651 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000652 BaseHTTPServerTestCase,
653 SimpleHTTPServerTestCase,
654 CGIHTTPServerTestCase,
655 SimpleHTTPRequestHandlerTestCase,
656 )
Georg Brandlb533e262008-05-25 18:19:30 +0000657 finally:
658 os.chdir(cwd)
659
660if __name__ == '__main__':
661 test_main()