blob: 6cf5e3e781ba3d2d5d8d1016f7b21f9ba982e0f1 [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
18import threading
19
20import unittest
21from test import support
22
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
37 self.test_object.lock.acquire()
38
39 def run(self):
40 self.server = HTTPServer(('', 0), self.request_handler)
41 self.test_object.PORT = self.server.socket.getsockname()[1]
42 self.test_object.lock.release()
43 try:
44 self.server.serve_forever()
45 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()
Georg Brandlb533e262008-05-25 18:19:30 +000056 self.lock = threading.Lock()
57 self.thread = TestServerThread(self, self.request_handler)
58 self.thread.start()
59 self.lock.acquire()
60
61 def tearDown(self):
62 self.lock.release()
63 self.thread.stop()
Nick Coghlan6ead5522009-10-18 13:19:33 +000064 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000065 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000066
67 def request(self, uri, method='GET', body=None, headers={}):
Georg Brandl24420152008-05-26 16:32:26 +000068 self.connection = http.client.HTTPConnection('localhost', self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000069 self.connection.request(method, uri, body, headers)
70 return self.connection.getresponse()
71
72
73class BaseHTTPServerTestCase(BaseTestCase):
74 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
75 protocol_version = 'HTTP/1.1'
76 default_request_version = 'HTTP/1.1'
77
78 def do_TEST(self):
79 self.send_response(204)
80 self.send_header('Content-Type', 'text/html')
81 self.send_header('Connection', 'close')
82 self.end_headers()
83
84 def do_KEEP(self):
85 self.send_response(204)
86 self.send_header('Content-Type', 'text/html')
87 self.send_header('Connection', 'keep-alive')
88 self.end_headers()
89
90 def do_KEYERROR(self):
91 self.send_error(999)
92
93 def do_CUSTOM(self):
94 self.send_response(999)
95 self.send_header('Content-Type', 'text/html')
96 self.send_header('Connection', 'close')
97 self.end_headers()
98
99 def setUp(self):
100 BaseTestCase.setUp(self)
Georg Brandl24420152008-05-26 16:32:26 +0000101 self.con = http.client.HTTPConnection('localhost', self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000102 self.con.connect()
103
104 def test_command(self):
105 self.con.request('GET', '/')
106 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000107 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000108
109 def test_request_line_trimming(self):
110 self.con._http_vsn_str = 'HTTP/1.1\n'
111 self.con.putrequest('GET', '/')
112 self.con.endheaders()
113 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000114 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000115
116 def test_version_bogus(self):
117 self.con._http_vsn_str = 'FUBAR'
118 self.con.putrequest('GET', '/')
119 self.con.endheaders()
120 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000121 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000122
123 def test_version_digits(self):
124 self.con._http_vsn_str = 'HTTP/9.9.9'
125 self.con.putrequest('GET', '/')
126 self.con.endheaders()
127 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000128 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000129
130 def test_version_none_get(self):
131 self.con._http_vsn_str = ''
132 self.con.putrequest('GET', '/')
133 self.con.endheaders()
134 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000135 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000136
137 def test_version_none(self):
138 self.con._http_vsn_str = ''
139 self.con.putrequest('PUT', '/')
140 self.con.endheaders()
141 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000142 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000143
144 def test_version_invalid(self):
145 self.con._http_vsn = 99
146 self.con._http_vsn_str = 'HTTP/9.9'
147 self.con.putrequest('GET', '/')
148 self.con.endheaders()
149 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000150 self.assertEqual(res.status, 505)
Georg Brandlb533e262008-05-25 18:19:30 +0000151
152 def test_send_blank(self):
153 self.con._http_vsn_str = ''
154 self.con.putrequest('', '')
155 self.con.endheaders()
156 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000157 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000158
159 def test_header_close(self):
160 self.con.putrequest('GET', '/')
161 self.con.putheader('Connection', 'close')
162 self.con.endheaders()
163 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000164 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000165
166 def test_head_keep_alive(self):
167 self.con._http_vsn_str = 'HTTP/1.1'
168 self.con.putrequest('GET', '/')
169 self.con.putheader('Connection', 'keep-alive')
170 self.con.endheaders()
171 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000172 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000173
174 def test_handler(self):
175 self.con.request('TEST', '/')
176 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000177 self.assertEqual(res.status, 204)
Georg Brandlb533e262008-05-25 18:19:30 +0000178
179 def test_return_header_keep_alive(self):
180 self.con.request('KEEP', '/')
181 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000182 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000183 self.con.request('TEST', '/')
184
185 def test_internal_key_error(self):
186 self.con.request('KEYERROR', '/')
187 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000188 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000189
190 def test_return_custom_status(self):
191 self.con.request('CUSTOM', '/')
192 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000193 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000194
195
196class SimpleHTTPServerTestCase(BaseTestCase):
197 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
198 pass
199
200 def setUp(self):
201 BaseTestCase.setUp(self)
202 self.cwd = os.getcwd()
203 basetempdir = tempfile.gettempdir()
204 os.chdir(basetempdir)
205 self.data = b'We are the knights who say Ni!'
206 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
207 self.tempdir_name = os.path.basename(self.tempdir)
208 temp = open(os.path.join(self.tempdir, 'test'), 'wb')
209 temp.write(self.data)
210 temp.close()
211
212 def tearDown(self):
213 try:
214 os.chdir(self.cwd)
215 try:
216 shutil.rmtree(self.tempdir)
217 except:
218 pass
219 finally:
220 BaseTestCase.tearDown(self)
221
222 def check_status_and_reason(self, response, status, data=None):
223 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000224 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000225 self.assertEqual(response.status, status)
226 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000227 if data:
228 self.assertEqual(data, body)
229
230 def test_get(self):
231 #constructs the path relative to the root directory of the HTTPServer
232 response = self.request(self.tempdir_name + '/test')
233 self.check_status_and_reason(response, 200, data=self.data)
234 response = self.request(self.tempdir_name + '/')
235 self.check_status_and_reason(response, 200)
236 response = self.request(self.tempdir_name)
237 self.check_status_and_reason(response, 301)
238 response = self.request('/ThisDoesNotExist')
239 self.check_status_and_reason(response, 404)
240 response = self.request('/' + 'ThisDoesNotExist' + '/')
241 self.check_status_and_reason(response, 404)
242 f = open(os.path.join(self.tempdir_name, 'index.html'), 'w')
243 response = self.request('/' + self.tempdir_name + '/')
244 self.check_status_and_reason(response, 200)
245 if os.name == 'posix':
246 # chmod won't work as expected on Windows platforms
247 os.chmod(self.tempdir, 0)
248 response = self.request(self.tempdir_name + '/')
249 self.check_status_and_reason(response, 404)
250 os.chmod(self.tempdir, 0o755)
251
252 def test_head(self):
253 response = self.request(
254 self.tempdir_name + '/test', method='HEAD')
255 self.check_status_and_reason(response, 200)
256 self.assertEqual(response.getheader('content-length'),
257 str(len(self.data)))
258 self.assertEqual(response.getheader('content-type'),
259 'application/octet-stream')
260
261 def test_invalid_requests(self):
262 response = self.request('/', method='FOO')
263 self.check_status_and_reason(response, 501)
264 # requests must be case sensitive,so this should fail too
265 response = self.request('/', method='get')
266 self.check_status_and_reason(response, 501)
267 response = self.request('/', method='GETs')
268 self.check_status_and_reason(response, 501)
269
270
271cgi_file1 = """\
272#!%s
273
274print("Content-type: text/html")
275print()
276print("Hello World")
277"""
278
279cgi_file2 = """\
280#!%s
281import cgi
282
283print("Content-type: text/html")
284print()
285
286form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000287print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
288 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000289"""
290
291class CGIHTTPServerTestCase(BaseTestCase):
292 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
293 pass
294
295 def setUp(self):
296 BaseTestCase.setUp(self)
297 self.parent_dir = tempfile.mkdtemp()
298 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
299 os.mkdir(self.cgi_dir)
300
301 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
302 with open(self.file1_path, 'w') as file1:
303 file1.write(cgi_file1 % sys.executable)
304 os.chmod(self.file1_path, 0o777)
305
306 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
307 with open(self.file2_path, 'w') as file2:
308 file2.write(cgi_file2 % sys.executable)
309 os.chmod(self.file2_path, 0o777)
310
311 self.cwd = os.getcwd()
312 os.chdir(self.parent_dir)
313
314 def tearDown(self):
315 try:
316 os.chdir(self.cwd)
317 os.remove(self.file1_path)
318 os.remove(self.file2_path)
319 os.rmdir(self.cgi_dir)
320 os.rmdir(self.parent_dir)
321 finally:
322 BaseTestCase.tearDown(self)
323
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000324 def test_url_collapse_path_split(self):
325 test_vectors = {
326 '': ('/', ''),
327 '..': IndexError,
328 '/.//..': IndexError,
329 '/': ('/', ''),
330 '//': ('/', ''),
331 '/\\': ('/', '\\'),
332 '/.//': ('/', ''),
333 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
334 '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
335 'a': ('/', 'a'),
336 '/a': ('/', 'a'),
337 '//a': ('/', 'a'),
338 './a': ('/', 'a'),
339 './C:/': ('/C:', ''),
340 '/a/b': ('/a', 'b'),
341 '/a/b/': ('/a/b', ''),
342 '/a/b/c/..': ('/a/b', ''),
343 '/a/b/c/../d': ('/a/b', 'd'),
344 '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
345 '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
346 '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
347 '../a/b/c/../d/e/.././././..//f': IndexError,
348 '/a/b/c/../d/e/../../../f': ('/a', 'f'),
349 '/a/b/c/../d/e/../../../../f': ('/', 'f'),
350 '/a/b/c/../d/e/../../../../../f': IndexError,
351 '/a/b/c/../d/e/../../../../f/..': ('/', ''),
352 }
353 for path, expected in test_vectors.items():
354 if isinstance(expected, type) and issubclass(expected, Exception):
355 self.assertRaises(expected,
356 server._url_collapse_path_split, path)
357 else:
358 actual = server._url_collapse_path_split(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000359 self.assertEqual(expected, actual,
360 msg='path = %r\nGot: %r\nWanted: %r' %
361 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000362
Georg Brandlb533e262008-05-25 18:19:30 +0000363 def test_headers_and_content(self):
364 res = self.request('/cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000365 self.assertEqual((b'Hello World\n', 'text/html', 200),
366 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000367
368 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000369 params = urllib.parse.urlencode(
370 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000371 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
372 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
373
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000374 self.assertEqual(res.read(), b'1, python, 123456\n')
Georg Brandlb533e262008-05-25 18:19:30 +0000375
376 def test_invaliduri(self):
377 res = self.request('/cgi-bin/invalid')
378 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000379 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000380
381 def test_authorization(self):
382 headers = {b'Authorization' : b'Basic ' +
383 base64.b64encode(b'username:pass')}
384 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000385 self.assertEqual((b'Hello World\n', 'text/html', 200),
386 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000387
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000388 def test_no_leading_slash(self):
389 # http://bugs.python.org/issue2254
390 res = self.request('cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000391 self.assertEqual((b'Hello World\n', 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000392 (res.read(), res.getheader('Content-type'), res.status))
393
Georg Brandlb533e262008-05-25 18:19:30 +0000394
395def test_main(verbose=None):
396 try:
397 cwd = os.getcwd()
Georg Brandl24420152008-05-26 16:32:26 +0000398 support.run_unittest(BaseHTTPServerTestCase,
Georg Brandlb533e262008-05-25 18:19:30 +0000399 SimpleHTTPServerTestCase,
400 CGIHTTPServerTestCase
401 )
402 finally:
403 os.chdir(cwd)
404
405if __name__ == '__main__':
406 test_main()