blob: 672c187a42836d23ced26ffe2dd13bc929639e87 [file] [log] [blame]
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Brandlf899dfa2008-05-18 09:12:20 +00007import os
8import sys
Senthil Kumaranb643fc62010-09-30 06:40:56 +00009import re
Georg Brandlf899dfa2008-05-18 09:12:20 +000010import base64
Martin Panter0cf2cf22016-04-18 03:45:18 +000011import ntpath
Georg Brandlf899dfa2008-05-18 09:12:20 +000012import shutil
13import urllib
14import httplib
15import tempfile
Georg Brandlf899dfa2008-05-18 09:12:20 +000016import unittest
Senthil Kumaran5f7e7342012-04-12 02:23:23 +080017import CGIHTTPServer
Senthil Kumaranb643fc62010-09-30 06:40:56 +000018
Senthil Kumaran5f7e7342012-04-12 02:23:23 +080019
20from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
21from SimpleHTTPServer import SimpleHTTPRequestHandler
22from CGIHTTPServer import CGIHTTPRequestHandler
Senthil Kumaranb643fc62010-09-30 06:40:56 +000023from StringIO import StringIO
Georg Brandlf899dfa2008-05-18 09:12:20 +000024from test import test_support
Senthil Kumaran5f7e7342012-04-12 02:23:23 +080025
26
Victor Stinner6a102812010-04-27 23:55:59 +000027threading = test_support.import_module('threading')
Georg Brandlf899dfa2008-05-18 09:12:20 +000028
29
30class NoLogRequestHandler:
31 def log_message(self, *args):
32 # don't write log messages to stderr
33 pass
34
Antoine Pitrou2623ae92010-12-16 17:18:49 +000035class SocketlessRequestHandler(SimpleHTTPRequestHandler):
Senthil Kumaranb643fc62010-09-30 06:40:56 +000036 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()
Antoine Pitrou2623ae92010-12-16 17:18:49 +000045 self.wfile.write(b'<html><body>Data</body></html>\r\n')
Senthil Kumaranb643fc62010-09-30 06:40:56 +000046
Senthil Kumaran5f7e7342012-04-12 02:23:23 +080047 def log_message(self, fmt, *args):
Senthil Kumaranb643fc62010-09-30 06:40:56 +000048 pass
49
50
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Brandlf899dfa2008-05-18 09:12:20 +000056
57 def run(self):
58 self.server = HTTPServer(('', 0), self.request_handler)
59 self.test_object.PORT = self.server.socket.getsockname()[1]
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000060 self.test_object.server_started.set()
61 self.test_object = None
Georg Brandlf899dfa2008-05-18 09:12:20 +000062 try:
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000063 self.server.serve_forever(0.05)
Georg Brandlf899dfa2008-05-18 09:12:20 +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 Pitrou85bd5872009-10-27 18:50:52 +000073 self._threads = test_support.threading_setup()
Nick Coghlan87c03b32009-10-17 15:23:08 +000074 os.environ = test_support.EnvironmentVarGuard()
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000075 self.server_started = threading.Event()
Georg Brandlf899dfa2008-05-18 09:12:20 +000076 self.thread = TestServerThread(self, self.request_handler)
77 self.thread.start()
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000078 self.server_started.wait()
Georg Brandlf899dfa2008-05-18 09:12:20 +000079
80 def tearDown(self):
Georg Brandlf899dfa2008-05-18 09:12:20 +000081 self.thread.stop()
Nick Coghlan87c03b32009-10-17 15:23:08 +000082 os.environ.__exit__()
Antoine Pitrou85bd5872009-10-27 18:50:52 +000083 test_support.threading_cleanup(*self._threads)
Georg Brandlf899dfa2008-05-18 09:12:20 +000084
85 def request(self, uri, method='GET', body=None, headers={}):
86 self.connection = httplib.HTTPConnection('localhost', self.PORT)
87 self.connection.request(method, uri, body, headers)
88 return self.connection.getresponse()
89
Senthil Kumaranb643fc62010-09-30 06:40:56 +000090class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melottic2077b02011-03-16 12:34:31 +020091 """Test the functionality of the BaseHTTPServer focussing on
Senthil Kumaranb643fc62010-09-30 06:40:56 +000092 BaseHTTPRequestHandler.
93 """
94
95 HTTPResponseMatch = re.compile('HTTP/1.[0-9]+ 200 OK')
96
97 def setUp (self):
98 self.handler = SocketlessRequestHandler()
99
100 def send_typical_request(self, message):
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800101 input_msg = StringIO(message)
Senthil Kumaranb643fc62010-09-30 06:40:56 +0000102 output = StringIO()
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800103 self.handler.rfile = input_msg
Senthil Kumaranb643fc62010-09-30 06:40:56 +0000104 self.handler.wfile = output
105 self.handler.handle_one_request()
106 output.seek(0)
107 return output.readlines()
108
109 def verify_get_called(self):
110 self.assertTrue(self.handler.get_called)
111
112 def verify_expected_headers(self, headers):
113 for fieldName in 'Server: ', 'Date: ', 'Content-Type: ':
114 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
115
116 def verify_http_server_response(self, response):
117 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200118 self.assertIsNotNone(match)
Senthil Kumaranb643fc62010-09-30 06:40:56 +0000119
120 def test_http_1_1(self):
121 result = self.send_typical_request('GET / HTTP/1.1\r\n\r\n')
122 self.verify_http_server_response(result[0])
123 self.verify_expected_headers(result[1:-1])
124 self.verify_get_called()
125 self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
126
127 def test_http_1_0(self):
128 result = self.send_typical_request('GET / HTTP/1.0\r\n\r\n')
129 self.verify_http_server_response(result[0])
130 self.verify_expected_headers(result[1:-1])
131 self.verify_get_called()
132 self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
133
134 def test_http_0_9(self):
135 result = self.send_typical_request('GET / HTTP/0.9\r\n\r\n')
136 self.assertEqual(len(result), 1)
137 self.assertEqual(result[0], '<html><body>Data</body></html>\r\n')
138 self.verify_get_called()
139
140 def test_with_continue_1_0(self):
141 result = self.send_typical_request('GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
142 self.verify_http_server_response(result[0])
143 self.verify_expected_headers(result[1:-1])
144 self.verify_get_called()
145 self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
146
Antoine Pitrou2623ae92010-12-16 17:18:49 +0000147 def test_request_length(self):
148 # Issue #10714: huge request lines are discarded, to avoid Denial
149 # of Service attacks.
150 result = self.send_typical_request(b'GET ' + b'x' * 65537)
151 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
152 self.assertFalse(self.handler.get_called)
153
Georg Brandlf899dfa2008-05-18 09:12:20 +0000154
155class BaseHTTPServerTestCase(BaseTestCase):
156 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
157 protocol_version = 'HTTP/1.1'
158 default_request_version = 'HTTP/1.1'
159
160 def do_TEST(self):
161 self.send_response(204)
162 self.send_header('Content-Type', 'text/html')
163 self.send_header('Connection', 'close')
164 self.end_headers()
165
166 def do_KEEP(self):
167 self.send_response(204)
168 self.send_header('Content-Type', 'text/html')
169 self.send_header('Connection', 'keep-alive')
170 self.end_headers()
171
172 def do_KEYERROR(self):
173 self.send_error(999)
174
175 def do_CUSTOM(self):
176 self.send_response(999)
177 self.send_header('Content-Type', 'text/html')
178 self.send_header('Connection', 'close')
179 self.end_headers()
180
181 def setUp(self):
182 BaseTestCase.setUp(self)
183 self.con = httplib.HTTPConnection('localhost', self.PORT)
184 self.con.connect()
185
186 def test_command(self):
187 self.con.request('GET', '/')
188 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000189 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000190
191 def test_request_line_trimming(self):
192 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray3eb76fc2014-06-24 16:49:24 -0400193 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000194 self.con.endheaders()
195 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000196 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000197
198 def test_version_bogus(self):
199 self.con._http_vsn_str = 'FUBAR'
200 self.con.putrequest('GET', '/')
201 self.con.endheaders()
202 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000203 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000204
205 def test_version_digits(self):
206 self.con._http_vsn_str = 'HTTP/9.9.9'
207 self.con.putrequest('GET', '/')
208 self.con.endheaders()
209 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000210 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000211
212 def test_version_none_get(self):
213 self.con._http_vsn_str = ''
214 self.con.putrequest('GET', '/')
215 self.con.endheaders()
216 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000217 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000218
219 def test_version_none(self):
R David Murray3eb76fc2014-06-24 16:49:24 -0400220 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlf899dfa2008-05-18 09:12:20 +0000221 self.con._http_vsn_str = ''
R David Murray3eb76fc2014-06-24 16:49:24 -0400222 self.con.putrequest('CUSTOM', '/')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000223 self.con.endheaders()
224 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000225 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000226
227 def test_version_invalid(self):
228 self.con._http_vsn = 99
229 self.con._http_vsn_str = 'HTTP/9.9'
230 self.con.putrequest('GET', '/')
231 self.con.endheaders()
232 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000233 self.assertEqual(res.status, 505)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000234
235 def test_send_blank(self):
236 self.con._http_vsn_str = ''
237 self.con.putrequest('', '')
238 self.con.endheaders()
239 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000240 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000241
242 def test_header_close(self):
243 self.con.putrequest('GET', '/')
244 self.con.putheader('Connection', 'close')
245 self.con.endheaders()
246 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000247 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000248
249 def test_head_keep_alive(self):
250 self.con._http_vsn_str = 'HTTP/1.1'
251 self.con.putrequest('GET', '/')
252 self.con.putheader('Connection', 'keep-alive')
253 self.con.endheaders()
254 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000255 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000256
257 def test_handler(self):
258 self.con.request('TEST', '/')
259 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000260 self.assertEqual(res.status, 204)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000261
262 def test_return_header_keep_alive(self):
263 self.con.request('KEEP', '/')
264 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000265 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000266 self.con.request('TEST', '/')
Brian Curtin55b62512010-10-31 00:36:01 +0000267 self.addCleanup(self.con.close)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000268
269 def test_internal_key_error(self):
270 self.con.request('KEYERROR', '/')
271 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000272 self.assertEqual(res.status, 999)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000273
274 def test_return_custom_status(self):
275 self.con.request('CUSTOM', '/')
276 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000277 self.assertEqual(res.status, 999)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000278
279
280class SimpleHTTPServerTestCase(BaseTestCase):
281 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
282 pass
283
284 def setUp(self):
285 BaseTestCase.setUp(self)
Georg Brandl7bb16532008-05-20 06:47:31 +0000286 self.cwd = os.getcwd()
287 basetempdir = tempfile.gettempdir()
288 os.chdir(basetempdir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000289 self.data = 'We are the knights who say Ni!'
Georg Brandl7bb16532008-05-20 06:47:31 +0000290 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000291 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panteraf58c852016-04-09 04:56:10 +0000292 self.base_url = '/' + self.tempdir_name
Georg Brandl7bb16532008-05-20 06:47:31 +0000293 temp = open(os.path.join(self.tempdir, 'test'), 'wb')
294 temp.write(self.data)
295 temp.close()
Georg Brandlf899dfa2008-05-18 09:12:20 +0000296
297 def tearDown(self):
298 try:
Georg Brandl7bb16532008-05-20 06:47:31 +0000299 os.chdir(self.cwd)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000300 try:
301 shutil.rmtree(self.tempdir)
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800302 except OSError:
Georg Brandlf899dfa2008-05-18 09:12:20 +0000303 pass
304 finally:
305 BaseTestCase.tearDown(self)
306
307 def check_status_and_reason(self, response, status, data=None):
308 body = response.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000309 self.assertTrue(response)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000310 self.assertEqual(response.status, status)
311 self.assertIsNotNone(response.reason)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000312 if data:
313 self.assertEqual(data, body)
314
315 def test_get(self):
316 #constructs the path relative to the root directory of the HTTPServer
Martin Panteraf58c852016-04-09 04:56:10 +0000317 response = self.request(self.base_url + '/test')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000318 self.check_status_and_reason(response, 200, data=self.data)
Senthil Kumarand4fac042013-09-13 00:18:55 -0700319 # check for trailing "/" which should return 404. See Issue17324
Martin Panteraf58c852016-04-09 04:56:10 +0000320 response = self.request(self.base_url + '/test/')
Senthil Kumarand4fac042013-09-13 00:18:55 -0700321 self.check_status_and_reason(response, 404)
Martin Panteraf58c852016-04-09 04:56:10 +0000322 response = self.request(self.base_url + '/')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000323 self.check_status_and_reason(response, 200)
Martin Panteraf58c852016-04-09 04:56:10 +0000324 response = self.request(self.base_url)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000325 self.check_status_and_reason(response, 301)
Martin Panteraf58c852016-04-09 04:56:10 +0000326 response = self.request(self.base_url + '/?hi=2')
Benjamin Petersona71cfc52014-12-26 10:53:43 -0600327 self.check_status_and_reason(response, 200)
Martin Panteraf58c852016-04-09 04:56:10 +0000328 response = self.request(self.base_url + '?hi=1')
Benjamin Petersona71cfc52014-12-26 10:53:43 -0600329 self.check_status_and_reason(response, 301)
330 self.assertEqual(response.getheader("Location"),
Martin Panteraf58c852016-04-09 04:56:10 +0000331 self.base_url + "/?hi=1")
Georg Brandlf899dfa2008-05-18 09:12:20 +0000332 response = self.request('/ThisDoesNotExist')
333 self.check_status_and_reason(response, 404)
334 response = self.request('/' + 'ThisDoesNotExist' + '/')
335 self.check_status_and_reason(response, 404)
Benjamin Peterson3c0027b2014-04-04 13:59:33 -0400336 with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as fp:
Martin Panteraf58c852016-04-09 04:56:10 +0000337 response = self.request(self.base_url + '/')
Benjamin Peterson3c0027b2014-04-04 13:59:33 -0400338 self.check_status_and_reason(response, 200)
339 # chmod() doesn't work as expected on Windows, and filesystem
340 # permissions are ignored by root on Unix.
341 if os.name == 'posix' and os.geteuid() != 0:
342 os.chmod(self.tempdir, 0)
Martin Panteraf58c852016-04-09 04:56:10 +0000343 response = self.request(self.base_url + '/')
Benjamin Peterson3c0027b2014-04-04 13:59:33 -0400344 self.check_status_and_reason(response, 404)
345 os.chmod(self.tempdir, 0755)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000346
347 def test_head(self):
348 response = self.request(
Martin Panteraf58c852016-04-09 04:56:10 +0000349 self.base_url + '/test', method='HEAD')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000350 self.check_status_and_reason(response, 200)
351 self.assertEqual(response.getheader('content-length'),
352 str(len(self.data)))
353 self.assertEqual(response.getheader('content-type'),
354 'application/octet-stream')
355
356 def test_invalid_requests(self):
357 response = self.request('/', method='FOO')
358 self.check_status_and_reason(response, 501)
359 # requests must be case sensitive,so this should fail too
Terry Jan Reedy0daddbd2014-10-18 17:10:02 -0400360 response = self.request('/', method='custom')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000361 self.check_status_and_reason(response, 501)
362 response = self.request('/', method='GETs')
363 self.check_status_and_reason(response, 501)
364
Martin Panteraf58c852016-04-09 04:56:10 +0000365 def test_path_without_leading_slash(self):
366 response = self.request(self.tempdir_name + '/test')
Martin Panterec3c2452016-04-09 13:45:52 +0000367 self.check_status_and_reason(response, 200, data=self.data)
Martin Panteraf58c852016-04-09 04:56:10 +0000368 response = self.request(self.tempdir_name + '/test/')
Martin Panterec3c2452016-04-09 13:45:52 +0000369 self.check_status_and_reason(response, 404)
Martin Panteraf58c852016-04-09 04:56:10 +0000370 response = self.request(self.tempdir_name + '/')
Martin Panterec3c2452016-04-09 13:45:52 +0000371 self.check_status_and_reason(response, 200)
Martin Panteraf58c852016-04-09 04:56:10 +0000372 response = self.request(self.tempdir_name)
Martin Panterec3c2452016-04-09 13:45:52 +0000373 self.check_status_and_reason(response, 301)
Martin Panteraf58c852016-04-09 04:56:10 +0000374 response = self.request(self.tempdir_name + '/?hi=2')
Martin Panterec3c2452016-04-09 13:45:52 +0000375 self.check_status_and_reason(response, 200)
Martin Panteraf58c852016-04-09 04:56:10 +0000376 response = self.request(self.tempdir_name + '?hi=1')
Martin Panterec3c2452016-04-09 13:45:52 +0000377 self.check_status_and_reason(response, 301)
Martin Panteraf58c852016-04-09 04:56:10 +0000378 self.assertEqual(response.getheader("Location"),
379 self.tempdir_name + "/?hi=1")
380
Georg Brandlf899dfa2008-05-18 09:12:20 +0000381
382cgi_file1 = """\
383#!%s
384
385print "Content-type: text/html"
386print
387print "Hello World"
388"""
389
390cgi_file2 = """\
391#!%s
392import cgi
393
394print "Content-type: text/html"
395print
396
397form = cgi.FieldStorage()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000398print "%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
399 form.getfirst("bacon"))
Georg Brandlf899dfa2008-05-18 09:12:20 +0000400"""
401
Martin Pantercff22eb2015-10-03 05:38:07 +0000402cgi_file4 = """\
403#!%s
404import os
405
406print("Content-type: text/html")
407print()
408
409print(os.environ["%s"])
410"""
411
Charles-François Natali09f87142011-11-02 19:32:54 +0100412
413@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
414 "This test can't be run reliably as root (issue #13308).")
Georg Brandlf899dfa2008-05-18 09:12:20 +0000415class CGIHTTPServerTestCase(BaseTestCase):
416 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
417 pass
418
419 def setUp(self):
420 BaseTestCase.setUp(self)
421 self.parent_dir = tempfile.mkdtemp()
422 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deilyc8937622014-07-12 22:01:15 -0700423 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000424 os.mkdir(self.cgi_dir)
Ned Deilyc8937622014-07-12 22:01:15 -0700425 os.mkdir(self.cgi_child_dir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000426
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000427 # The shebang line should be pure ASCII: use symlink if possible.
428 # See issue #7668.
429 if hasattr(os, 'symlink'):
430 self.pythonexe = os.path.join(self.parent_dir, 'python')
431 os.symlink(sys.executable, self.pythonexe)
432 else:
433 self.pythonexe = sys.executable
434
Benjamin Peterson1ef959a2013-10-30 12:43:09 -0400435 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
436 with open(self.nocgi_path, 'w') as fp:
437 fp.write(cgi_file1 % self.pythonexe)
438 os.chmod(self.nocgi_path, 0777)
439
Georg Brandlf899dfa2008-05-18 09:12:20 +0000440 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
441 with open(self.file1_path, 'w') as file1:
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000442 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000443 os.chmod(self.file1_path, 0777)
444
445 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
446 with open(self.file2_path, 'w') as file2:
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000447 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000448 os.chmod(self.file2_path, 0777)
449
Ned Deilyc8937622014-07-12 22:01:15 -0700450 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
451 with open(self.file3_path, 'w') as file3:
452 file3.write(cgi_file1 % self.pythonexe)
453 os.chmod(self.file3_path, 0777)
454
Martin Pantercff22eb2015-10-03 05:38:07 +0000455 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
456 with open(self.file4_path, 'w') as file4:
457 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
458 os.chmod(self.file4_path, 0o777)
459
Georg Brandl7bb16532008-05-20 06:47:31 +0000460 self.cwd = os.getcwd()
Georg Brandlf899dfa2008-05-18 09:12:20 +0000461 os.chdir(self.parent_dir)
462
463 def tearDown(self):
464 try:
Georg Brandl7bb16532008-05-20 06:47:31 +0000465 os.chdir(self.cwd)
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000466 if self.pythonexe != sys.executable:
467 os.remove(self.pythonexe)
Benjamin Peterson1ef959a2013-10-30 12:43:09 -0400468 os.remove(self.nocgi_path)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000469 os.remove(self.file1_path)
470 os.remove(self.file2_path)
Ned Deilyc8937622014-07-12 22:01:15 -0700471 os.remove(self.file3_path)
Martin Pantercff22eb2015-10-03 05:38:07 +0000472 os.remove(self.file4_path)
Ned Deilyc8937622014-07-12 22:01:15 -0700473 os.rmdir(self.cgi_child_dir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000474 os.rmdir(self.cgi_dir)
475 os.rmdir(self.parent_dir)
476 finally:
477 BaseTestCase.tearDown(self)
478
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800479 def test_url_collapse_path(self):
Senthil Kumaranfb2e8742012-04-11 03:07:57 +0800480 # verify tail is the last portion and head is the rest on proper urls
Gregory P. Smith923ba362009-04-06 06:33:26 +0000481 test_vectors = {
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800482 '': '//',
Gregory P. Smith923ba362009-04-06 06:33:26 +0000483 '..': IndexError,
484 '/.//..': IndexError,
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800485 '/': '//',
486 '//': '//',
487 '/\\': '//\\',
488 '/.//': '//',
489 'cgi-bin/file1.py': '/cgi-bin/file1.py',
490 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
491 'a': '//a',
492 '/a': '//a',
493 '//a': '//a',
494 './a': '//a',
495 './C:/': '/C:/',
496 '/a/b': '/a/b',
497 '/a/b/': '/a/b/',
498 '/a/b/.': '/a/b/',
499 '/a/b/c/..': '/a/b/',
500 '/a/b/c/../d': '/a/b/d',
501 '/a/b/c/../d/e/../f': '/a/b/d/f',
502 '/a/b/c/../d/e/../../f': '/a/b/f',
503 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Gregory P. Smith923ba362009-04-06 06:33:26 +0000504 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800505 '/a/b/c/../d/e/../../../f': '/a/f',
506 '/a/b/c/../d/e/../../../../f': '//f',
Gregory P. Smith923ba362009-04-06 06:33:26 +0000507 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800508 '/a/b/c/../d/e/../../../../f/..': '//',
509 '/a/b/c/../d/e/../../../../f/../.': '//',
Gregory P. Smith923ba362009-04-06 06:33:26 +0000510 }
511 for path, expected in test_vectors.iteritems():
512 if isinstance(expected, type) and issubclass(expected, Exception):
513 self.assertRaises(expected,
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800514 CGIHTTPServer._url_collapse_path, path)
Gregory P. Smith923ba362009-04-06 06:33:26 +0000515 else:
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800516 actual = CGIHTTPServer._url_collapse_path(path)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000517 self.assertEqual(expected, actual,
518 msg='path = %r\nGot: %r\nWanted: %r' %
519 (path, actual, expected))
Gregory P. Smith923ba362009-04-06 06:33:26 +0000520
Georg Brandlf899dfa2008-05-18 09:12:20 +0000521 def test_headers_and_content(self):
522 res = self.request('/cgi-bin/file1.py')
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000523 self.assertEqual(('Hello World\n', 'text/html', 200),
524 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlf899dfa2008-05-18 09:12:20 +0000525
Benjamin Peterson1ef959a2013-10-30 12:43:09 -0400526 def test_issue19435(self):
527 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
528 self.assertEqual(res.status, 404)
529
Georg Brandlf899dfa2008-05-18 09:12:20 +0000530 def test_post(self):
531 params = urllib.urlencode({'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
532 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
533 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
534
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000535 self.assertEqual(res.read(), '1, python, 123456\n')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000536
537 def test_invaliduri(self):
538 res = self.request('/cgi-bin/invalid')
539 res.read()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000540 self.assertEqual(res.status, 404)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000541
542 def test_authorization(self):
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000543 headers = {'Authorization' : 'Basic %s' %
544 base64.b64encode('username:pass')}
Georg Brandlf899dfa2008-05-18 09:12:20 +0000545 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000546 self.assertEqual(('Hello World\n', 'text/html', 200),
547 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlf899dfa2008-05-18 09:12:20 +0000548
Gregory P. Smith923ba362009-04-06 06:33:26 +0000549 def test_no_leading_slash(self):
550 # http://bugs.python.org/issue2254
551 res = self.request('cgi-bin/file1.py')
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000552 self.assertEqual(('Hello World\n', 'text/html', 200),
Gregory P. Smith923ba362009-04-06 06:33:26 +0000553 (res.read(), res.getheader('Content-type'), res.status))
554
Senthil Kumarana9bd0cc2010-10-03 18:16:52 +0000555 def test_os_environ_is_not_altered(self):
556 signature = "Test CGI Server"
557 os.environ['SERVER_SOFTWARE'] = signature
558 res = self.request('/cgi-bin/file1.py')
559 self.assertEqual((b'Hello World\n', 'text/html', 200),
560 (res.read(), res.getheader('Content-type'), res.status))
561 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000562
Benjamin Peterson8d24d772014-06-14 18:36:29 -0700563 def test_urlquote_decoding_in_cgi_check(self):
564 res = self.request('/cgi-bin%2ffile1.py')
565 self.assertEqual((b'Hello World\n', 'text/html', 200),
566 (res.read(), res.getheader('Content-type'), res.status))
567
Ned Deilyc8937622014-07-12 22:01:15 -0700568 def test_nested_cgi_path_issue21323(self):
569 res = self.request('/cgi-bin/child-dir/file3.py')
570 self.assertEqual((b'Hello World\n', 'text/html', 200),
571 (res.read(), res.getheader('Content-type'), res.status))
572
Martin Pantercff22eb2015-10-03 05:38:07 +0000573 def test_query_with_multiple_question_mark(self):
574 res = self.request('/cgi-bin/file4.py?a=b?c=d')
575 self.assertEqual(
576 (b'a=b?c=d\n', 'text/html', 200),
577 (res.read(), res.getheader('Content-type'), res.status))
578
Martin Panter74c76c82015-10-03 05:55:46 +0000579 def test_query_with_continuous_slashes(self):
580 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
581 self.assertEqual(
582 (b'k=aa%2F%2Fbb&//q//p//=//a//b//\n',
583 'text/html', 200),
584 (res.read(), res.getheader('Content-type'), res.status))
585
Antoine Pitrou47d9b0e2010-12-16 17:11:34 +0000586
Antoine Pitrou47d9b0e2010-12-16 17:11:34 +0000587class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
588 """ Test url parsing """
589 def setUp(self):
590 self.translated = os.getcwd()
591 self.translated = os.path.join(self.translated, 'filename')
592 self.handler = SocketlessRequestHandler()
593
594 def test_query_arguments(self):
595 path = self.handler.translate_path('/filename')
596 self.assertEqual(path, self.translated)
597 path = self.handler.translate_path('/filename?foo=bar')
598 self.assertEqual(path, self.translated)
599 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
600 self.assertEqual(path, self.translated)
601
602 def test_start_with_double_slash(self):
603 path = self.handler.translate_path('//filename')
604 self.assertEqual(path, self.translated)
605 path = self.handler.translate_path('//filename?foo=bar')
606 self.assertEqual(path, self.translated)
607
Martin Panter0cf2cf22016-04-18 03:45:18 +0000608 def test_windows_colon(self):
609 import SimpleHTTPServer
610 with test_support.swap_attr(SimpleHTTPServer.os, 'path', ntpath):
611 path = self.handler.translate_path('c:c:c:foo/filename')
612 path = path.replace(ntpath.sep, os.sep)
613 self.assertEqual(path, self.translated)
614
615 path = self.handler.translate_path('\\c:../filename')
616 path = path.replace(ntpath.sep, os.sep)
617 self.assertEqual(path, self.translated)
618
619 path = self.handler.translate_path('c:\\c:..\\foo/filename')
620 path = path.replace(ntpath.sep, os.sep)
621 self.assertEqual(path, self.translated)
622
623 path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
624 path = path.replace(ntpath.sep, os.sep)
625 self.assertEqual(path, self.translated)
626
Antoine Pitrou47d9b0e2010-12-16 17:11:34 +0000627
Georg Brandlf899dfa2008-05-18 09:12:20 +0000628def test_main(verbose=None):
629 try:
630 cwd = os.getcwd()
Senthil Kumaranb643fc62010-09-30 06:40:56 +0000631 test_support.run_unittest(BaseHTTPRequestHandlerTestCase,
Antoine Pitrou47d9b0e2010-12-16 17:11:34 +0000632 SimpleHTTPRequestHandlerTestCase,
Senthil Kumaranb643fc62010-09-30 06:40:56 +0000633 BaseHTTPServerTestCase,
634 SimpleHTTPServerTestCase,
635 CGIHTTPServerTestCase
636 )
Georg Brandlf899dfa2008-05-18 09:12:20 +0000637 finally:
638 os.chdir(cwd)
639
640if __name__ == '__main__':
641 test_main()