blob: 837d4a6c28aa10c439655448fff860c4143de33a [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()
220 self.assert_(response)
221 self.assertEquals(response.status, status)
222 self.assert_(response.reason != None)
223 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
297 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
298 with open(self.file1_path, 'w') as file1:
299 file1.write(cgi_file1 % sys.executable)
300 os.chmod(self.file1_path, 0o777)
301
302 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
303 with open(self.file2_path, 'w') as file2:
304 file2.write(cgi_file2 % sys.executable)
305 os.chmod(self.file2_path, 0o777)
306
307 self.cwd = os.getcwd()
308 os.chdir(self.parent_dir)
309
310 def tearDown(self):
311 try:
312 os.chdir(self.cwd)
313 os.remove(self.file1_path)
314 os.remove(self.file2_path)
315 os.rmdir(self.cgi_dir)
316 os.rmdir(self.parent_dir)
317 finally:
318 BaseTestCase.tearDown(self)
319
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000320 def test_url_collapse_path_split(self):
321 test_vectors = {
322 '': ('/', ''),
323 '..': IndexError,
324 '/.//..': IndexError,
325 '/': ('/', ''),
326 '//': ('/', ''),
327 '/\\': ('/', '\\'),
328 '/.//': ('/', ''),
329 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
330 '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
331 'a': ('/', 'a'),
332 '/a': ('/', 'a'),
333 '//a': ('/', 'a'),
334 './a': ('/', 'a'),
335 './C:/': ('/C:', ''),
336 '/a/b': ('/a', 'b'),
337 '/a/b/': ('/a/b', ''),
338 '/a/b/c/..': ('/a/b', ''),
339 '/a/b/c/../d': ('/a/b', 'd'),
340 '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
341 '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
342 '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
343 '../a/b/c/../d/e/.././././..//f': IndexError,
344 '/a/b/c/../d/e/../../../f': ('/a', 'f'),
345 '/a/b/c/../d/e/../../../../f': ('/', 'f'),
346 '/a/b/c/../d/e/../../../../../f': IndexError,
347 '/a/b/c/../d/e/../../../../f/..': ('/', ''),
348 }
349 for path, expected in test_vectors.items():
350 if isinstance(expected, type) and issubclass(expected, Exception):
351 self.assertRaises(expected,
352 server._url_collapse_path_split, path)
353 else:
354 actual = server._url_collapse_path_split(path)
355 self.assertEquals(expected, actual,
356 msg='path = %r\nGot: %r\nWanted: %r' % (
357 path, actual, expected))
358
Georg Brandlb533e262008-05-25 18:19:30 +0000359 def test_headers_and_content(self):
360 res = self.request('/cgi-bin/file1.py')
361 self.assertEquals((b'Hello World\n', 'text/html', 200), \
362 (res.read(), res.getheader('Content-type'), res.status))
363
364 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000365 params = urllib.parse.urlencode(
366 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000367 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
368 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
369
370 self.assertEquals(res.read(), b'1, python, 123456\n')
371
372 def test_invaliduri(self):
373 res = self.request('/cgi-bin/invalid')
374 res.read()
375 self.assertEquals(res.status, 404)
376
377 def test_authorization(self):
378 headers = {b'Authorization' : b'Basic ' +
379 base64.b64encode(b'username:pass')}
380 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
381 self.assertEquals((b'Hello World\n', 'text/html', 200), \
382 (res.read(), res.getheader('Content-type'), res.status))
383
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000384 def test_no_leading_slash(self):
385 # http://bugs.python.org/issue2254
386 res = self.request('cgi-bin/file1.py')
387 self.assertEquals((b'Hello World\n', 'text/html', 200),
388 (res.read(), res.getheader('Content-type'), res.status))
389
Georg Brandlb533e262008-05-25 18:19:30 +0000390
391def test_main(verbose=None):
392 try:
393 cwd = os.getcwd()
Georg Brandl24420152008-05-26 16:32:26 +0000394 support.run_unittest(BaseHTTPServerTestCase,
Georg Brandlb533e262008-05-25 18:19:30 +0000395 SimpleHTTPServerTestCase,
396 CGIHTTPServerTestCase
397 )
398 finally:
399 os.chdir(cwd)
400
401if __name__ == '__main__':
402 test_main()