blob: 9a3d2049594bffa6808fb531d9f33ac3e84c5543 [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):
Nick Coghlan6ead5522009-10-18 13:19:33 +000054 os.environ = support.EnvironmentVarGuard()
Georg Brandlb533e262008-05-25 18:19:30 +000055 self.lock = threading.Lock()
56 self.thread = TestServerThread(self, self.request_handler)
57 self.thread.start()
58 self.lock.acquire()
59
60 def tearDown(self):
61 self.lock.release()
62 self.thread.stop()
Nick Coghlan6ead5522009-10-18 13:19:33 +000063 os.environ.__exit__()
Georg Brandlb533e262008-05-25 18:19:30 +000064
65 def request(self, uri, method='GET', body=None, headers={}):
Georg Brandl24420152008-05-26 16:32:26 +000066 self.connection = http.client.HTTPConnection('localhost', self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000067 self.connection.request(method, uri, body, headers)
68 return self.connection.getresponse()
69
70
71class BaseHTTPServerTestCase(BaseTestCase):
72 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
73 protocol_version = 'HTTP/1.1'
74 default_request_version = 'HTTP/1.1'
75
76 def do_TEST(self):
77 self.send_response(204)
78 self.send_header('Content-Type', 'text/html')
79 self.send_header('Connection', 'close')
80 self.end_headers()
81
82 def do_KEEP(self):
83 self.send_response(204)
84 self.send_header('Content-Type', 'text/html')
85 self.send_header('Connection', 'keep-alive')
86 self.end_headers()
87
88 def do_KEYERROR(self):
89 self.send_error(999)
90
91 def do_CUSTOM(self):
92 self.send_response(999)
93 self.send_header('Content-Type', 'text/html')
94 self.send_header('Connection', 'close')
95 self.end_headers()
96
97 def setUp(self):
98 BaseTestCase.setUp(self)
Georg Brandl24420152008-05-26 16:32:26 +000099 self.con = http.client.HTTPConnection('localhost', self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000100 self.con.connect()
101
102 def test_command(self):
103 self.con.request('GET', '/')
104 res = self.con.getresponse()
105 self.assertEquals(res.status, 501)
106
107 def test_request_line_trimming(self):
108 self.con._http_vsn_str = 'HTTP/1.1\n'
109 self.con.putrequest('GET', '/')
110 self.con.endheaders()
111 res = self.con.getresponse()
112 self.assertEquals(res.status, 501)
113
114 def test_version_bogus(self):
115 self.con._http_vsn_str = 'FUBAR'
116 self.con.putrequest('GET', '/')
117 self.con.endheaders()
118 res = self.con.getresponse()
119 self.assertEquals(res.status, 400)
120
121 def test_version_digits(self):
122 self.con._http_vsn_str = 'HTTP/9.9.9'
123 self.con.putrequest('GET', '/')
124 self.con.endheaders()
125 res = self.con.getresponse()
126 self.assertEquals(res.status, 400)
127
128 def test_version_none_get(self):
129 self.con._http_vsn_str = ''
130 self.con.putrequest('GET', '/')
131 self.con.endheaders()
132 res = self.con.getresponse()
133 self.assertEquals(res.status, 501)
134
135 def test_version_none(self):
136 self.con._http_vsn_str = ''
137 self.con.putrequest('PUT', '/')
138 self.con.endheaders()
139 res = self.con.getresponse()
140 self.assertEquals(res.status, 400)
141
142 def test_version_invalid(self):
143 self.con._http_vsn = 99
144 self.con._http_vsn_str = 'HTTP/9.9'
145 self.con.putrequest('GET', '/')
146 self.con.endheaders()
147 res = self.con.getresponse()
148 self.assertEquals(res.status, 505)
149
150 def test_send_blank(self):
151 self.con._http_vsn_str = ''
152 self.con.putrequest('', '')
153 self.con.endheaders()
154 res = self.con.getresponse()
155 self.assertEquals(res.status, 400)
156
157 def test_header_close(self):
158 self.con.putrequest('GET', '/')
159 self.con.putheader('Connection', 'close')
160 self.con.endheaders()
161 res = self.con.getresponse()
162 self.assertEquals(res.status, 501)
163
164 def test_head_keep_alive(self):
165 self.con._http_vsn_str = 'HTTP/1.1'
166 self.con.putrequest('GET', '/')
167 self.con.putheader('Connection', 'keep-alive')
168 self.con.endheaders()
169 res = self.con.getresponse()
170 self.assertEquals(res.status, 501)
171
172 def test_handler(self):
173 self.con.request('TEST', '/')
174 res = self.con.getresponse()
175 self.assertEquals(res.status, 204)
176
177 def test_return_header_keep_alive(self):
178 self.con.request('KEEP', '/')
179 res = self.con.getresponse()
180 self.assertEquals(res.getheader('Connection'), 'keep-alive')
181 self.con.request('TEST', '/')
182
183 def test_internal_key_error(self):
184 self.con.request('KEYERROR', '/')
185 res = self.con.getresponse()
186 self.assertEquals(res.status, 999)
187
188 def test_return_custom_status(self):
189 self.con.request('CUSTOM', '/')
190 res = self.con.getresponse()
191 self.assertEquals(res.status, 999)
192
193
194class SimpleHTTPServerTestCase(BaseTestCase):
195 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
196 pass
197
198 def setUp(self):
199 BaseTestCase.setUp(self)
200 self.cwd = os.getcwd()
201 basetempdir = tempfile.gettempdir()
202 os.chdir(basetempdir)
203 self.data = b'We are the knights who say Ni!'
204 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
205 self.tempdir_name = os.path.basename(self.tempdir)
206 temp = open(os.path.join(self.tempdir, 'test'), 'wb')
207 temp.write(self.data)
208 temp.close()
209
210 def tearDown(self):
211 try:
212 os.chdir(self.cwd)
213 try:
214 shutil.rmtree(self.tempdir)
215 except:
216 pass
217 finally:
218 BaseTestCase.tearDown(self)
219
220 def check_status_and_reason(self, response, status, data=None):
221 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000222 self.assertTrue(response)
Georg Brandlb533e262008-05-25 18:19:30 +0000223 self.assertEquals(response.status, status)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000224 self.assertTrue(response.reason != None)
Georg Brandlb533e262008-05-25 18:19:30 +0000225 if data:
226 self.assertEqual(data, body)
227
228 def test_get(self):
229 #constructs the path relative to the root directory of the HTTPServer
230 response = self.request(self.tempdir_name + '/test')
231 self.check_status_and_reason(response, 200, data=self.data)
232 response = self.request(self.tempdir_name + '/')
233 self.check_status_and_reason(response, 200)
234 response = self.request(self.tempdir_name)
235 self.check_status_and_reason(response, 301)
236 response = self.request('/ThisDoesNotExist')
237 self.check_status_and_reason(response, 404)
238 response = self.request('/' + 'ThisDoesNotExist' + '/')
239 self.check_status_and_reason(response, 404)
240 f = open(os.path.join(self.tempdir_name, 'index.html'), 'w')
241 response = self.request('/' + self.tempdir_name + '/')
242 self.check_status_and_reason(response, 200)
243 if os.name == 'posix':
244 # chmod won't work as expected on Windows platforms
245 os.chmod(self.tempdir, 0)
246 response = self.request(self.tempdir_name + '/')
247 self.check_status_and_reason(response, 404)
248 os.chmod(self.tempdir, 0o755)
249
250 def test_head(self):
251 response = self.request(
252 self.tempdir_name + '/test', method='HEAD')
253 self.check_status_and_reason(response, 200)
254 self.assertEqual(response.getheader('content-length'),
255 str(len(self.data)))
256 self.assertEqual(response.getheader('content-type'),
257 'application/octet-stream')
258
259 def test_invalid_requests(self):
260 response = self.request('/', method='FOO')
261 self.check_status_and_reason(response, 501)
262 # requests must be case sensitive,so this should fail too
263 response = self.request('/', method='get')
264 self.check_status_and_reason(response, 501)
265 response = self.request('/', method='GETs')
266 self.check_status_and_reason(response, 501)
267
268
269cgi_file1 = """\
270#!%s
271
272print("Content-type: text/html")
273print()
274print("Hello World")
275"""
276
277cgi_file2 = """\
278#!%s
279import cgi
280
281print("Content-type: text/html")
282print()
283
284form = cgi.FieldStorage()
285print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),\
286 form.getfirst("bacon")))
287"""
288
289class CGIHTTPServerTestCase(BaseTestCase):
290 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
291 pass
292
293 def setUp(self):
294 BaseTestCase.setUp(self)
295 self.parent_dir = tempfile.mkdtemp()
296 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
297 os.mkdir(self.cgi_dir)
298
299 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
300 with open(self.file1_path, 'w') as file1:
301 file1.write(cgi_file1 % sys.executable)
302 os.chmod(self.file1_path, 0o777)
303
304 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
305 with open(self.file2_path, 'w') as file2:
306 file2.write(cgi_file2 % sys.executable)
307 os.chmod(self.file2_path, 0o777)
308
309 self.cwd = os.getcwd()
310 os.chdir(self.parent_dir)
311
312 def tearDown(self):
313 try:
314 os.chdir(self.cwd)
315 os.remove(self.file1_path)
316 os.remove(self.file2_path)
317 os.rmdir(self.cgi_dir)
318 os.rmdir(self.parent_dir)
319 finally:
320 BaseTestCase.tearDown(self)
321
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000322 def test_url_collapse_path_split(self):
323 test_vectors = {
324 '': ('/', ''),
325 '..': IndexError,
326 '/.//..': IndexError,
327 '/': ('/', ''),
328 '//': ('/', ''),
329 '/\\': ('/', '\\'),
330 '/.//': ('/', ''),
331 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
332 '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
333 'a': ('/', 'a'),
334 '/a': ('/', 'a'),
335 '//a': ('/', 'a'),
336 './a': ('/', 'a'),
337 './C:/': ('/C:', ''),
338 '/a/b': ('/a', 'b'),
339 '/a/b/': ('/a/b', ''),
340 '/a/b/c/..': ('/a/b', ''),
341 '/a/b/c/../d': ('/a/b', 'd'),
342 '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
343 '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
344 '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
345 '../a/b/c/../d/e/.././././..//f': IndexError,
346 '/a/b/c/../d/e/../../../f': ('/a', 'f'),
347 '/a/b/c/../d/e/../../../../f': ('/', 'f'),
348 '/a/b/c/../d/e/../../../../../f': IndexError,
349 '/a/b/c/../d/e/../../../../f/..': ('/', ''),
350 }
351 for path, expected in test_vectors.items():
352 if isinstance(expected, type) and issubclass(expected, Exception):
353 self.assertRaises(expected,
354 server._url_collapse_path_split, path)
355 else:
356 actual = server._url_collapse_path_split(path)
357 self.assertEquals(expected, actual,
358 msg='path = %r\nGot: %r\nWanted: %r' % (
359 path, actual, expected))
360
Georg Brandlb533e262008-05-25 18:19:30 +0000361 def test_headers_and_content(self):
362 res = self.request('/cgi-bin/file1.py')
363 self.assertEquals((b'Hello World\n', 'text/html', 200), \
364 (res.read(), res.getheader('Content-type'), res.status))
365
366 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000367 params = urllib.parse.urlencode(
368 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000369 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
370 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
371
372 self.assertEquals(res.read(), b'1, python, 123456\n')
373
374 def test_invaliduri(self):
375 res = self.request('/cgi-bin/invalid')
376 res.read()
377 self.assertEquals(res.status, 404)
378
379 def test_authorization(self):
380 headers = {b'Authorization' : b'Basic ' +
381 base64.b64encode(b'username:pass')}
382 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
383 self.assertEquals((b'Hello World\n', 'text/html', 200), \
384 (res.read(), res.getheader('Content-type'), res.status))
385
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000386 def test_no_leading_slash(self):
387 # http://bugs.python.org/issue2254
388 res = self.request('cgi-bin/file1.py')
389 self.assertEquals((b'Hello World\n', 'text/html', 200),
390 (res.read(), res.getheader('Content-type'), res.status))
391
Georg Brandlb533e262008-05-25 18:19:30 +0000392
393def test_main(verbose=None):
394 try:
395 cwd = os.getcwd()
Georg Brandl24420152008-05-26 16:32:26 +0000396 support.run_unittest(BaseHTTPServerTestCase,
Georg Brandlb533e262008-05-25 18:19:30 +0000397 SimpleHTTPServerTestCase,
398 CGIHTTPServerTestCase
399 )
400 finally:
401 os.chdir(cwd)
402
403if __name__ == '__main__':
404 test_main()