blob: cbc77f20cfa3719fb80ba07c7e226d4b0b5e7d1a [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 Kumaraneb3b6ed2010-09-30 06:34:02 +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
19import threading
20
21import unittest
Senthil Kumaraneb3b6ed2010-09-30 06:34:02 +000022
23from io import BytesIO
Georg Brandlb533e262008-05-25 18:19:30 +000024from test import support
25
Georg Brandlb533e262008-05-25 18:19:30 +000026class NoLogRequestHandler:
27 def log_message(self, *args):
28 # don't write log messages to stderr
29 pass
30
Barry Warsaw820c1202008-06-12 04:06:45 +000031 def read(self, n=None):
32 return ''
33
Georg Brandlb533e262008-05-25 18:19:30 +000034
Senthil Kumaraneb3b6ed2010-09-30 06:34:02 +000035class SocketlessRequestHandler(BaseHTTPRequestHandler):
36 def __init__(self):
37 self.get_called = False
38 self.protocol_version = "HTTP/1.1"
39
40 def do_GET(self):
41 self.get_called = True
42 self.send_response(200)
43 self.send_header('Content-Type', 'text/html')
44 self.end_headers()
45 self.wfile.write(b'<html><body>Data</body></html>\r\n')
46
47 def log_message(self, format, *args):
48 pass
49
50
Georg Brandlb533e262008-05-25 18:19:30 +000051class TestServerThread(threading.Thread):
52 def __init__(self, test_object, request_handler):
53 threading.Thread.__init__(self)
54 self.request_handler = request_handler
55 self.test_object = test_object
Georg Brandlb533e262008-05-25 18:19:30 +000056
57 def run(self):
58 self.server = HTTPServer(('', 0), self.request_handler)
59 self.test_object.PORT = self.server.socket.getsockname()[1]
Antoine Pitroue3123912010-04-25 22:26:08 +000060 self.test_object.server_started.set()
61 self.test_object = None
Georg Brandlb533e262008-05-25 18:19:30 +000062 try:
Antoine Pitroue3123912010-04-25 22:26:08 +000063 self.server.serve_forever(0.05)
Georg Brandlb533e262008-05-25 18:19:30 +000064 finally:
65 self.server.server_close()
66
67 def stop(self):
68 self.server.shutdown()
69
70
71class BaseTestCase(unittest.TestCase):
72 def setUp(self):
Antoine Pitroue3123912010-04-25 22:26:08 +000073 self.server_started = threading.Event()
Georg Brandlb533e262008-05-25 18:19:30 +000074 self.thread = TestServerThread(self, self.request_handler)
75 self.thread.start()
Antoine Pitroue3123912010-04-25 22:26:08 +000076 self.server_started.wait()
Georg Brandlb533e262008-05-25 18:19:30 +000077
78 def tearDown(self):
Georg Brandlb533e262008-05-25 18:19:30 +000079 self.thread.stop()
80
81 def request(self, uri, method='GET', body=None, headers={}):
Georg Brandl24420152008-05-26 16:32:26 +000082 self.connection = http.client.HTTPConnection('localhost', self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +000083 self.connection.request(method, uri, body, headers)
84 return self.connection.getresponse()
85
Senthil Kumaraneb3b6ed2010-09-30 06:34:02 +000086class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
87 """Test the functionaility of the BaseHTTPServer."""
88
89 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
90
91 def setUp (self):
92 self.handler = SocketlessRequestHandler()
93
94 def send_typical_request(self, message):
95 input = BytesIO(message)
96 output = BytesIO()
97 self.handler.rfile = input
98 self.handler.wfile = output
99 self.handler.handle_one_request()
100 output.seek(0)
101 return output.readlines()
102
103 def verify_get_called(self):
104 self.assertTrue(self.handler.get_called)
105
106 def verify_expected_headers(self, headers):
107 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
108 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
109
110 def verify_http_server_response(self, response):
111 match = self.HTTPResponseMatch.search(response)
112 self.assertTrue(match is not None)
113
114 def test_http_1_1(self):
115 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
116 self.verify_http_server_response(result[0])
117 self.verify_expected_headers(result[1:-1])
118 self.verify_get_called()
119 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
120
121 def test_http_1_0(self):
122 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
123 self.verify_http_server_response(result[0])
124 self.verify_expected_headers(result[1:-1])
125 self.verify_get_called()
126 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
127
128 def test_http_0_9(self):
129 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
130 self.assertEqual(len(result), 1)
131 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
132 self.verify_get_called()
133
134 def test_with_continue_1_0(self):
135 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
136 self.verify_http_server_response(result[0])
137 self.verify_expected_headers(result[1:-1])
138 self.verify_get_called()
139 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
140
Georg Brandlb533e262008-05-25 18:19:30 +0000141
142class BaseHTTPServerTestCase(BaseTestCase):
143 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
144 protocol_version = 'HTTP/1.1'
145 default_request_version = 'HTTP/1.1'
146
147 def do_TEST(self):
148 self.send_response(204)
149 self.send_header('Content-Type', 'text/html')
150 self.send_header('Connection', 'close')
151 self.end_headers()
152
153 def do_KEEP(self):
154 self.send_response(204)
155 self.send_header('Content-Type', 'text/html')
156 self.send_header('Connection', 'keep-alive')
157 self.end_headers()
158
159 def do_KEYERROR(self):
160 self.send_error(999)
161
162 def do_CUSTOM(self):
163 self.send_response(999)
164 self.send_header('Content-Type', 'text/html')
165 self.send_header('Connection', 'close')
166 self.end_headers()
167
168 def setUp(self):
169 BaseTestCase.setUp(self)
Georg Brandl24420152008-05-26 16:32:26 +0000170 self.con = http.client.HTTPConnection('localhost', self.PORT)
Georg Brandlb533e262008-05-25 18:19:30 +0000171 self.con.connect()
172
173 def test_command(self):
174 self.con.request('GET', '/')
175 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000176 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000177
178 def test_request_line_trimming(self):
179 self.con._http_vsn_str = 'HTTP/1.1\n'
180 self.con.putrequest('GET', '/')
181 self.con.endheaders()
182 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000183 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000184
185 def test_version_bogus(self):
186 self.con._http_vsn_str = 'FUBAR'
187 self.con.putrequest('GET', '/')
188 self.con.endheaders()
189 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000190 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000191
192 def test_version_digits(self):
193 self.con._http_vsn_str = 'HTTP/9.9.9'
194 self.con.putrequest('GET', '/')
195 self.con.endheaders()
196 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000197 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000198
199 def test_version_none_get(self):
200 self.con._http_vsn_str = ''
201 self.con.putrequest('GET', '/')
202 self.con.endheaders()
203 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000204 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000205
206 def test_version_none(self):
207 self.con._http_vsn_str = ''
208 self.con.putrequest('PUT', '/')
209 self.con.endheaders()
210 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000211 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000212
213 def test_version_invalid(self):
214 self.con._http_vsn = 99
215 self.con._http_vsn_str = 'HTTP/9.9'
216 self.con.putrequest('GET', '/')
217 self.con.endheaders()
218 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000219 self.assertEqual(res.status, 505)
Georg Brandlb533e262008-05-25 18:19:30 +0000220
221 def test_send_blank(self):
222 self.con._http_vsn_str = ''
223 self.con.putrequest('', '')
224 self.con.endheaders()
225 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000226 self.assertEqual(res.status, 400)
Georg Brandlb533e262008-05-25 18:19:30 +0000227
228 def test_header_close(self):
229 self.con.putrequest('GET', '/')
230 self.con.putheader('Connection', 'close')
231 self.con.endheaders()
232 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000233 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000234
235 def test_head_keep_alive(self):
236 self.con._http_vsn_str = 'HTTP/1.1'
237 self.con.putrequest('GET', '/')
238 self.con.putheader('Connection', 'keep-alive')
239 self.con.endheaders()
240 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000241 self.assertEqual(res.status, 501)
Georg Brandlb533e262008-05-25 18:19:30 +0000242
243 def test_handler(self):
244 self.con.request('TEST', '/')
245 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000246 self.assertEqual(res.status, 204)
Georg Brandlb533e262008-05-25 18:19:30 +0000247
248 def test_return_header_keep_alive(self):
249 self.con.request('KEEP', '/')
250 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000251 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlb533e262008-05-25 18:19:30 +0000252 self.con.request('TEST', '/')
253
254 def test_internal_key_error(self):
255 self.con.request('KEYERROR', '/')
256 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000257 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000258
259 def test_return_custom_status(self):
260 self.con.request('CUSTOM', '/')
261 res = self.con.getresponse()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000262 self.assertEqual(res.status, 999)
Georg Brandlb533e262008-05-25 18:19:30 +0000263
264
265class SimpleHTTPServerTestCase(BaseTestCase):
266 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
267 pass
268
269 def setUp(self):
270 BaseTestCase.setUp(self)
271 self.cwd = os.getcwd()
272 basetempdir = tempfile.gettempdir()
273 os.chdir(basetempdir)
274 self.data = b'We are the knights who say Ni!'
275 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
276 self.tempdir_name = os.path.basename(self.tempdir)
277 temp = open(os.path.join(self.tempdir, 'test'), 'wb')
278 temp.write(self.data)
279 temp.close()
280
281 def tearDown(self):
282 try:
283 os.chdir(self.cwd)
284 try:
285 shutil.rmtree(self.tempdir)
286 except:
287 pass
288 finally:
289 BaseTestCase.tearDown(self)
290
291 def check_status_and_reason(self, response, status, data=None):
292 body = response.read()
Georg Brandlab91fde2009-08-13 08:51:18 +0000293 self.assertTrue(response)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000294 self.assertEqual(response.status, status)
Georg Brandlab91fde2009-08-13 08:51:18 +0000295 self.assertTrue(response.reason != None)
Georg Brandlb533e262008-05-25 18:19:30 +0000296 if data:
297 self.assertEqual(data, body)
298
299 def test_get(self):
300 #constructs the path relative to the root directory of the HTTPServer
301 response = self.request(self.tempdir_name + '/test')
302 self.check_status_and_reason(response, 200, data=self.data)
303 response = self.request(self.tempdir_name + '/')
304 self.check_status_and_reason(response, 200)
305 response = self.request(self.tempdir_name)
306 self.check_status_and_reason(response, 301)
307 response = self.request('/ThisDoesNotExist')
308 self.check_status_and_reason(response, 404)
309 response = self.request('/' + 'ThisDoesNotExist' + '/')
310 self.check_status_and_reason(response, 404)
311 f = open(os.path.join(self.tempdir_name, 'index.html'), 'w')
312 response = self.request('/' + self.tempdir_name + '/')
313 self.check_status_and_reason(response, 200)
314 if os.name == 'posix':
315 # chmod won't work as expected on Windows platforms
316 os.chmod(self.tempdir, 0)
317 response = self.request(self.tempdir_name + '/')
318 self.check_status_and_reason(response, 404)
319 os.chmod(self.tempdir, 0o755)
320
321 def test_head(self):
322 response = self.request(
323 self.tempdir_name + '/test', method='HEAD')
324 self.check_status_and_reason(response, 200)
325 self.assertEqual(response.getheader('content-length'),
326 str(len(self.data)))
327 self.assertEqual(response.getheader('content-type'),
328 'application/octet-stream')
329
330 def test_invalid_requests(self):
331 response = self.request('/', method='FOO')
332 self.check_status_and_reason(response, 501)
333 # requests must be case sensitive,so this should fail too
334 response = self.request('/', method='get')
335 self.check_status_and_reason(response, 501)
336 response = self.request('/', method='GETs')
337 self.check_status_and_reason(response, 501)
338
339
340cgi_file1 = """\
341#!%s
342
343print("Content-type: text/html")
344print()
345print("Hello World")
346"""
347
348cgi_file2 = """\
349#!%s
350import cgi
351
352print("Content-type: text/html")
353print()
354
355form = cgi.FieldStorage()
356print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),\
357 form.getfirst("bacon")))
358"""
359
360class CGIHTTPServerTestCase(BaseTestCase):
361 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
362 pass
363
364 def setUp(self):
365 BaseTestCase.setUp(self)
366 self.parent_dir = tempfile.mkdtemp()
367 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
368 os.mkdir(self.cgi_dir)
369
Florent Xicluna9b0e9182010-03-28 11:42:38 +0000370 # The shebang line should be pure ASCII: use symlink if possible.
371 # See issue #7668.
372 if hasattr(os, 'symlink'):
373 self.pythonexe = os.path.join(self.parent_dir, 'python')
374 os.symlink(sys.executable, self.pythonexe)
375 else:
376 self.pythonexe = sys.executable
377
Georg Brandlb533e262008-05-25 18:19:30 +0000378 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
379 with open(self.file1_path, 'w') as file1:
Florent Xicluna9b0e9182010-03-28 11:42:38 +0000380 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000381 os.chmod(self.file1_path, 0o777)
382
383 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
384 with open(self.file2_path, 'w') as file2:
Florent Xicluna9b0e9182010-03-28 11:42:38 +0000385 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000386 os.chmod(self.file2_path, 0o777)
387
388 self.cwd = os.getcwd()
389 os.chdir(self.parent_dir)
390
391 def tearDown(self):
392 try:
393 os.chdir(self.cwd)
Florent Xicluna9b0e9182010-03-28 11:42:38 +0000394 if self.pythonexe != sys.executable:
395 os.remove(self.pythonexe)
Georg Brandlb533e262008-05-25 18:19:30 +0000396 os.remove(self.file1_path)
397 os.remove(self.file2_path)
398 os.rmdir(self.cgi_dir)
399 os.rmdir(self.parent_dir)
400 finally:
401 BaseTestCase.tearDown(self)
402
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000403 def test_url_collapse_path_split(self):
404 test_vectors = {
405 '': ('/', ''),
406 '..': IndexError,
407 '/.//..': IndexError,
408 '/': ('/', ''),
409 '//': ('/', ''),
410 '/\\': ('/', '\\'),
411 '/.//': ('/', ''),
412 'cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
413 '/cgi-bin/file1.py': ('/cgi-bin', 'file1.py'),
414 'a': ('/', 'a'),
415 '/a': ('/', 'a'),
416 '//a': ('/', 'a'),
417 './a': ('/', 'a'),
418 './C:/': ('/C:', ''),
419 '/a/b': ('/a', 'b'),
420 '/a/b/': ('/a/b', ''),
421 '/a/b/c/..': ('/a/b', ''),
422 '/a/b/c/../d': ('/a/b', 'd'),
423 '/a/b/c/../d/e/../f': ('/a/b/d', 'f'),
424 '/a/b/c/../d/e/../../f': ('/a/b', 'f'),
425 '/a/b/c/../d/e/.././././..//f': ('/a/b', 'f'),
426 '../a/b/c/../d/e/.././././..//f': IndexError,
427 '/a/b/c/../d/e/../../../f': ('/a', 'f'),
428 '/a/b/c/../d/e/../../../../f': ('/', 'f'),
429 '/a/b/c/../d/e/../../../../../f': IndexError,
430 '/a/b/c/../d/e/../../../../f/..': ('/', ''),
431 }
432 for path, expected in test_vectors.items():
433 if isinstance(expected, type) and issubclass(expected, Exception):
434 self.assertRaises(expected,
435 server._url_collapse_path_split, path)
436 else:
437 actual = server._url_collapse_path_split(path)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000438 self.assertEqual(expected, actual,
439 msg='path = %r\nGot: %r\nWanted: %r' % (
440 path, actual, expected))
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000441
Georg Brandlb533e262008-05-25 18:19:30 +0000442 def test_headers_and_content(self):
443 res = self.request('/cgi-bin/file1.py')
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000444 self.assertEqual((b'Hello World\n', 'text/html', 200), \
Georg Brandlb533e262008-05-25 18:19:30 +0000445 (res.read(), res.getheader('Content-type'), res.status))
446
447 def test_post(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000448 params = urllib.parse.urlencode(
449 {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
Georg Brandlb533e262008-05-25 18:19:30 +0000450 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
451 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
452
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000453 self.assertEqual(res.read(), b'1, python, 123456\n')
Georg Brandlb533e262008-05-25 18:19:30 +0000454
455 def test_invaliduri(self):
456 res = self.request('/cgi-bin/invalid')
457 res.read()
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000458 self.assertEqual(res.status, 404)
Georg Brandlb533e262008-05-25 18:19:30 +0000459
460 def test_authorization(self):
461 headers = {b'Authorization' : b'Basic ' +
462 base64.b64encode(b'username:pass')}
463 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000464 self.assertEqual((b'Hello World\n', 'text/html', 200), \
Georg Brandlb533e262008-05-25 18:19:30 +0000465 (res.read(), res.getheader('Content-type'), res.status))
466
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000467 def test_no_leading_slash(self):
468 # http://bugs.python.org/issue2254
469 res = self.request('cgi-bin/file1.py')
Ezio Melotti19f2aeb2010-11-21 01:30:29 +0000470 self.assertEqual((b'Hello World\n', 'text/html', 200),
Benjamin Petersonad71f0f2009-04-11 20:12:10 +0000471 (res.read(), res.getheader('Content-type'), res.status))
472
Senthil Kumaran5e8826c2010-10-03 18:04:52 +0000473 def test_os_environ_is_not_altered(self):
474 signature = "Test CGI Server"
475 os.environ['SERVER_SOFTWARE'] = signature
476 res = self.request('/cgi-bin/file1.py')
477 self.assertEqual((b'Hello World\n', 'text/html', 200),
478 (res.read(), res.getheader('Content-type'), res.status))
479 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
Georg Brandlb533e262008-05-25 18:19:30 +0000480
Antoine Pitrou3022ce12010-12-16 17:03:16 +0000481
482class SocketlessRequestHandler(SimpleHTTPRequestHandler):
483 def __init__(self):
484 self.get_called = False
485 self.protocol_version = "HTTP/1.1"
486
487 def do_GET(self):
488 self.get_called = True
489 self.send_response(200)
490 self.send_header('Content-Type', 'text/html')
491 self.end_headers()
492 self.wfile.write(b'<html><body>Data</body></html>\r\n')
493
494 def log_message(self, format, *args):
495 pass
496
497class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
498 """Test the functionaility of the BaseHTTPServer.
499 """
500
501 HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK')
502
503 def setUp (self):
504 self.handler = SocketlessRequestHandler()
505
506 def send_typical_request(self, message):
507 input = BytesIO(message)
508 output = BytesIO()
509 self.handler.rfile = input
510 self.handler.wfile = output
511 self.handler.handle_one_request()
512 output.seek(0)
513 return output.readlines()
514
515 def verify_get_called(self):
516 self.assertTrue(self.handler.get_called)
517
518 def verify_expected_headers(self, headers):
519 for fieldName in b'Server: ', b'Date: ', b'Content-Type: ':
520 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
521
522 def verify_http_server_response(self, response):
523 match = self.HTTPResponseMatch.search(response)
524 self.assertTrue(match is not None)
525
526 def test_http_1_1(self):
527 result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n')
528 self.verify_http_server_response(result[0])
529 self.verify_expected_headers(result[1:-1])
530 self.verify_get_called()
531 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
532
533 def test_http_1_0(self):
534 result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n')
535 self.verify_http_server_response(result[0])
536 self.verify_expected_headers(result[1:-1])
537 self.verify_get_called()
538 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
539
540 def test_http_0_9(self):
541 result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n')
542 self.assertEqual(len(result), 1)
543 self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n')
544 self.verify_get_called()
545
546 def test_with_continue_1_0(self):
547 result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
548 self.verify_http_server_response(result[0])
549 self.verify_expected_headers(result[1:-1])
550 self.verify_get_called()
551 self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
552
553 def test_request_length(self):
554 # Issue #10714: huge request lines are discarded, to avoid Denial
555 # of Service attacks.
556 result = self.send_typical_request(b'GET ' + b'x' * 65537)
557 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
558 self.assertFalse(self.handler.get_called)
559
560class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
561 """ Test url parsing """
562 def setUp(self):
563 self.translated = os.getcwd()
564 self.translated = os.path.join(self.translated, 'filename')
565 self.handler = SocketlessRequestHandler()
566
567 def test_query_arguments(self):
568 path = self.handler.translate_path('/filename')
569 self.assertEqual(path, self.translated)
570 path = self.handler.translate_path('/filename?foo=bar')
571 self.assertEqual(path, self.translated)
572 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
573 self.assertEqual(path, self.translated)
574
575 def test_start_with_double_slash(self):
576 path = self.handler.translate_path('//filename')
577 self.assertEqual(path, self.translated)
578 path = self.handler.translate_path('//filename?foo=bar')
579 self.assertEqual(path, self.translated)
580
581
Georg Brandlb533e262008-05-25 18:19:30 +0000582def test_main(verbose=None):
583 try:
584 cwd = os.getcwd()
Senthil Kumaraneb3b6ed2010-09-30 06:34:02 +0000585 support.run_unittest(BaseHTTPRequestHandlerTestCase,
586 BaseHTTPServerTestCase,
Georg Brandlb533e262008-05-25 18:19:30 +0000587 SimpleHTTPServerTestCase,
588 CGIHTTPServerTestCase
589 )
590 finally:
591 os.chdir(cwd)
592
593if __name__ == '__main__':
594 test_main()