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