blob: ddb50dc23f206f5f5472700d40e12273e9803be8 [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
Senthil Kumaran0f476d42010-09-30 06:09:18 +000013import re
Georg Brandlb533e262008-05-25 18:19:30 +000014import base64
15import shutil
Jeremy Hylton1afc1692008-06-18 20:49:58 +000016import urllib.parse
Georg Brandl24420152008-05-26 16:32:26 +000017import http.client
Georg Brandlb533e262008-05-25 18:19:30 +000018import tempfile
Senthil Kumaran0f476d42010-09-30 06:09:18 +000019from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000020
21import unittest
22from test import support
Victor Stinner45df8202010-04-28 22:31:17 +000023threading = support.import_module('threading')
Georg Brandlb533e262008-05-25 18:19:30 +000024
Georg Brandlb533e262008-05-25 18:19:30 +000025class NoLogRequestHandler:
26 def log_message(self, *args):
27 # don't write log messages to stderr
28 pass
29
Barry Warsaw820c1202008-06-12 04:06:45 +000030 def read(self, n=None):
31 return ''
32
Georg Brandlb533e262008-05-25 18:19:30 +000033
34class TestServerThread(threading.Thread):
35 def __init__(self, test_object, request_handler):
36 threading.Thread.__init__(self)
37 self.request_handler = request_handler
38 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000039
40 def run(self):
41 self.server = HTTPServer(('', 0), self.request_handler)
42 self.test_object.PORT = self.server.socket.getsockname()[1]
Antoine Pitrou08911bd2010-04-25 22:19:43 +000043 self.test_object.server_started.set()
44 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000045 try:
Antoine Pitrou08911bd2010-04-25 22:19:43 +000046 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000047 finally:
48 self.server.server_close()
49
50 def stop(self):
51 self.server.shutdown()
52
53
54class BaseTestCase(unittest.TestCase):
55 def setUp(self):
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000056 self._threads = support.threading_setup()
Nick Coghlan6ead5522009-10-18 13:19:33 +000057 os.environ = support.EnvironmentVarGuard()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000058 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000059 self.thread = TestServerThread(self, self.request_handler)
60 self.thread.start()
Antoine Pitrou08911bd2010-04-25 22:19:43 +000061 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000062
63 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000064 self.thread.stop()
Nick Coghlan6ead5522009-10-18 13:19:33 +000065 os.environ.__exit__()
Antoine Pitrou45ebeb82009-10-27 18:52:30 +000066 support.threading_cleanup(*self._threads)
Georg Brandlb533e262008-05-25 18:19:30 +000067
68 def request(self, uri, method='GET', body=None, headers={}):
Georg Brandl24420152008-05-26 16:32:26 +000069 self.connection = http.client.HTTPConnection('localhost', self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000070 self.connection.request(method, uri, body, headers)
71 return self.connection.getresponse()
72
73
74class BaseHTTPServerTestCase(BaseTestCase):
75 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
76 protocol_version = 'HTTP/1.1'
77 default_request_version = 'HTTP/1.1'
78
79 def do_TEST(self):
80 self.send_response(204)
81 self.send_header('Content-Type', 'text/html')
82 self.send_header('Connection', 'close')
83 self.end_headers()
84
85 def do_KEEP(self):
86 self.send_response(204)
87 self.send_header('Content-Type', 'text/html')
88 self.send_header('Connection', 'keep-alive')
89 self.end_headers()
90
91 def do_KEYERROR(self):
92 self.send_error(999)
93
94 def do_CUSTOM(self):
95 self.send_response(999)
96 self.send_header('Content-Type', 'text/html')
97 self.send_header('Connection', 'close')
98 self.end_headers()
99
100 def setUp(self):
101 BaseTestCase.setUp(self)
Georg Brandl24420152008-05-26 16:32:26 +0000102 self.con = http.client.HTTPConnection('localhost', self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000103 self.con.connect()
104
105 def test_command(self):
106 self.con.request('GET', '/')
107 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000108 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000109
110 def test_request_line_trimming(self):
111 self.con._http_vsn_str = 'HTTP/1.1\n'
112 self.con.putrequest('GET', '/')
113 self.con.endheaders()
114 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000115 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000116
117 def test_version_bogus(self):
118 self.con._http_vsn_str = 'FUBAR'
119 self.con.putrequest('GET', '/')
120 self.con.endheaders()
121 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000122 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000123
124 def test_version_digits(self):
125 self.con._http_vsn_str = 'HTTP/9.9.9'
126 self.con.putrequest('GET', '/')
127 self.con.endheaders()
128 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000129 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000130
131 def test_version_none_get(self):
132 self.con._http_vsn_str = ''
133 self.con.putrequest('GET', '/')
134 self.con.endheaders()
135 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000136 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000137
138 def test_version_none(self):
139 self.con._http_vsn_str = ''
140 self.con.putrequest('PUT', '/')
141 self.con.endheaders()
142 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000143 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000144
145 def test_version_invalid(self):
146 self.con._http_vsn = 99
147 self.con._http_vsn_str = 'HTTP/9.9'
148 self.con.putrequest('GET', '/')
149 self.con.endheaders()
150 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000151 self.assertEqual(res.status, 505)
Georg Brandlb533e262008-05-25 18:19:30 +0000152
153 def test_send_blank(self):
154 self.con._http_vsn_str = ''
155 self.con.putrequest('', '')
156 self.con.endheaders()
157 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000158 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000159
160 def test_header_close(self):
161 self.con.putrequest('GET', '/')
162 self.con.putheader('Connection', 'close')
163 self.con.endheaders()
164 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000165 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000166
167 def test_head_keep_alive(self):
168 self.con._http_vsn_str = 'HTTP/1.1'
169 self.con.putrequest('GET', '/')
170 self.con.putheader('Connection', 'keep-alive')
171 self.con.endheaders()
172 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000173 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000174
175 def test_handler(self):
176 self.con.request('TEST', '/')
177 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000178 self.assertEqual(res.status, 204)
Georg Brandlb533e262008-05-25 18:19:30 +0000179
180 def test_return_header_keep_alive(self):
181 self.con.request('KEEP', '/')
182 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000183 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000184 self.con.request('TEST', '/')
185
186 def test_internal_key_error(self):
187 self.con.request('KEYERROR', '/')
188 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000189 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000190
191 def test_return_custom_status(self):
192 self.con.request('CUSTOM', '/')
193 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000194 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000195
196
197class SimpleHTTPServerTestCase(BaseTestCase):
198 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
199 pass
200
201 def setUp(self):
202 BaseTestCase.setUp(self)
203 self.cwd = os.getcwd()
204 basetempdir = tempfile.gettempdir()
205 os.chdir(basetempdir)
206 self.data = b'We are the knights who say Ni!'
207 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
208 self.tempdir_name = os.path.basename(self.tempdir)
Brett Cannon105df5d2010-10-29 23:43:42 +0000209 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
210 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000211
212 def tearDown(self):
213 try:
214 os.chdir(self.cwd)
215 try:
216 shutil.rmtree(self.tempdir)
217 except:
218 pass
219 finally:
220 BaseTestCase.tearDown(self)
221
222 def check_status_and_reason(self, response, status, data=None):
223 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000224 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000225 self.assertEqual(response.status, status)
226 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000227 if data:
228 self.assertEqual(data, body)
229
230 def test_get(self):
231 #constructs the path relative to the root directory of the HTTPServer
232 response = self.request(self.tempdir_name + '/test')
233 self.check_status_and_reason(response, 200, data=self.data)
234 response = self.request(self.tempdir_name + '/')
235 self.check_status_and_reason(response, 200)
236 response = self.request(self.tempdir_name)
237 self.check_status_and_reason(response, 301)
238 response = self.request('/ThisDoesNotExist')
239 self.check_status_and_reason(response, 404)
240 response = self.request('/' + 'ThisDoesNotExist' + '/')
241 self.check_status_and_reason(response, 404)
Brett Cannon105df5d2010-10-29 23:43:42 +0000242 with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as f:
243 response = self.request('/' + self.tempdir_name + '/')
244 self.check_status_and_reason(response, 200)
245 if os.name == 'posix':
246 # chmod won't work as expected on Windows platforms
247 os.chmod(self.tempdir, 0)
248 response = self.request(self.tempdir_name + '/')
249 self.check_status_and_reason(response, 404)
250 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000251
252 def test_head(self):
253 response = self.request(
254 self.tempdir_name + '/test', method='HEAD')
255 self.check_status_and_reason(response, 200)
256 self.assertEqual(response.getheader('content-length'),
257 str(len(self.data)))
258 self.assertEqual(response.getheader('content-type'),
259 'application/octet-stream')
260
261 def test_invalid_requests(self):
262 response = self.request('/', method='FOO')
263 self.check_status_and_reason(response, 501)
264 # requests must be case sensitive,so this should fail too
265 response = self.request('/', method='get')
266 self.check_status_and_reason(response, 501)
267 response = self.request('/', method='GETs')
268 self.check_status_and_reason(response, 501)
269
270
271cgi_file1 = """\
272#!%s
273
274print("Content-type: text/html")
275print()
276print("Hello World")
277"""
278
279cgi_file2 = """\
280#!%s
281import cgi
282
283print("Content-type: text/html")
284print()
285
286form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000287print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
288 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000289"""
290
291class CGIHTTPServerTestCase(BaseTestCase):
292 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
293 pass
294
295 def setUp(self):
296 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000297 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000298 self.parent_dir = tempfile.mkdtemp()
299 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
300 os.mkdir(self.cgi_dir)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000301 self.file1_path = None
302 self.file2_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000303
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000304 # The shebang line should be pure ASCII: use symlink if possible.
305 # See issue #7668.
Brian Curtind40e6f72010-07-08 21:39:08 +0000306 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000307 self.pythonexe = os.path.join(self.parent_dir, 'python')
308 os.symlink(sys.executable, self.pythonexe)
309 else:
310 self.pythonexe = sys.executable
311
Victor Stinner3218c312010-10-17 20:13:36 +0000312 try:
313 # The python executable path is written as the first line of the
314 # CGI Python script. The encoding cookie cannot be used, and so the
315 # path should be encodable to the default script encoding (utf-8)
316 self.pythonexe.encode('utf-8')
317 except UnicodeEncodeError:
318 self.tearDown()
319 raise self.skipTest(
320 "Python executable path is not encodable to utf-8")
321
Georg Brandlb533e262008-05-25 18:19:30 +0000322 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000323 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000324 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000325 os.chmod(self.file1_path, 0o777)
326
327 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000328 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000329 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000330 os.chmod(self.file2_path, 0o777)
331
Georg Brandlb533e262008-05-25 18:19:30 +0000332 os.chdir(self.parent_dir)
333
334 def tearDown(self):
335 try:
336 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000337 if self.pythonexe != sys.executable:
338 os.remove(self.pythonexe)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000339 if self.file1_path:
340 os.remove(self.file1_path)
341 if self.file2_path:
342 os.remove(self.file2_path)
Georg Brandlb533e262008-05-25 18:19:30 +0000343 os.rmdir(self.cgi_dir)
344 os.rmdir(self.parent_dir)
345 finally:
346 BaseTestCase.tearDown(self)
347
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000348 def test_url_collapse_path_split(self):
349 test_vectors = {
350 '': ('/', ''),
351 '..': IndexError,
352 '/.//..': IndexError,
353 '/': ('/', ''),
354 '//': ('/', ''),
355 '/\\': ('/', '\\'),
356 '/.//': ('/', ''),
357 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
358 '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
359 'a': ('/', 'a'),
360 '/a': ('/', 'a'),
361 '//a': ('/', 'a'),
362 './a': ('/', 'a'),
363 './C:/': ('/C:', ''),
364 '/a/b': ('/a', 'b'),
365 '/a/b/': ('/a/b', ''),
366 '/a/b/c/..': ('/a/b', ''),
367 '/a/b/c/../d': ('/a/b', 'd'),
368 '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
369 '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
370 '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
371 '../a/b/c/../d/e/.././././..//f': IndexError,
372 '/a/b/c/../d/e/../../../f': ('/a', 'f'),
373 '/a/b/c/../d/e/../../../../f': ('/', 'f'),
374 '/a/b/c/../d/e/../../../../../f': IndexError,
375 '/a/b/c/../d/e/../../../../f/..': ('/', ''),
376 }
377 for path, expected in test_vectors.items():
378 if isinstance(expected, type) and issubclass(expected, Exception):
379 self.assertRaises(expected,
380 server._url_collapse_path_split, path)
381 else:
382 actual = server._url_collapse_path_split(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000383 self.assertEqual(expected, actual,
384 msg='path = %r\nGot: %r\nWanted: %r' %
385 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000386
Georg Brandlb533e262008-05-25 18:19:30 +0000387 def test_headers_and_content(self):
388 res = self.request('/cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000389 self.assertEqual((b'Hello World\n', 'text/html', 200),
390 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000391
392 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000393 params = urllib.parse.urlencode(
394 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000395 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
396 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
397
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000398 self.assertEqual(res.read(), b'1, python, 123456\n')
Georg Brandlb533e262008-05-25 18:19:30 +0000399
400 def test_invaliduri(self):
401 res = self.request('/cgi-bin/invalid')
402 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000403 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000404
405 def test_authorization(self):
406 headers = {b'Authorization' : b'Basic ' +
407 base64.b64encode(b'username:pass')}
408 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000409 self.assertEqual((b'Hello World\n', 'text/html', 200),
410 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000411
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000412 def test_no_leading_slash(self):
413 # http://bugs.python.org/issue2254
414 res = self.request('cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000415 self.assertEqual((b'Hello World\n', 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000416 (res.read(), res.getheader('Content-type'), res.status))
417
Senthil Kumaran42713722010-10-03 17:55:45 +0000418 def test_os_environ_is_not_altered(self):
419 signature = "Test CGI Server"
420 os.environ['SERVER_SOFTWARE'] = signature
421 res = self.request('/cgi-bin/file1.py')
422 self.assertEqual((b'Hello World\n', 'text/html', 200),
423 (res.read(), res.getheader('Content-type'), res.status))
424 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
425
Georg Brandlb533e262008-05-25 18:19:30 +0000426
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000427class SocketlessRequestHandler(SimpleHTTPRequestHandler):
428 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000429 self.get_called = False
430 self.protocol_version = "HTTP/1.1"
431
432 def do_GET(self):
433 self.get_called = True
434 self.send_response(200)
435 self.send_header('Content-Type', 'text/html')
436 self.end_headers()
437 self.wfile.write(b'<html><body>Data</body></html>\r\n')
438
439 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000440 pass
441
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000442class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
443 def handle_expect_100(self):
444 self.send_error(417)
445 return False
446
447class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
448 """Test the functionaility of the BaseHTTPServer.
449
450 Test the support for the Expect 100-continue header.
451 """
452
453 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
454
455 def setUp (self):
456 self.handler = SocketlessRequestHandler()
457
458 def send_typical_request(self, message):
459 input = BytesIO(message)
460 output = BytesIO()
461 self.handler.rfile = input
462 self.handler.wfile = output
463 self.handler.handle_one_request()
464 output.seek(0)
465 return output.readlines()
466
467 def verify_get_called(self):
468 self.assertTrue(self.handler.get_called)
469
470 def verify_expected_headers(self, headers):
471 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
472 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
473
474 def verify_http_server_response(self, response):
475 match = self.HTTPResponseMatch.search(response)
476 self.assertTrue(match is not None)
477
478 def test_http_1_1(self):
479 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
480 self.verify_http_server_response(result[0])
481 self.verify_expected_headers(result[1:-1])
482 self.verify_get_called()
483 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
484
485 def test_http_1_0(self):
486 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
487 self.verify_http_server_response(result[0])
488 self.verify_expected_headers(result[1:-1])
489 self.verify_get_called()
490 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
491
492 def test_http_0_9(self):
493 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
494 self.assertEqual(len(result), 1)
495 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
496 self.verify_get_called()
497
498 def test_with_continue_1_0(self):
499 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
500 self.verify_http_server_response(result[0])
501 self.verify_expected_headers(result[1:-1])
502 self.verify_get_called()
503 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
504
505 def test_with_continue_1_1(self):
506 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
507 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
508 self.assertEqual(result[1], b'HTTP/1.1 200 OK\r\n')
509 self.verify_expected_headers(result[2:-1])
510 self.verify_get_called()
511 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
512
513 def test_with_continue_rejected(self):
514 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
515 self.handler = RejectingSocketlessRequestHandler()
516 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
517 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
518 self.verify_expected_headers(result[1:-1])
519 # The expect handler should short circuit the usual get method by
520 # returning false here, so get_called should be false
521 self.assertFalse(self.handler.get_called)
522 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
523 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
524
525
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000526class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
527 """ Test url parsing """
528 def setUp(self):
529 self.translated = os.getcwd()
530 self.translated = os.path.join(self.translated, 'filename')
531 self.handler = SocketlessRequestHandler()
532
533 def test_query_arguments(self):
534 path = self.handler.translate_path('/filename')
535 self.assertEqual(path, self.translated)
536 path = self.handler.translate_path('/filename?foo=bar')
537 self.assertEqual(path, self.translated)
538 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
539 self.assertEqual(path, self.translated)
540
541 def test_start_with_double_slash(self):
542 path = self.handler.translate_path('//filename')
543 self.assertEqual(path, self.translated)
544 path = self.handler.translate_path('//filename?foo=bar')
545 self.assertEqual(path, self.translated)
546
547
Georg Brandlb533e262008-05-25 18:19:30 +0000548def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000549 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000550 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000551 support.run_unittest(
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000552 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000553 BaseHTTPServerTestCase,
554 SimpleHTTPServerTestCase,
555 CGIHTTPServerTestCase,
556 SimpleHTTPRequestHandlerTestCase,
557 )
Georg Brandlb533e262008-05-25 18:19:30 +0000558 finally:
559 os.chdir(cwd)
560
561if __name__ == '__main__':
562 test_main()