blob: 4895b650f58dd7dd00f75aa17826c4f985b0cfcb [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
13import base64
14import shutil
Jeremy Hylton1afc1692008-06-18 20:49:58 +000015import urllib.parse
Georg Brandl24420152008-05-26 16:32:26 +000016import http.client
Georg Brandlb533e262008-05-25 18:19:30 +000017import tempfile
Georg Brandlb533e262008-05-25 18:19:30 +000018
19import unittest
20from test import support
Victor Stinner45df8202010-04-28 22:31:17 +000021threading = support.import_module('threading')
Georg Brandlb533e262008-05-25 18:19:30 +000022
Georg Brandlb533e262008-05-25 18:19:30 +000023class NoLogRequestHandler:
24 def log_message(self, *args):
25 # don't write log messages to stderr
26 pass
27
Barry Warsaw820c1202008-06-12 04:06:45 +000028 def read(self, n=None):
29 return ''
30
Georg Brandlb533e262008-05-25 18:19:30 +000031
32class TestServerThread(threading.Thread):
33 def __init__(self, test_object, request_handler):
34 threading.Thread.__init__(self)
35 self.request_handler = request_handler
36 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000037
38 def run(self):
39 self.server = HTTPServer(('', 0), self.request_handler)
40 self.test_object.PORT = self.server.socket.getsockname()[1]
Antoine Pitrou08911bd2010-04-25 22:19:43 +000041 self.test_object.server_started.set()
42 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000043 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000044 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000045 finally:
46 self.server.server_close()
47
48 def stop(self):
49 self.server.shutdown()
50
51
52class BaseTestCase(unittest.TestCase):
53 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000054 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000055 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000056 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000057 self.thread = TestServerThread(self, self.request_handler)
58 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000059 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000060
61 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000062 self.thread.stop()
Nick Coghlan6ead5522009-10-18 13:19:33 +000063 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000064 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000065
66 def request(self, uri, method='GET', body=None, headers={}):
Georg Brandl24420152008-05-26 16:32:26 +000067 self.connection = http.client.HTTPConnection('localhost', self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000068 self.connection.request(method, uri, body, headers)
69 return self.connection.getresponse()
70
71
72class BaseHTTPServerTestCase(BaseTestCase):
73 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
74 protocol_version = 'HTTP/1.1'
75 default_request_version = 'HTTP/1.1'
76
77 def do_TEST(self):
78 self.send_response(204)
79 self.send_header('Content-Type', 'text/html')
80 self.send_header('Connection', 'close')
81 self.end_headers()
82
83 def do_KEEP(self):
84 self.send_response(204)
85 self.send_header('Content-Type', 'text/html')
86 self.send_header('Connection', 'keep-alive')
87 self.end_headers()
88
89 def do_KEYERROR(self):
90 self.send_error(999)
91
92 def do_CUSTOM(self):
93 self.send_response(999)
94 self.send_header('Content-Type', 'text/html')
95 self.send_header('Connection', 'close')
96 self.end_headers()
97
98 def setUp(self):
99 BaseTestCase.setUp(self)
Georg Brandl24420152008-05-26 16:32:26 +0000100 self.con = http.client.HTTPConnection('localhost', self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000101 self.con.connect()
102
103 def test_command(self):
104 self.con.request('GET', '/')
105 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000106 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000107
108 def test_request_line_trimming(self):
109 self.con._http_vsn_str = 'HTTP/1.1\n'
110 self.con.putrequest('GET', '/')
111 self.con.endheaders()
112 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000113 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000114
115 def test_version_bogus(self):
116 self.con._http_vsn_str = 'FUBAR'
117 self.con.putrequest('GET', '/')
118 self.con.endheaders()
119 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000120 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000121
122 def test_version_digits(self):
123 self.con._http_vsn_str = 'HTTP/9.9.9'
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, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000128
129 def test_version_none_get(self):
130 self.con._http_vsn_str = ''
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, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000135
136 def test_version_none(self):
137 self.con._http_vsn_str = ''
138 self.con.putrequest('PUT', '/')
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_invalid(self):
144 self.con._http_vsn = 99
145 self.con._http_vsn_str = 'HTTP/9.9'
146 self.con.putrequest('GET', '/')
147 self.con.endheaders()
148 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000149 self.assertEqual(res.status, 505)
Georg Brandlb533e262008-05-25 18:19:30 +0000150
151 def test_send_blank(self):
152 self.con._http_vsn_str = ''
153 self.con.putrequest('', '')
154 self.con.endheaders()
155 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000156 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000157
158 def test_header_close(self):
159 self.con.putrequest('GET', '/')
160 self.con.putheader('Connection', 'close')
161 self.con.endheaders()
162 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000163 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000164
165 def test_head_keep_alive(self):
166 self.con._http_vsn_str = 'HTTP/1.1'
167 self.con.putrequest('GET', '/')
168 self.con.putheader('Connection', 'keep-alive')
169 self.con.endheaders()
170 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000171 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000172
173 def test_handler(self):
174 self.con.request('TEST', '/')
175 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000176 self.assertEqual(res.status, 204)
Georg Brandlb533e262008-05-25 18:19:30 +0000177
178 def test_return_header_keep_alive(self):
179 self.con.request('KEEP', '/')
180 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000181 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000182 self.con.request('TEST', '/')
183
184 def test_internal_key_error(self):
185 self.con.request('KEYERROR', '/')
186 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000187 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000188
189 def test_return_custom_status(self):
190 self.con.request('CUSTOM', '/')
191 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000192 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000193
194
195class SimpleHTTPServerTestCase(BaseTestCase):
196 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
197 pass
198
199 def setUp(self):
200 BaseTestCase.setUp(self)
201 self.cwd = os.getcwd()
202 basetempdir = tempfile.gettempdir()
203 os.chdir(basetempdir)
204 self.data = b'We are the knights who say Ni!'
205 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
206 self.tempdir_name = os.path.basename(self.tempdir)
207 temp = open(os.path.join(self.tempdir, 'test'), 'wb')
208 temp.write(self.data)
209 temp.close()
210
211 def tearDown(self):
212 try:
213 os.chdir(self.cwd)
214 try:
215 shutil.rmtree(self.tempdir)
216 except:
217 pass
218 finally:
219 BaseTestCase.tearDown(self)
220
221 def check_status_and_reason(self, response, status, data=None):
222 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000223 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000224 self.assertEqual(response.status, status)
225 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000226 if data:
227 self.assertEqual(data, body)
228
229 def test_get(self):
230 #constructs the path relative to the root directory of the HTTPServer
231 response = self.request(self.tempdir_name + '/test')
232 self.check_status_and_reason(response, 200, data=self.data)
233 response = self.request(self.tempdir_name + '/')
234 self.check_status_and_reason(response, 200)
235 response = self.request(self.tempdir_name)
236 self.check_status_and_reason(response, 301)
237 response = self.request('/ThisDoesNotExist')
238 self.check_status_and_reason(response, 404)
239 response = self.request('/' + 'ThisDoesNotExist' + '/')
240 self.check_status_and_reason(response, 404)
241 f = open(os.path.join(self.tempdir_name, 'index.html'), 'w')
242 response = self.request('/' + self.tempdir_name + '/')
243 self.check_status_and_reason(response, 200)
244 if os.name == 'posix':
245 # chmod won't work as expected on Windows platforms
246 os.chmod(self.tempdir, 0)
247 response = self.request(self.tempdir_name + '/')
248 self.check_status_and_reason(response, 404)
249 os.chmod(self.tempdir, 0o755)
250
251 def test_head(self):
252 response = self.request(
253 self.tempdir_name + '/test', method='HEAD')
254 self.check_status_and_reason(response, 200)
255 self.assertEqual(response.getheader('content-length'),
256 str(len(self.data)))
257 self.assertEqual(response.getheader('content-type'),
258 'application/octet-stream')
259
260 def test_invalid_requests(self):
261 response = self.request('/', method='FOO')
262 self.check_status_and_reason(response, 501)
263 # requests must be case sensitive,so this should fail too
264 response = self.request('/', method='get')
265 self.check_status_and_reason(response, 501)
266 response = self.request('/', method='GETs')
267 self.check_status_and_reason(response, 501)
268
269
270cgi_file1 = """\
271#!%s
272
273print("Content-type: text/html")
274print()
275print("Hello World")
276"""
277
278cgi_file2 = """\
279#!%s
280import cgi
281
282print("Content-type: text/html")
283print()
284
285form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000286print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
287 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000288"""
289
290class CGIHTTPServerTestCase(BaseTestCase):
291 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
292 pass
293
294 def setUp(self):
295 BaseTestCase.setUp(self)
296 self.parent_dir = tempfile.mkdtemp()
297 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
298 os.mkdir(self.cgi_dir)
299
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000300 # The shebang line should be pure ASCII: use symlink if possible.
301 # See issue #7668.
Brian Curtind40e6f72010-07-08 21:39:08 +0000302 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000303 self.pythonexe = os.path.join(self.parent_dir, 'python')
304 os.symlink(sys.executable, self.pythonexe)
305 else:
306 self.pythonexe = sys.executable
307
Georg Brandlb533e262008-05-25 18:19:30 +0000308 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
309 with open(self.file1_path, 'w') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000310 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000311 os.chmod(self.file1_path, 0o777)
312
313 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
314 with open(self.file2_path, 'w') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000315 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000316 os.chmod(self.file2_path, 0o777)
317
318 self.cwd = os.getcwd()
319 os.chdir(self.parent_dir)
320
321 def tearDown(self):
322 try:
323 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000324 if self.pythonexe != sys.executable:
325 os.remove(self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000326 os.remove(self.file1_path)
327 os.remove(self.file2_path)
328 os.rmdir(self.cgi_dir)
329 os.rmdir(self.parent_dir)
330 finally:
331 BaseTestCase.tearDown(self)
332
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000333 def test_url_collapse_path_split(self):
334 test_vectors = {
335 '': ('/', ''),
336 '..': IndexError,
337 '/.//..': IndexError,
338 '/': ('/', ''),
339 '//': ('/', ''),
340 '/\\': ('/', '\\'),
341 '/.//': ('/', ''),
342 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
343 '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
344 'a': ('/', 'a'),
345 '/a': ('/', 'a'),
346 '//a': ('/', 'a'),
347 './a': ('/', 'a'),
348 './C:/': ('/C:', ''),
349 '/a/b': ('/a', 'b'),
350 '/a/b/': ('/a/b', ''),
351 '/a/b/c/..': ('/a/b', ''),
352 '/a/b/c/../d': ('/a/b', 'd'),
353 '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
354 '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
355 '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
356 '../a/b/c/../d/e/.././././..//f': IndexError,
357 '/a/b/c/../d/e/../../../f': ('/a', 'f'),
358 '/a/b/c/../d/e/../../../../f': ('/', 'f'),
359 '/a/b/c/../d/e/../../../../../f': IndexError,
360 '/a/b/c/../d/e/../../../../f/..': ('/', ''),
361 }
362 for path, expected in test_vectors.items():
363 if isinstance(expected, type) and issubclass(expected, Exception):
364 self.assertRaises(expected,
365 server._url_collapse_path_split, path)
366 else:
367 actual = server._url_collapse_path_split(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000368 self.assertEqual(expected, actual,
369 msg='path = %r\nGot: %r\nWanted: %r' %
370 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000371
Georg Brandlb533e262008-05-25 18:19:30 +0000372 def test_headers_and_content(self):
373 res = self.request('/cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000374 self.assertEqual((b'Hello World\n', 'text/html', 200),
375 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000376
377 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000378 params = urllib.parse.urlencode(
379 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000380 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
381 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
382
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000383 self.assertEqual(res.read(), b'1, python, 123456\n')
Georg Brandlb533e262008-05-25 18:19:30 +0000384
385 def test_invaliduri(self):
386 res = self.request('/cgi-bin/invalid')
387 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000388 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000389
390 def test_authorization(self):
391 headers = {b'Authorization' : b'Basic ' +
392 base64.b64encode(b'username:pass')}
393 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000394 self.assertEqual((b'Hello World\n', 'text/html', 200),
395 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000396
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000397 def test_no_leading_slash(self):
398 # http://bugs.python.org/issue2254
399 res = self.request('cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000400 self.assertEqual((b'Hello World\n', 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000401 (res.read(), res.getheader('Content-type'), res.status))
402
Georg Brandlb533e262008-05-25 18:19:30 +0000403
404def test_main(verbose=None):
405 try:
406 cwd = os.getcwd()
Georg Brandl24420152008-05-26 16:32:26 +0000407 support.run_unittest(BaseHTTPServerTestCase,
Georg Brandlb533e262008-05-25 18:19:30 +0000408 SimpleHTTPServerTestCase,
409 CGIHTTPServerTestCase
410 )
411 finally:
412 os.chdir(cwd)
413
414if __name__ == '__main__':
415 test_main()