blob: ab74e5b8659e216353675b08abb1a96db93ffd45 [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
11import shutil
12import urllib
13import httplib
14import tempfile
Georg Brandlf899dfa2008-05-18 09:12:20 +000015import unittest
Senthil Kumaran5f7e7342012-04-12 02:23:23 +080016import CGIHTTPServer
Senthil Kumaranb643fc62010-09-30 06:40:56 +000017
Senthil Kumaran5f7e7342012-04-12 02:23:23 +080018
19from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
20from SimpleHTTPServer import SimpleHTTPRequestHandler
21from CGIHTTPServer import CGIHTTPRequestHandler
Senthil Kumaranb643fc62010-09-30 06:40:56 +000022from StringIO import StringIO
Georg Brandlf899dfa2008-05-18 09:12:20 +000023from test import test_support
Senthil Kumaran5f7e7342012-04-12 02:23:23 +080024
25
Victor Stinner6a102812010-04-27 23:55:59 +000026threading = test_support.import_module('threading')
Georg Brandlf899dfa2008-05-18 09:12:20 +000027
28
29class NoLogRequestHandler:
30 def log_message(self, *args):
31 # don't write log messages to stderr
32 pass
33
Antoine Pitrou2623ae92010-12-16 17:18:49 +000034class SocketlessRequestHandler(SimpleHTTPRequestHandler):
Senthil Kumaranb643fc62010-09-30 06:40:56 +000035 def __init__(self):
36 self.get_called = False
37 self.protocol_version = "HTTP/1.1"
38
39 def do_GET(self):
40 self.get_called = True
41 self.send_response(200)
42 self.send_header('Content-Type', 'text/html')
43 self.end_headers()
Antoine Pitrou2623ae92010-12-16 17:18:49 +000044 self.wfile.write(b'<html><body>Data</body></html>\r\n')
Senthil Kumaranb643fc62010-09-30 06:40:56 +000045
Senthil Kumaran5f7e7342012-04-12 02:23:23 +080046 def log_message(self, fmt, *args):
Senthil Kumaranb643fc62010-09-30 06:40:56 +000047 pass
48
49
Georg Brandlf899dfa2008-05-18 09:12:20 +000050class TestServerThread(threading.Thread):
51 def __init__(self, test_object, request_handler):
52 threading.Thread.__init__(self)
53 self.request_handler = request_handler
54 self.test_object = test_object
Georg Brandlf899dfa2008-05-18 09:12:20 +000055
56 def run(self):
57 self.server = HTTPServer(('', 0), self.request_handler)
58 self.test_object.PORT = self.server.socket.getsockname()[1]
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000059 self.test_object.server_started.set()
60 self.test_object = None
Georg Brandlf899dfa2008-05-18 09:12:20 +000061 try:
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000062 self.server.serve_forever(0.05)
Georg Brandlf899dfa2008-05-18 09:12:20 +000063 finally:
64 self.server.server_close()
65
66 def stop(self):
67 self.server.shutdown()
68
69
70class BaseTestCase(unittest.TestCase):
71 def setUp(self):
Antoine Pitrou85bd5872009-10-27 18:50:52 +000072 self._threads = test_support.threading_setup()
Nick Coghlan87c03b32009-10-17 15:23:08 +000073 os.environ = test_support.EnvironmentVarGuard()
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000074 self.server_started = threading.Event()
Georg Brandlf899dfa2008-05-18 09:12:20 +000075 self.thread = TestServerThread(self, self.request_handler)
76 self.thread.start()
Antoine Pitrou1ca8c192010-04-25 21:15:50 +000077 self.server_started.wait()
Georg Brandlf899dfa2008-05-18 09:12:20 +000078
79 def tearDown(self):
Georg Brandlf899dfa2008-05-18 09:12:20 +000080 self.thread.stop()
Nick Coghlan87c03b32009-10-17 15:23:08 +000081 os.environ.__exit__()
Antoine Pitrou85bd5872009-10-27 18:50:52 +000082 test_support.threading_cleanup(*self._threads)
Georg Brandlf899dfa2008-05-18 09:12:20 +000083
84 def request(self, uri, method='GET', body=None, headers={}):
85 self.connection = httplib.HTTPConnection('localhost', self.PORT)
86 self.connection.request(method, uri, body, headers)
87 return self.connection.getresponse()
88
Senthil Kumaranb643fc62010-09-30 06:40:56 +000089class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
Ezio Melottic2077b02011-03-16 12:34:31 +020090 """Test the functionality of the BaseHTTPServer focussing on
Senthil Kumaranb643fc62010-09-30 06:40:56 +000091 BaseHTTPRequestHandler.
92 """
93
94 HTTPResponseMatch = re.compile('HTTP/1.[0-9]+ 200 OK')
95
96 def setUp (self):
97 self.handler = SocketlessRequestHandler()
98
99 def send_typical_request(self, message):
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800100 input_msg = StringIO(message)
Senthil Kumaranb643fc62010-09-30 06:40:56 +0000101 output = StringIO()
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800102 self.handler.rfile = input_msg
Senthil Kumaranb643fc62010-09-30 06:40:56 +0000103 self.handler.wfile = output
104 self.handler.handle_one_request()
105 output.seek(0)
106 return output.readlines()
107
108 def verify_get_called(self):
109 self.assertTrue(self.handler.get_called)
110
111 def verify_expected_headers(self, headers):
112 for fieldName in 'Server: ', 'Date: ', 'Content-Type: ':
113 self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
114
115 def verify_http_server_response(self, response):
116 match = self.HTTPResponseMatch.search(response)
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200117 self.assertIsNotNone(match)
Senthil Kumaranb643fc62010-09-30 06:40:56 +0000118
119 def test_http_1_1(self):
120 result = self.send_typical_request('GET / HTTP/1.1\r\n\r\n')
121 self.verify_http_server_response(result[0])
122 self.verify_expected_headers(result[1:-1])
123 self.verify_get_called()
124 self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
125
126 def test_http_1_0(self):
127 result = self.send_typical_request('GET / HTTP/1.0\r\n\r\n')
128 self.verify_http_server_response(result[0])
129 self.verify_expected_headers(result[1:-1])
130 self.verify_get_called()
131 self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
132
133 def test_http_0_9(self):
134 result = self.send_typical_request('GET / HTTP/0.9\r\n\r\n')
135 self.assertEqual(len(result), 1)
136 self.assertEqual(result[0], '<html><body>Data</body></html>\r\n')
137 self.verify_get_called()
138
139 def test_with_continue_1_0(self):
140 result = self.send_typical_request('GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
141 self.verify_http_server_response(result[0])
142 self.verify_expected_headers(result[1:-1])
143 self.verify_get_called()
144 self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
145
Antoine Pitrou2623ae92010-12-16 17:18:49 +0000146 def test_request_length(self):
147 # Issue #10714: huge request lines are discarded, to avoid Denial
148 # of Service attacks.
149 result = self.send_typical_request(b'GET ' + b'x' * 65537)
150 self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
151 self.assertFalse(self.handler.get_called)
152
Georg Brandlf899dfa2008-05-18 09:12:20 +0000153
154class BaseHTTPServerTestCase(BaseTestCase):
155 class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
156 protocol_version = 'HTTP/1.1'
157 default_request_version = 'HTTP/1.1'
158
159 def do_TEST(self):
160 self.send_response(204)
161 self.send_header('Content-Type', 'text/html')
162 self.send_header('Connection', 'close')
163 self.end_headers()
164
165 def do_KEEP(self):
166 self.send_response(204)
167 self.send_header('Content-Type', 'text/html')
168 self.send_header('Connection', 'keep-alive')
169 self.end_headers()
170
171 def do_KEYERROR(self):
172 self.send_error(999)
173
174 def do_CUSTOM(self):
175 self.send_response(999)
176 self.send_header('Content-Type', 'text/html')
177 self.send_header('Connection', 'close')
178 self.end_headers()
179
180 def setUp(self):
181 BaseTestCase.setUp(self)
182 self.con = httplib.HTTPConnection('localhost', self.PORT)
183 self.con.connect()
184
185 def test_command(self):
186 self.con.request('GET', '/')
187 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000188 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000189
190 def test_request_line_trimming(self):
191 self.con._http_vsn_str = 'HTTP/1.1\n'
R David Murray3eb76fc2014-06-24 16:49:24 -0400192 self.con.putrequest('XYZBOGUS', '/')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000193 self.con.endheaders()
194 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000195 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000196
197 def test_version_bogus(self):
198 self.con._http_vsn_str = 'FUBAR'
199 self.con.putrequest('GET', '/')
200 self.con.endheaders()
201 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000202 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000203
204 def test_version_digits(self):
205 self.con._http_vsn_str = 'HTTP/9.9.9'
206 self.con.putrequest('GET', '/')
207 self.con.endheaders()
208 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000209 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000210
211 def test_version_none_get(self):
212 self.con._http_vsn_str = ''
213 self.con.putrequest('GET', '/')
214 self.con.endheaders()
215 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000216 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000217
218 def test_version_none(self):
R David Murray3eb76fc2014-06-24 16:49:24 -0400219 # Test that a valid method is rejected when not HTTP/1.x
Georg Brandlf899dfa2008-05-18 09:12:20 +0000220 self.con._http_vsn_str = ''
R David Murray3eb76fc2014-06-24 16:49:24 -0400221 self.con.putrequest('CUSTOM', '/')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000222 self.con.endheaders()
223 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000224 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000225
226 def test_version_invalid(self):
227 self.con._http_vsn = 99
228 self.con._http_vsn_str = 'HTTP/9.9'
229 self.con.putrequest('GET', '/')
230 self.con.endheaders()
231 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000232 self.assertEqual(res.status, 505)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000233
234 def test_send_blank(self):
235 self.con._http_vsn_str = ''
236 self.con.putrequest('', '')
237 self.con.endheaders()
238 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000239 self.assertEqual(res.status, 400)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000240
241 def test_header_close(self):
242 self.con.putrequest('GET', '/')
243 self.con.putheader('Connection', 'close')
244 self.con.endheaders()
245 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000246 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000247
248 def test_head_keep_alive(self):
249 self.con._http_vsn_str = 'HTTP/1.1'
250 self.con.putrequest('GET', '/')
251 self.con.putheader('Connection', 'keep-alive')
252 self.con.endheaders()
253 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000254 self.assertEqual(res.status, 501)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000255
256 def test_handler(self):
257 self.con.request('TEST', '/')
258 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000259 self.assertEqual(res.status, 204)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000260
261 def test_return_header_keep_alive(self):
262 self.con.request('KEEP', '/')
263 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000264 self.assertEqual(res.getheader('Connection'), 'keep-alive')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000265 self.con.request('TEST', '/')
Brian Curtin55b62512010-10-31 00:36:01 +0000266 self.addCleanup(self.con.close)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000267
268 def test_internal_key_error(self):
269 self.con.request('KEYERROR', '/')
270 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000271 self.assertEqual(res.status, 999)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000272
273 def test_return_custom_status(self):
274 self.con.request('CUSTOM', '/')
275 res = self.con.getresponse()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000276 self.assertEqual(res.status, 999)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000277
278
279class SimpleHTTPServerTestCase(BaseTestCase):
280 class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
281 pass
282
283 def setUp(self):
284 BaseTestCase.setUp(self)
Georg Brandl7bb16532008-05-20 06:47:31 +0000285 self.cwd = os.getcwd()
286 basetempdir = tempfile.gettempdir()
287 os.chdir(basetempdir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000288 self.data = 'We are the knights who say Ni!'
Georg Brandl7bb16532008-05-20 06:47:31 +0000289 self.tempdir = tempfile.mkdtemp(dir=basetempdir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000290 self.tempdir_name = os.path.basename(self.tempdir)
Martin Panteraf58c852016-04-09 04:56:10 +0000291 self.base_url = '/' + self.tempdir_name
Georg Brandl7bb16532008-05-20 06:47:31 +0000292 temp = open(os.path.join(self.tempdir, 'test'), 'wb')
293 temp.write(self.data)
294 temp.close()
Georg Brandlf899dfa2008-05-18 09:12:20 +0000295
296 def tearDown(self):
297 try:
Georg Brandl7bb16532008-05-20 06:47:31 +0000298 os.chdir(self.cwd)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000299 try:
300 shutil.rmtree(self.tempdir)
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800301 except OSError:
Georg Brandlf899dfa2008-05-18 09:12:20 +0000302 pass
303 finally:
304 BaseTestCase.tearDown(self)
305
306 def check_status_and_reason(self, response, status, data=None):
307 body = response.read()
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000308 self.assertTrue(response)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000309 self.assertEqual(response.status, status)
310 self.assertIsNotNone(response.reason)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000311 if data:
312 self.assertEqual(data, body)
313
314 def test_get(self):
315 #constructs the path relative to the root directory of the HTTPServer
Martin Panteraf58c852016-04-09 04:56:10 +0000316 response = self.request(self.base_url + '/test')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000317 self.check_status_and_reason(response, 200, data=self.data)
Senthil Kumarand4fac042013-09-13 00:18:55 -0700318 # check for trailing "/" which should return 404. See Issue17324
Martin Panteraf58c852016-04-09 04:56:10 +0000319 response = self.request(self.base_url + '/test/')
Senthil Kumarand4fac042013-09-13 00:18:55 -0700320 self.check_status_and_reason(response, 404)
Martin Panteraf58c852016-04-09 04:56:10 +0000321 response = self.request(self.base_url + '/')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000322 self.check_status_and_reason(response, 200)
Martin Panteraf58c852016-04-09 04:56:10 +0000323 response = self.request(self.base_url)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000324 self.check_status_and_reason(response, 301)
Martin Panteraf58c852016-04-09 04:56:10 +0000325 response = self.request(self.base_url + '/?hi=2')
Benjamin Petersona71cfc52014-12-26 10:53:43 -0600326 self.check_status_and_reason(response, 200)
Martin Panteraf58c852016-04-09 04:56:10 +0000327 response = self.request(self.base_url + '?hi=1')
Benjamin Petersona71cfc52014-12-26 10:53:43 -0600328 self.check_status_and_reason(response, 301)
329 self.assertEqual(response.getheader("Location"),
Martin Panteraf58c852016-04-09 04:56:10 +0000330 self.base_url + "/?hi=1")
Georg Brandlf899dfa2008-05-18 09:12:20 +0000331 response = self.request('/ThisDoesNotExist')
332 self.check_status_and_reason(response, 404)
333 response = self.request('/' + 'ThisDoesNotExist' + '/')
334 self.check_status_and_reason(response, 404)
Benjamin Peterson3c0027b2014-04-04 13:59:33 -0400335 with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as fp:
Martin Panteraf58c852016-04-09 04:56:10 +0000336 response = self.request(self.base_url + '/')
Benjamin Peterson3c0027b2014-04-04 13:59:33 -0400337 self.check_status_and_reason(response, 200)
338 # chmod() doesn't work as expected on Windows, and filesystem
339 # permissions are ignored by root on Unix.
340 if os.name == 'posix' and os.geteuid() != 0:
341 os.chmod(self.tempdir, 0)
Martin Panteraf58c852016-04-09 04:56:10 +0000342 response = self.request(self.base_url + '/')
Benjamin Peterson3c0027b2014-04-04 13:59:33 -0400343 self.check_status_and_reason(response, 404)
344 os.chmod(self.tempdir, 0755)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000345
346 def test_head(self):
347 response = self.request(
Martin Panteraf58c852016-04-09 04:56:10 +0000348 self.base_url + '/test', method='HEAD')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000349 self.check_status_and_reason(response, 200)
350 self.assertEqual(response.getheader('content-length'),
351 str(len(self.data)))
352 self.assertEqual(response.getheader('content-type'),
353 'application/octet-stream')
354
355 def test_invalid_requests(self):
356 response = self.request('/', method='FOO')
357 self.check_status_and_reason(response, 501)
358 # requests must be case sensitive,so this should fail too
Terry Jan Reedy0daddbd2014-10-18 17:10:02 -0400359 response = self.request('/', method='custom')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000360 self.check_status_and_reason(response, 501)
361 response = self.request('/', method='GETs')
362 self.check_status_and_reason(response, 501)
363
Martin Panteraf58c852016-04-09 04:56:10 +0000364 def test_path_without_leading_slash(self):
365 response = self.request(self.tempdir_name + '/test')
366 self.check_status_and_reason(response, HTTPStatus.OK, data=self.data)
367 response = self.request(self.tempdir_name + '/test/')
368 self.check_status_and_reason(response, HTTPStatus.NOT_FOUND)
369 response = self.request(self.tempdir_name + '/')
370 self.check_status_and_reason(response, HTTPStatus.OK)
371 response = self.request(self.tempdir_name)
372 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
373 response = self.request(self.tempdir_name + '/?hi=2')
374 self.check_status_and_reason(response, HTTPStatus.OK)
375 response = self.request(self.tempdir_name + '?hi=1')
376 self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY)
377 self.assertEqual(response.getheader("Location"),
378 self.tempdir_name + "/?hi=1")
379
Georg Brandlf899dfa2008-05-18 09:12:20 +0000380
381cgi_file1 = """\
382#!%s
383
384print "Content-type: text/html"
385print
386print "Hello World"
387"""
388
389cgi_file2 = """\
390#!%s
391import cgi
392
393print "Content-type: text/html"
394print
395
396form = cgi.FieldStorage()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000397print "%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
398 form.getfirst("bacon"))
Georg Brandlf899dfa2008-05-18 09:12:20 +0000399"""
400
Martin Pantercff22eb2015-10-03 05:38:07 +0000401cgi_file4 = """\
402#!%s
403import os
404
405print("Content-type: text/html")
406print()
407
408print(os.environ["%s"])
409"""
410
Charles-François Natali09f87142011-11-02 19:32:54 +0100411
412@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
413 "This test can't be run reliably as root (issue #13308).")
Georg Brandlf899dfa2008-05-18 09:12:20 +0000414class CGIHTTPServerTestCase(BaseTestCase):
415 class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
416 pass
417
418 def setUp(self):
419 BaseTestCase.setUp(self)
420 self.parent_dir = tempfile.mkdtemp()
421 self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
Ned Deilyc8937622014-07-12 22:01:15 -0700422 self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000423 os.mkdir(self.cgi_dir)
Ned Deilyc8937622014-07-12 22:01:15 -0700424 os.mkdir(self.cgi_child_dir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000425
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000426 # The shebang line should be pure ASCII: use symlink if possible.
427 # See issue #7668.
428 if hasattr(os, 'symlink'):
429 self.pythonexe = os.path.join(self.parent_dir, 'python')
430 os.symlink(sys.executable, self.pythonexe)
431 else:
432 self.pythonexe = sys.executable
433
Benjamin Peterson1ef959a2013-10-30 12:43:09 -0400434 self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
435 with open(self.nocgi_path, 'w') as fp:
436 fp.write(cgi_file1 % self.pythonexe)
437 os.chmod(self.nocgi_path, 0777)
438
Georg Brandlf899dfa2008-05-18 09:12:20 +0000439 self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
440 with open(self.file1_path, 'w') as file1:
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000441 file1.write(cgi_file1 % self.pythonexe)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000442 os.chmod(self.file1_path, 0777)
443
444 self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
445 with open(self.file2_path, 'w') as file2:
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000446 file2.write(cgi_file2 % self.pythonexe)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000447 os.chmod(self.file2_path, 0777)
448
Ned Deilyc8937622014-07-12 22:01:15 -0700449 self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
450 with open(self.file3_path, 'w') as file3:
451 file3.write(cgi_file1 % self.pythonexe)
452 os.chmod(self.file3_path, 0777)
453
Martin Pantercff22eb2015-10-03 05:38:07 +0000454 self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
455 with open(self.file4_path, 'w') as file4:
456 file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
457 os.chmod(self.file4_path, 0o777)
458
Georg Brandl7bb16532008-05-20 06:47:31 +0000459 self.cwd = os.getcwd()
Georg Brandlf899dfa2008-05-18 09:12:20 +0000460 os.chdir(self.parent_dir)
461
462 def tearDown(self):
463 try:
Georg Brandl7bb16532008-05-20 06:47:31 +0000464 os.chdir(self.cwd)
Florent Xicluna0805e6e2010-03-22 17:18:18 +0000465 if self.pythonexe != sys.executable:
466 os.remove(self.pythonexe)
Benjamin Peterson1ef959a2013-10-30 12:43:09 -0400467 os.remove(self.nocgi_path)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000468 os.remove(self.file1_path)
469 os.remove(self.file2_path)
Ned Deilyc8937622014-07-12 22:01:15 -0700470 os.remove(self.file3_path)
Martin Pantercff22eb2015-10-03 05:38:07 +0000471 os.remove(self.file4_path)
Ned Deilyc8937622014-07-12 22:01:15 -0700472 os.rmdir(self.cgi_child_dir)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000473 os.rmdir(self.cgi_dir)
474 os.rmdir(self.parent_dir)
475 finally:
476 BaseTestCase.tearDown(self)
477
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800478 def test_url_collapse_path(self):
Senthil Kumaranfb2e8742012-04-11 03:07:57 +0800479 # verify tail is the last portion and head is the rest on proper urls
Gregory P. Smith923ba362009-04-06 06:33:26 +0000480 test_vectors = {
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800481 '': '//',
Gregory P. Smith923ba362009-04-06 06:33:26 +0000482 '..': IndexError,
483 '/.//..': IndexError,
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800484 '/': '//',
485 '//': '//',
486 '/\\': '//\\',
487 '/.//': '//',
488 'cgi-bin/file1.py': '/cgi-bin/file1.py',
489 '/cgi-bin/file1.py': '/cgi-bin/file1.py',
490 'a': '//a',
491 '/a': '//a',
492 '//a': '//a',
493 './a': '//a',
494 './C:/': '/C:/',
495 '/a/b': '/a/b',
496 '/a/b/': '/a/b/',
497 '/a/b/.': '/a/b/',
498 '/a/b/c/..': '/a/b/',
499 '/a/b/c/../d': '/a/b/d',
500 '/a/b/c/../d/e/../f': '/a/b/d/f',
501 '/a/b/c/../d/e/../../f': '/a/b/f',
502 '/a/b/c/../d/e/.././././..//f': '/a/b/f',
Gregory P. Smith923ba362009-04-06 06:33:26 +0000503 '../a/b/c/../d/e/.././././..//f': IndexError,
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800504 '/a/b/c/../d/e/../../../f': '/a/f',
505 '/a/b/c/../d/e/../../../../f': '//f',
Gregory P. Smith923ba362009-04-06 06:33:26 +0000506 '/a/b/c/../d/e/../../../../../f': IndexError,
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800507 '/a/b/c/../d/e/../../../../f/..': '//',
508 '/a/b/c/../d/e/../../../../f/../.': '//',
Gregory P. Smith923ba362009-04-06 06:33:26 +0000509 }
510 for path, expected in test_vectors.iteritems():
511 if isinstance(expected, type) and issubclass(expected, Exception):
512 self.assertRaises(expected,
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800513 CGIHTTPServer._url_collapse_path, path)
Gregory P. Smith923ba362009-04-06 06:33:26 +0000514 else:
Senthil Kumaran5f7e7342012-04-12 02:23:23 +0800515 actual = CGIHTTPServer._url_collapse_path(path)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000516 self.assertEqual(expected, actual,
517 msg='path = %r\nGot: %r\nWanted: %r' %
518 (path, actual, expected))
Gregory P. Smith923ba362009-04-06 06:33:26 +0000519
Georg Brandlf899dfa2008-05-18 09:12:20 +0000520 def test_headers_and_content(self):
521 res = self.request('/cgi-bin/file1.py')
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000522 self.assertEqual(('Hello World\n', 'text/html', 200),
523 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlf899dfa2008-05-18 09:12:20 +0000524
Benjamin Peterson1ef959a2013-10-30 12:43:09 -0400525 def test_issue19435(self):
526 res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
527 self.assertEqual(res.status, 404)
528
Georg Brandlf899dfa2008-05-18 09:12:20 +0000529 def test_post(self):
530 params = urllib.urlencode({'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
531 headers = {'Content-type' : 'application/x-www-form-urlencoded'}
532 res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
533
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000534 self.assertEqual(res.read(), '1, python, 123456\n')
Georg Brandlf899dfa2008-05-18 09:12:20 +0000535
536 def test_invaliduri(self):
537 res = self.request('/cgi-bin/invalid')
538 res.read()
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000539 self.assertEqual(res.status, 404)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000540
541 def test_authorization(self):
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000542 headers = {'Authorization' : 'Basic %s' %
543 base64.b64encode('username:pass')}
Georg Brandlf899dfa2008-05-18 09:12:20 +0000544 res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000545 self.assertEqual(('Hello World\n', 'text/html', 200),
546 (res.read(), res.getheader('Content-type'), res.status))
Georg Brandlf899dfa2008-05-18 09:12:20 +0000547
Gregory P. Smith923ba362009-04-06 06:33:26 +0000548 def test_no_leading_slash(self):
549 # http://bugs.python.org/issue2254
550 res = self.request('cgi-bin/file1.py')
Florent Xiclunabc27c6a2010-03-19 18:34:55 +0000551 self.assertEqual(('Hello World\n', 'text/html', 200),
Gregory P. Smith923ba362009-04-06 06:33:26 +0000552 (res.read(), res.getheader('Content-type'), res.status))
553
Senthil Kumarana9bd0cc2010-10-03 18:16:52 +0000554 def test_os_environ_is_not_altered(self):
555 signature = "Test CGI Server"
556 os.environ['SERVER_SOFTWARE'] = signature
557 res = self.request('/cgi-bin/file1.py')
558 self.assertEqual((b'Hello World\n', 'text/html', 200),
559 (res.read(), res.getheader('Content-type'), res.status))
560 self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
Georg Brandlf899dfa2008-05-18 09:12:20 +0000561
Benjamin Peterson8d24d772014-06-14 18:36:29 -0700562 def test_urlquote_decoding_in_cgi_check(self):
563 res = self.request('/cgi-bin%2ffile1.py')
564 self.assertEqual((b'Hello World\n', 'text/html', 200),
565 (res.read(), res.getheader('Content-type'), res.status))
566
Ned Deilyc8937622014-07-12 22:01:15 -0700567 def test_nested_cgi_path_issue21323(self):
568 res = self.request('/cgi-bin/child-dir/file3.py')
569 self.assertEqual((b'Hello World\n', 'text/html', 200),
570 (res.read(), res.getheader('Content-type'), res.status))
571
Martin Pantercff22eb2015-10-03 05:38:07 +0000572 def test_query_with_multiple_question_mark(self):
573 res = self.request('/cgi-bin/file4.py?a=b?c=d')
574 self.assertEqual(
575 (b'a=b?c=d\n', 'text/html', 200),
576 (res.read(), res.getheader('Content-type'), res.status))
577
Martin Panter74c76c82015-10-03 05:55:46 +0000578 def test_query_with_continuous_slashes(self):
579 res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
580 self.assertEqual(
581 (b'k=aa%2F%2Fbb&//q//p//=//a//b//\n',
582 'text/html', 200),
583 (res.read(), res.getheader('Content-type'), res.status))
584
Antoine Pitrou47d9b0e2010-12-16 17:11:34 +0000585
Antoine Pitrou47d9b0e2010-12-16 17:11:34 +0000586class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
587 """ Test url parsing """
588 def setUp(self):
589 self.translated = os.getcwd()
590 self.translated = os.path.join(self.translated, 'filename')
591 self.handler = SocketlessRequestHandler()
592
593 def test_query_arguments(self):
594 path = self.handler.translate_path('/filename')
595 self.assertEqual(path, self.translated)
596 path = self.handler.translate_path('/filename?foo=bar')
597 self.assertEqual(path, self.translated)
598 path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
599 self.assertEqual(path, self.translated)
600
601 def test_start_with_double_slash(self):
602 path = self.handler.translate_path('//filename')
603 self.assertEqual(path, self.translated)
604 path = self.handler.translate_path('//filename?foo=bar')
605 self.assertEqual(path, self.translated)
606
607
Georg Brandlf899dfa2008-05-18 09:12:20 +0000608def test_main(verbose=None):
609 try:
610 cwd = os.getcwd()
Senthil Kumaranb643fc62010-09-30 06:40:56 +0000611 test_support.run_unittest(BaseHTTPRequestHandlerTestCase,
Antoine Pitrou47d9b0e2010-12-16 17:11:34 +0000612 SimpleHTTPRequestHandlerTestCase,
Senthil Kumaranb643fc62010-09-30 06:40:56 +0000613 BaseHTTPServerTestCase,
614 SimpleHTTPServerTestCase,
615 CGIHTTPServerTestCase
616 )
Georg Brandlf899dfa2008-05-18 09:12:20 +0000617 finally:
618 os.chdir(cwd)
619
620if __name__ == '__main__':
621 test_main()