blob: 287ad532e6707b3a99b52868d2eb4e4f529b0f72 [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):
Antoine Pitrou85bd5872009-10-27 18:50:52 +000053 self._threads = test_support.threading_setup()
Nick Coghlan87c03b32009-10-17 15:23:08 +000054 os.environ = test_support.EnvironmentVarGuard()
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Coghlan87c03b32009-10-17 15:23:08 +000063 os.environ.__exit__()
Antoine Pitrou85bd5872009-10-27 18:50:52 +000064 test_support.threading_cleanup(*self._threads)
Georg Brandlf899dfa2008-05-18 09:12:20 +000065
66 def request(self, uri, method='GET', body=None, headers={}):
67 self.connection = httplib.HTTPConnection('localhost', self.PORT)
68 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)
100 self.con = httplib.HTTPConnection('localhost', self.PORT)
101 self.con.connect()
102
103 def test_command(self):
104 self.con.request('GET', '/')
105 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000106 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Xiclunabc27c6a2010-03-19 18:34:55 +0000113 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Xiclunabc27c6a2010-03-19 18:34:55 +0000120 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Xiclunabc27c6a2010-03-19 18:34:55 +0000127 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Xiclunabc27c6a2010-03-19 18:34:55 +0000134 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Xiclunabc27c6a2010-03-19 18:34:55 +0000141 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Xiclunabc27c6a2010-03-19 18:34:55 +0000149 self.assertEqual(res.status, 505)
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Xiclunabc27c6a2010-03-19 18:34:55 +0000156 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Xiclunabc27c6a2010-03-19 18:34:55 +0000163 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Xiclunabc27c6a2010-03-19 18:34:55 +0000171 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000172
173 def test_handler(self):
174 self.con.request('TEST', '/')
175 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000176 self.assertEqual(res.status, 204)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000177
178 def test_return_header_keep_alive(self):
179 self.con.request('KEEP', '/')
180 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000181 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000182 self.con.request('TEST', '/')
183
184 def test_internal_key_error(self):
185 self.con.request('KEYERROR', '/')
186 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000187 self.assertEqual(res.status, 999)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000188
189 def test_return_custom_status(self):
190 self.con.request('CUSTOM', '/')
191 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000192 self.assertEqual(res.status, 999)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000193
194
195class SimpleHTTPServerTestCase(BaseTestCase):
196 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
197 pass
198
199 def setUp(self):
200 BaseTestCase.setUp(self)
Georg Brandl7bb16532008-05-20 06:47:31 +0000201 self.cwd = os.getcwd()
202 basetempdir = tempfile.gettempdir()
203 os.chdir(basetempdir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000204 self.data = 'We are the knights who say Ni!'
Georg Brandl7bb16532008-05-20 06:47:31 +0000205 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000206 self.tempdir_name = os.path.basename(self.tempdir)
Georg Brandl7bb16532008-05-20 06:47:31 +0000207 temp = open(os.path.join(self.tempdir, 'test'), 'wb')
208 temp.write(self.data)
209 temp.close()
Georg Brandlf899dfa2008-05-18 09:12:20 +0000210
211 def tearDown(self):
212 try:
Georg Brandl7bb16532008-05-20 06:47:31 +0000213 os.chdir(self.cwd)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000214 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 Peterson5c8da862009-06-30 22:57:08 +0000223 self.assertTrue(response)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000224 self.assertEqual(response.status, status)
225 self.assertIsNotNone(response.reason)
Georg Brandlf899dfa2008-05-18 09:12:20 +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
Georg Brandl7bb16532008-05-20 06:47:31 +0000231 response = self.request(self.tempdir_name + '/test')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000232 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, 0755)
250
251 def test_head(self):
252 response = self.request(
Georg Brandl7bb16532008-05-20 06:47:31 +0000253 self.tempdir_name + '/test', method='HEAD')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000254 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 Xiclunabc27c6a2010-03-19 18:34:55 +0000286print "%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
287 form.getfirst("bacon"))
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Xicluna0805e6e2010-03-22 17:18:18 +0000300 # The shebang line should be pure ASCII: use symlink if possible.
301 # See issue #7668.
302 if hasattr(os, 'symlink'):
303 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 Brandlf899dfa2008-05-18 09:12:20 +0000308 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
309 with open(self.file1_path, 'w') as file1:
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000310 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000311 os.chmod(self.file1_path, 0777)
312
313 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
314 with open(self.file2_path, 'w') as file2:
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000315 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000316 os.chmod(self.file2_path, 0777)
317
Georg Brandl7bb16532008-05-20 06:47:31 +0000318 self.cwd = os.getcwd()
Georg Brandlf899dfa2008-05-18 09:12:20 +0000319 os.chdir(self.parent_dir)
320
321 def tearDown(self):
322 try:
Georg Brandl7bb16532008-05-20 06:47:31 +0000323 os.chdir(self.cwd)
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000324 if self.pythonexe != sys.executable:
325 os.remove(self.pythonexe)
Georg Brandlf899dfa2008-05-18 09:12:20 +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
Gregory P. Smith923ba362009-04-06 06:33:26 +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.iteritems():
363 if isinstance(expected, type) and issubclass(expected, Exception):
364 self.assertRaises(expected,
365 CGIHTTPServer._url_collapse_path_split, path)
366 else:
367 actual = CGIHTTPServer._url_collapse_path_split(path)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000368 self.assertEqual(expected, actual,
369 msg='path = %r\nGot: %r\nWanted: %r' %
370 (path, actual, expected))
Gregory P. Smith923ba362009-04-06 06:33:26 +0000371
Georg Brandlf899dfa2008-05-18 09:12:20 +0000372 def test_headers_and_content(self):
373 res = self.request('/cgi-bin/file1.py')
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000374 self.assertEqual(('Hello World\n', 'text/html', 200),
375 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlf899dfa2008-05-18 09:12:20 +0000376
377 def test_post(self):
378 params = urllib.urlencode({'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
379 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
380 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
381
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000382 self.assertEqual(res.read(), '1, python, 123456\n')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000383
384 def test_invaliduri(self):
385 res = self.request('/cgi-bin/invalid')
386 res.read()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000387 self.assertEqual(res.status, 404)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000388
389 def test_authorization(self):
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000390 headers = {'Authorization' : 'Basic %s' %
391 base64.b64encode('username:pass')}
Georg Brandlf899dfa2008-05-18 09:12:20 +0000392 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000393 self.assertEqual(('Hello World\n', 'text/html', 200),
394 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlf899dfa2008-05-18 09:12:20 +0000395
Gregory P. Smith923ba362009-04-06 06:33:26 +0000396 def test_no_leading_slash(self):
397 # http://bugs.python.org/issue2254
398 res = self.request('cgi-bin/file1.py')
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000399 self.assertEqual(('Hello World\n', 'text/html', 200),
Gregory P. Smith923ba362009-04-06 06:33:26 +0000400 (res.read(), res.getheader('Content-type'), res.status))
401
Georg Brandlf899dfa2008-05-18 09:12:20 +0000402
403def test_main(verbose=None):
404 try:
405 cwd = os.getcwd()
406 test_support.run_unittest(BaseHTTPServerTestCase,
Nick Coghlan87c03b32009-10-17 15:23:08 +0000407 SimpleHTTPServerTestCase,
408 CGIHTTPServerTestCase
409 )
Georg Brandlf899dfa2008-05-18 09:12:20 +0000410 finally:
411 os.chdir(cwd)
412
413if __name__ == '__main__':
414 test_main()