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