blob: 73354e39543f4fb7b39659e7da66fab4c45093ff [file] [log] [blame]
Georg Brandlf899dfa2008-05-18 09:12:20 +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
7from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
8from SimpleHTTPServer import SimpleHTTPRequestHandler
9from CGIHTTPServer import CGIHTTPRequestHandler
Gregory P. Smith923ba362009-04-06 06:33:26 +000010import CGIHTTPServer
Georg Brandlf899dfa2008-05-18 09:12:20 +000011
12import os
13import sys
14import base64
15import shutil
16import urllib
17import httplib
18import tempfile
19import threading
20
21import unittest
22from test import test_support
23
24
25class NoLogRequestHandler:
26 def log_message(self, *args):
27 # don't write log messages to stderr
28 pass
29
30
31class TestServerThread(threading.Thread):
32 def __init__(self, test_object, request_handler):
33 threading.Thread.__init__(self)
34 self.request_handler = request_handler
35 self.test_object = test_object
36 self.test_object.lock.acquire()
37
38 def run(self):
39 self.server = HTTPServer(('', 0), self.request_handler)
40 self.test_object.PORT = self.server.socket.getsockname()[1]
41 self.test_object.lock.release()
42 try:
43 self.server.serve_forever()
44 finally:
45 self.server.server_close()
46
47 def stop(self):
48 self.server.shutdown()
49
50
51class BaseTestCase(unittest.TestCase):
52 def setUp(self):
Nick Coghlan87c03b32009-10-17 15:23:08 +000053 os.environ = test_support.EnvironmentVarGuard()
Georg Brandlf899dfa2008-05-18 09:12:20 +000054 self.lock = threading.Lock()
55 self.thread = TestServerThread(self, self.request_handler)
56 self.thread.start()
57 self.lock.acquire()
58
59 def tearDown(self):
60 self.lock.release()
61 self.thread.stop()
Nick Coghlan87c03b32009-10-17 15:23:08 +000062 os.environ.__exit__()
63 os.environ = os.environ._environ
Georg Brandlf899dfa2008-05-18 09:12:20 +000064
65 def request(self, uri, method='GET', body=None, headers={}):
66 self.connection = httplib.HTTPConnection('localhost', self.PORT)
67 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)
99 self.con = httplib.HTTPConnection('localhost', self.PORT)
100 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)
Georg Brandl7bb16532008-05-20 06:47:31 +0000200 self.cwd = os.getcwd()
201 basetempdir = tempfile.gettempdir()
202 os.chdir(basetempdir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000203 self.data = 'We are the knights who say Ni!'
Georg Brandl7bb16532008-05-20 06:47:31 +0000204 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000205 self.tempdir_name = os.path.basename(self.tempdir)
Georg Brandl7bb16532008-05-20 06:47:31 +0000206 temp = open(os.path.join(self.tempdir, 'test'), 'wb')
207 temp.write(self.data)
208 temp.close()
Georg Brandlf899dfa2008-05-18 09:12:20 +0000209
210 def tearDown(self):
211 try:
Georg Brandl7bb16532008-05-20 06:47:31 +0000212 os.chdir(self.cwd)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000213 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 Peterson5c8da862009-06-30 22:57:08 +0000222 self.assertTrue(response)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000223 self.assertEquals(response.status, status)
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000224 self.assertTrue(response.reason != None)
Georg Brandlf899dfa2008-05-18 09:12:20 +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
Georg Brandl7bb16532008-05-20 06:47:31 +0000230 response = self.request(self.tempdir_name + '/test')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000231 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, 0755)
249
250 def test_head(self):
251 response = self.request(
Georg Brandl7bb16532008-05-20 06:47:31 +0000252 self.tempdir_name + '/test', method='HEAD')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000253 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()
Georg Brandlb740f6a2008-05-20 06:15:36 +0000285print "%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),\
Georg Brandlf899dfa2008-05-18 09:12:20 +0000286 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, 0777)
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, 0777)
308
Georg Brandl7bb16532008-05-20 06:47:31 +0000309 self.cwd = os.getcwd()
Georg Brandlf899dfa2008-05-18 09:12:20 +0000310 os.chdir(self.parent_dir)
311
312 def tearDown(self):
313 try:
Georg Brandl7bb16532008-05-20 06:47:31 +0000314 os.chdir(self.cwd)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000315 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
Gregory P. Smith923ba362009-04-06 06:33:26 +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.iteritems():
352 if isinstance(expected, type) and issubclass(expected, Exception):
353 self.assertRaises(expected,
354 CGIHTTPServer._url_collapse_path_split, path)
355 else:
356 actual = CGIHTTPServer._url_collapse_path_split(path)
357 self.assertEquals(expected, actual,
358 msg='path = %r\nGot: %r\nWanted: %r' % (
359 path, actual, expected))
360
Georg Brandlf899dfa2008-05-18 09:12:20 +0000361 def test_headers_and_content(self):
362 res = self.request('/cgi-bin/file1.py')
363 self.assertEquals(('Hello World\n', 'text/html', 200), \
364 (res.read(), res.getheader('Content-type'), res.status))
365
366 def test_post(self):
367 params = urllib.urlencode({'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
368 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
369 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
370
371 self.assertEquals(res.read(), '1, python, 123456\n')
372
373 def test_invaliduri(self):
374 res = self.request('/cgi-bin/invalid')
375 res.read()
376 self.assertEquals(res.status, 404)
377
378 def test_authorization(self):
379 headers = {'Authorization' : 'Basic %s' % \
380 base64.b64encode('username:pass')}
381 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
382 self.assertEquals(('Hello World\n', 'text/html', 200), \
383 (res.read(), res.getheader('Content-type'), res.status))
384
Gregory P. Smith923ba362009-04-06 06:33:26 +0000385 def test_no_leading_slash(self):
386 # http://bugs.python.org/issue2254
387 res = self.request('cgi-bin/file1.py')
388 self.assertEquals(('Hello World\n', 'text/html', 200),
389 (res.read(), res.getheader('Content-type'), res.status))
390
Georg Brandlf899dfa2008-05-18 09:12:20 +0000391
392def test_main(verbose=None):
393 try:
394 cwd = os.getcwd()
395 test_support.run_unittest(BaseHTTPServerTestCase,
Nick Coghlan87c03b32009-10-17 15:23:08 +0000396 SimpleHTTPServerTestCase,
397 CGIHTTPServerTestCase
398 )
Georg Brandlf899dfa2008-05-18 09:12:20 +0000399 finally:
400 os.chdir(cwd)
401
402if __name__ == '__main__':
403 test_main()