blob: daf37b2788ce5cadfa1f8acc912dcc64074510a0 [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', '/')
Brian Curtin61d0d602010-10-31 00:34:23 +0000185 self.addCleanup(self.con.close)
Georg Brandlb533e262008-05-25 18:19:30 +0000186
187 def test_internal_key_error(self):
188 self.con.request('KEYERROR', '/')
189 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000190 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000191
192 def test_return_custom_status(self):
193 self.con.request('CUSTOM', '/')
194 res = self.con.getresponse()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000195 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000196
197
198class SimpleHTTPServerTestCase(BaseTestCase):
199 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
200 pass
201
202 def setUp(self):
203 BaseTestCase.setUp(self)
204 self.cwd = os.getcwd()
205 basetempdir = tempfile.gettempdir()
206 os.chdir(basetempdir)
207 self.data = b'We are the knights who say Ni!'
208 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
209 self.tempdir_name = os.path.basename(self.tempdir)
Brett Cannon105df5d2010-10-29 23:43:42 +0000210 with open(os.path.join(self.tempdir, 'test'), 'wb') as temp:
211 temp.write(self.data)
Georg Brandlb533e262008-05-25 18:19:30 +0000212
213 def tearDown(self):
214 try:
215 os.chdir(self.cwd)
216 try:
217 shutil.rmtree(self.tempdir)
218 except:
219 pass
220 finally:
221 BaseTestCase.tearDown(self)
222
223 def check_status_and_reason(self, response, status, data=None):
224 body = response.read()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000225 self.assertTrue(response)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000226 self.assertEqual(response.status, status)
227 self.assertIsNotNone(response.reason)
Georg Brandlb533e262008-05-25 18:19:30 +0000228 if data:
229 self.assertEqual(data, body)
230
231 def test_get(self):
232 #constructs the path relative to the root directory of the HTTPServer
233 response = self.request(self.tempdir_name + '/test')
234 self.check_status_and_reason(response, 200, data=self.data)
235 response = self.request(self.tempdir_name + '/')
236 self.check_status_and_reason(response, 200)
237 response = self.request(self.tempdir_name)
238 self.check_status_and_reason(response, 301)
239 response = self.request('/ThisDoesNotExist')
240 self.check_status_and_reason(response, 404)
241 response = self.request('/' + 'ThisDoesNotExist' + '/')
242 self.check_status_and_reason(response, 404)
Brett Cannon105df5d2010-10-29 23:43:42 +0000243 with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as f:
244 response = self.request('/' + self.tempdir_name + '/')
245 self.check_status_and_reason(response, 200)
246 if os.name == 'posix':
247 # chmod won't work as expected on Windows platforms
248 os.chmod(self.tempdir, 0)
249 response = self.request(self.tempdir_name + '/')
250 self.check_status_and_reason(response, 404)
251 os.chmod(self.tempdir, 0o755)
Georg Brandlb533e262008-05-25 18:19:30 +0000252
253 def test_head(self):
254 response = self.request(
255 self.tempdir_name + '/test', method='HEAD')
256 self.check_status_and_reason(response, 200)
257 self.assertEqual(response.getheader('content-length'),
258 str(len(self.data)))
259 self.assertEqual(response.getheader('content-type'),
260 'application/octet-stream')
261
262 def test_invalid_requests(self):
263 response = self.request('/', method='FOO')
264 self.check_status_and_reason(response, 501)
265 # requests must be case sensitive,so this should fail too
266 response = self.request('/', method='get')
267 self.check_status_and_reason(response, 501)
268 response = self.request('/', method='GETs')
269 self.check_status_and_reason(response, 501)
270
271
272cgi_file1 = """\
273#!%s
274
275print("Content-type: text/html")
276print()
277print("Hello World")
278"""
279
280cgi_file2 = """\
281#!%s
282import cgi
283
284print("Content-type: text/html")
285print()
286
287form = cgi.FieldStorage()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000288print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
289 form.getfirst("bacon")))
Georg Brandlb533e262008-05-25 18:19:30 +0000290"""
291
292class CGIHTTPServerTestCase(BaseTestCase):
293 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
294 pass
295
296 def setUp(self):
297 BaseTestCase.setUp(self)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000298 self.cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000299 self.parent_dir = tempfile.mkdtemp()
300 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
301 os.mkdir(self.cgi_dir)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000302 self.file1_path = None
303 self.file2_path = None
Georg Brandlb533e262008-05-25 18:19:30 +0000304
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000305 # The shebang line should be pure ASCII: use symlink if possible.
306 # See issue #7668.
Brian Curtind40e6f72010-07-08 21:39:08 +0000307 if support.can_symlink():
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000308 self.pythonexe = os.path.join(self.parent_dir, 'python')
309 os.symlink(sys.executable, self.pythonexe)
310 else:
311 self.pythonexe = sys.executable
312
Victor Stinner3218c312010-10-17 20:13:36 +0000313 try:
314 # The python executable path is written as the first line of the
315 # CGI Python script. The encoding cookie cannot be used, and so the
316 # path should be encodable to the default script encoding (utf-8)
317 self.pythonexe.encode('utf-8')
318 except UnicodeEncodeError:
319 self.tearDown()
320 raise self.skipTest(
321 "Python executable path is not encodable to utf-8")
322
Georg Brandlb533e262008-05-25 18:19:30 +0000323 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000324 with open(self.file1_path, 'w', encoding='utf-8') as file1:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000325 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000326 os.chmod(self.file1_path, 0o777)
327
328 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
Victor Stinner6fb45752010-10-17 20:17:41 +0000329 with open(self.file2_path, 'w', encoding='utf-8') as file2:
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000330 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000331 os.chmod(self.file2_path, 0o777)
332
Georg Brandlb533e262008-05-25 18:19:30 +0000333 os.chdir(self.parent_dir)
334
335 def tearDown(self):
336 try:
337 os.chdir(self.cwd)
Florent Xiclunafd1b0932010-03-28 00:25:02 +0000338 if self.pythonexe != sys.executable:
339 os.remove(self.pythonexe)
Victor Stinner0b0ca0c2010-10-17 19:46:36 +0000340 if self.file1_path:
341 os.remove(self.file1_path)
342 if self.file2_path:
343 os.remove(self.file2_path)
Georg Brandlb533e262008-05-25 18:19:30 +0000344 os.rmdir(self.cgi_dir)
345 os.rmdir(self.parent_dir)
346 finally:
347 BaseTestCase.tearDown(self)
348
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000349 def test_url_collapse_path_split(self):
350 test_vectors = {
351 '': ('/', ''),
352 '..': IndexError,
353 '/.//..': IndexError,
354 '/': ('/', ''),
355 '//': ('/', ''),
356 '/\\': ('/', '\\'),
357 '/.//': ('/', ''),
358 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
359 '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
360 'a': ('/', 'a'),
361 '/a': ('/', 'a'),
362 '//a': ('/', 'a'),
363 './a': ('/', 'a'),
364 './C:/': ('/C:', ''),
365 '/a/b': ('/a', 'b'),
366 '/a/b/': ('/a/b', ''),
367 '/a/b/c/..': ('/a/b', ''),
368 '/a/b/c/../d': ('/a/b', 'd'),
369 '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
370 '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
371 '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
372 '../a/b/c/../d/e/.././././..//f': IndexError,
373 '/a/b/c/../d/e/../../../f': ('/a', 'f'),
374 '/a/b/c/../d/e/../../../../f': ('/', 'f'),
375 '/a/b/c/../d/e/../../../../../f': IndexError,
376 '/a/b/c/../d/e/../../../../f/..': ('/', ''),
377 }
378 for path, expected in test_vectors.items():
379 if isinstance(expected, type) and issubclass(expected, Exception):
380 self.assertRaises(expected,
381 server._url_collapse_path_split, path)
382 else:
383 actual = server._url_collapse_path_split(path)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000384 self.assertEqual(expected, actual,
385 msg='path = %r\nGot: %r\nWanted: %r' %
386 (path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000387
Georg Brandlb533e262008-05-25 18:19:30 +0000388 def test_headers_and_content(self):
389 res = self.request('/cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000390 self.assertEqual((b'Hello World\n', 'text/html', 200),
391 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000392
393 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000394 params = urllib.parse.urlencode(
395 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000396 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
397 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
398
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000399 self.assertEqual(res.read(), b'1, python, 123456\n')
Georg Brandlb533e262008-05-25 18:19:30 +0000400
401 def test_invaliduri(self):
402 res = self.request('/cgi-bin/invalid')
403 res.read()
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000404 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000405
406 def test_authorization(self):
407 headers = {b'Authorization' : b'Basic ' +
408 base64.b64encode(b'username:pass')}
409 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000410 self.assertEqual((b'Hello World\n', 'text/html', 200),
411 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlb533e262008-05-25 18:19:30 +0000412
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000413 def test_no_leading_slash(self):
414 # http://bugs.python.org/issue2254
415 res = self.request('cgi-bin/file1.py')
Florent Xicluna9b86b9a2010-03-19 19:00:44 +0000416 self.assertEqual((b'Hello World\n', 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000417 (res.read(), res.getheader('Content-type'), res.status))
418
Senthil Kumaran42713722010-10-03 17:55:45 +0000419 def test_os_environ_is_not_altered(self):
420 signature = "Test CGI Server"
421 os.environ['SERVER_SOFTWARE'] = signature
422 res = self.request('/cgi-bin/file1.py')
423 self.assertEqual((b'Hello World\n', 'text/html', 200),
424 (res.read(), res.getheader('Content-type'), res.status))
425 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
426
Georg Brandlb533e262008-05-25 18:19:30 +0000427
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000428class SocketlessRequestHandler(SimpleHTTPRequestHandler):
429 def __init__(self):
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000430 self.get_called = False
431 self.protocol_version = "HTTP/1.1"
432
433 def do_GET(self):
434 self.get_called = True
435 self.send_response(200)
436 self.send_header('Content-Type', 'text/html')
437 self.end_headers()
438 self.wfile.write(b'<html><body>Data</body></html>\r\n')
439
440 def log_message(self, format, *args):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000441 pass
442
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000443class RejectingSocketlessRequestHandler(SocketlessRequestHandler):
444 def handle_expect_100(self):
445 self.send_error(417)
446 return False
447
448class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
449 """Test the functionaility of the BaseHTTPServer.
450
451 Test the support for the Expect 100-continue header.
452 """
453
454 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
455
456 def setUp (self):
457 self.handler = SocketlessRequestHandler()
458
459 def send_typical_request(self, message):
460 input = BytesIO(message)
461 output = BytesIO()
462 self.handler.rfile = input
463 self.handler.wfile = output
464 self.handler.handle_one_request()
465 output.seek(0)
466 return output.readlines()
467
468 def verify_get_called(self):
469 self.assertTrue(self.handler.get_called)
470
471 def verify_expected_headers(self, headers):
472 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
473 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
474
475 def verify_http_server_response(self, response):
476 match = self.HTTPResponseMatch.search(response)
477 self.assertTrue(match is not None)
478
479 def test_http_1_1(self):
480 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
481 self.verify_http_server_response(result[0])
482 self.verify_expected_headers(result[1:-1])
483 self.verify_get_called()
484 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
485
486 def test_http_1_0(self):
487 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
488 self.verify_http_server_response(result[0])
489 self.verify_expected_headers(result[1:-1])
490 self.verify_get_called()
491 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
492
493 def test_http_0_9(self):
494 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
495 self.assertEqual(len(result), 1)
496 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
497 self.verify_get_called()
498
499 def test_with_continue_1_0(self):
500 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
501 self.verify_http_server_response(result[0])
502 self.verify_expected_headers(result[1:-1])
503 self.verify_get_called()
504 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
505
506 def test_with_continue_1_1(self):
507 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
508 self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n')
509 self.assertEqual(result[1], b'HTTP/1.1 200 OK\r\n')
510 self.verify_expected_headers(result[2:-1])
511 self.verify_get_called()
512 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
513
514 def test_with_continue_rejected(self):
515 usual_handler = self.handler # Save to avoid breaking any subsequent tests.
516 self.handler = RejectingSocketlessRequestHandler()
517 result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
518 self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n')
519 self.verify_expected_headers(result[1:-1])
520 # The expect handler should short circuit the usual get method by
521 # returning false here, so get_called should be false
522 self.assertFalse(self.handler.get_called)
523 self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
524 self.handler = usual_handler # Restore to avoid breaking any subsequent tests.
525
526
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000527class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
528 """ Test url parsing """
529 def setUp(self):
530 self.translated = os.getcwd()
531 self.translated = os.path.join(self.translated, 'filename')
532 self.handler = SocketlessRequestHandler()
533
534 def test_query_arguments(self):
535 path = self.handler.translate_path('/filename')
536 self.assertEqual(path, self.translated)
537 path = self.handler.translate_path('/filename?foo=bar')
538 self.assertEqual(path, self.translated)
539 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
540 self.assertEqual(path, self.translated)
541
542 def test_start_with_double_slash(self):
543 path = self.handler.translate_path('//filename')
544 self.assertEqual(path, self.translated)
545 path = self.handler.translate_path('//filename?foo=bar')
546 self.assertEqual(path, self.translated)
547
548
Georg Brandlb533e262008-05-25 18:19:30 +0000549def test_main(verbose=None):
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000550 cwd = os.getcwd()
Georg Brandlb533e262008-05-25 18:19:30 +0000551 try:
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000552 support.run_unittest(
Senthil Kumaran0f476d42010-09-30 06:09:18 +0000553 BaseHTTPRequestHandlerTestCase,
Georg Brandl6fcac0d2010-08-02 18:56:54 +0000554 BaseHTTPServerTestCase,
555 SimpleHTTPServerTestCase,
556 CGIHTTPServerTestCase,
557 SimpleHTTPRequestHandlerTestCase,
558 )
Georg Brandlb533e262008-05-25 18:19:30 +0000559 finally:
560 os.chdir(cwd)
561
562if __name__ == '__main__':
563 test_main()