blob: e392aeedfec02b57700f58bd5df3daba9f27afe3 [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
Georg Brandlf899dfa2008-05-18 09:12:20 +000036
37 def run(self):
38 self.server = HTTPServer(('', 0), self.request_handler)
39 self.test_object.PORT = self.server.socket.getsockname()[1]
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000040 self.test_object.server_started.set()
41 self.test_object = None
Georg Brandlf899dfa2008-05-18 09:12:20 +000042 try:
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000043 self.server.serve_forever(0.05)
Georg Brandlf899dfa2008-05-18 09:12:20 +000044 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()
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000055 self.server_started = threading.Event()
Georg Brandlf899dfa2008-05-18 09:12:20 +000056 self.thread = TestServerThread(self, self.request_handler)
57 self.thread.start()
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000058 self.server_started.wait()
Georg Brandlf899dfa2008-05-18 09:12:20 +000059
60 def tearDown(self):
Georg Brandlf899dfa2008-05-18 09:12:20 +000061 self.thread.stop()
Nick Coghlan87c03b32009-10-17 15:23:08 +000062 os.environ.__exit__()
Antoine Pitrou85bd5872009-10-27 18:50:52 +000063 test_support.threading_cleanup(*self._threads)
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()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000105 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000106
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()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000112 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000113
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()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000119 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000120
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()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000126 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000127
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()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000133 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000134
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()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000140 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000141
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()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000148 self.assertEqual(res.status, 505)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000149
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()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000155 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000156
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()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000162 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000163
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()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000170 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000171
172 def test_handler(self):
173 self.con.request('TEST', '/')
174 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000175 self.assertEqual(res.status, 204)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000176
177 def test_return_header_keep_alive(self):
178 self.con.request('KEEP', '/')
179 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000180 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000181 self.con.request('TEST', '/')
182
183 def test_internal_key_error(self):
184 self.con.request('KEYERROR', '/')
185 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000186 self.assertEqual(res.status, 999)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000187
188 def test_return_custom_status(self):
189 self.con.request('CUSTOM', '/')
190 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000191 self.assertEqual(res.status, 999)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000192
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)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000223 self.assertEqual(response.status, status)
224 self.assertIsNotNone(response.reason)
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()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000285print "%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
286 form.getfirst("bacon"))
Georg Brandlf899dfa2008-05-18 09:12:20 +0000287"""
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
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000299 # The shebang line should be pure ASCII: use symlink if possible.
300 # See issue #7668.
301 if hasattr(os, 'symlink'):
302 self.pythonexe = os.path.join(self.parent_dir, 'python')
303 os.symlink(sys.executable, self.pythonexe)
304 else:
305 self.pythonexe = sys.executable
306
Georg Brandlf899dfa2008-05-18 09:12:20 +0000307 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
308 with open(self.file1_path, 'w') as file1:
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000309 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000310 os.chmod(self.file1_path, 0777)
311
312 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
313 with open(self.file2_path, 'w') as file2:
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000314 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000315 os.chmod(self.file2_path, 0777)
316
Georg Brandl7bb16532008-05-20 06:47:31 +0000317 self.cwd = os.getcwd()
Georg Brandlf899dfa2008-05-18 09:12:20 +0000318 os.chdir(self.parent_dir)
319
320 def tearDown(self):
321 try:
Georg Brandl7bb16532008-05-20 06:47:31 +0000322 os.chdir(self.cwd)
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000323 if self.pythonexe != sys.executable:
324 os.remove(self.pythonexe)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000325 os.remove(self.file1_path)
326 os.remove(self.file2_path)
327 os.rmdir(self.cgi_dir)
328 os.rmdir(self.parent_dir)
329 finally:
330 BaseTestCase.tearDown(self)
331
Gregory P. Smith923ba362009-04-06 06:33:26 +0000332 def test_url_collapse_path_split(self):
333 test_vectors = {
334 '': ('/', ''),
335 '..': IndexError,
336 '/.//..': IndexError,
337 '/': ('/', ''),
338 '//': ('/', ''),
339 '/\\': ('/', '\\'),
340 '/.//': ('/', ''),
341 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
342 '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
343 'a': ('/', 'a'),
344 '/a': ('/', 'a'),
345 '//a': ('/', 'a'),
346 './a': ('/', 'a'),
347 './C:/': ('/C:', ''),
348 '/a/b': ('/a', 'b'),
349 '/a/b/': ('/a/b', ''),
350 '/a/b/c/..': ('/a/b', ''),
351 '/a/b/c/../d': ('/a/b', 'd'),
352 '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
353 '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
354 '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
355 '../a/b/c/../d/e/.././././..//f': IndexError,
356 '/a/b/c/../d/e/../../../f': ('/a', 'f'),
357 '/a/b/c/../d/e/../../../../f': ('/', 'f'),
358 '/a/b/c/../d/e/../../../../../f': IndexError,
359 '/a/b/c/../d/e/../../../../f/..': ('/', ''),
360 }
361 for path, expected in test_vectors.iteritems():
362 if isinstance(expected, type) and issubclass(expected, Exception):
363 self.assertRaises(expected,
364 CGIHTTPServer._url_collapse_path_split, path)
365 else:
366 actual = CGIHTTPServer._url_collapse_path_split(path)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000367 self.assertEqual(expected, actual,
368 msg='path = %r\nGot: %r\nWanted: %r' %
369 (path, actual, expected))
Gregory P. Smith923ba362009-04-06 06:33:26 +0000370
Georg Brandlf899dfa2008-05-18 09:12:20 +0000371 def test_headers_and_content(self):
372 res = self.request('/cgi-bin/file1.py')
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000373 self.assertEqual(('Hello World\n', 'text/html', 200),
374 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlf899dfa2008-05-18 09:12:20 +0000375
376 def test_post(self):
377 params = urllib.urlencode({'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
378 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
379 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
380
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000381 self.assertEqual(res.read(), '1, python, 123456\n')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000382
383 def test_invaliduri(self):
384 res = self.request('/cgi-bin/invalid')
385 res.read()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000386 self.assertEqual(res.status, 404)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000387
388 def test_authorization(self):
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000389 headers = {'Authorization' : 'Basic %s' %
390 base64.b64encode('username:pass')}
Georg Brandlf899dfa2008-05-18 09:12:20 +0000391 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000392 self.assertEqual(('Hello World\n', 'text/html', 200),
393 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlf899dfa2008-05-18 09:12:20 +0000394
Gregory P. Smith923ba362009-04-06 06:33:26 +0000395 def test_no_leading_slash(self):
396 # http://bugs.python.org/issue2254
397 res = self.request('cgi-bin/file1.py')
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000398 self.assertEqual(('Hello World\n', 'text/html', 200),
Gregory P. Smith923ba362009-04-06 06:33:26 +0000399 (res.read(), res.getheader('Content-type'), res.status))
400
Georg Brandlf899dfa2008-05-18 09:12:20 +0000401
402def test_main(verbose=None):
403 try:
404 cwd = os.getcwd()
405 test_support.run_unittest(BaseHTTPServerTestCase,
Nick Coghlan87c03b32009-10-17 15:23:08 +0000406 SimpleHTTPServerTestCase,
407 CGIHTTPServerTestCase
408 )
Georg Brandlf899dfa2008-05-18 09:12:20 +0000409 finally:
410 os.chdir(cwd)
411
412if __name__ == '__main__':
413 test_main()