1 | n/a | """Unittests for the various HTTPServer modules. |
---|
2 | n/a | |
---|
3 | n/a | Written by Cody A.W. Somerville <cody-somerville@ubuntu.com>, |
---|
4 | n/a | Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest. |
---|
5 | n/a | """ |
---|
6 | n/a | |
---|
7 | n/a | from http.server import BaseHTTPRequestHandler, HTTPServer, \ |
---|
8 | n/a | SimpleHTTPRequestHandler, CGIHTTPRequestHandler |
---|
9 | n/a | from http import server, HTTPStatus |
---|
10 | n/a | |
---|
11 | n/a | import os |
---|
12 | n/a | import sys |
---|
13 | n/a | import re |
---|
14 | n/a | import base64 |
---|
15 | n/a | import ntpath |
---|
16 | n/a | import shutil |
---|
17 | n/a | import urllib.parse |
---|
18 | n/a | import html |
---|
19 | n/a | import http.client |
---|
20 | n/a | import tempfile |
---|
21 | n/a | import time |
---|
22 | n/a | from io import BytesIO |
---|
23 | n/a | |
---|
24 | n/a | import unittest |
---|
25 | n/a | from test import support |
---|
26 | n/a | threading = support.import_module('threading') |
---|
27 | n/a | |
---|
28 | n/a | class NoLogRequestHandler: |
---|
29 | n/a | def log_message(self, *args): |
---|
30 | n/a | # don't write log messages to stderr |
---|
31 | n/a | pass |
---|
32 | n/a | |
---|
33 | n/a | def read(self, n=None): |
---|
34 | n/a | return '' |
---|
35 | n/a | |
---|
36 | n/a | |
---|
37 | n/a | class TestServerThread(threading.Thread): |
---|
38 | n/a | def __init__(self, test_object, request_handler): |
---|
39 | n/a | threading.Thread.__init__(self) |
---|
40 | n/a | self.request_handler = request_handler |
---|
41 | n/a | self.test_object = test_object |
---|
42 | n/a | |
---|
43 | n/a | def run(self): |
---|
44 | n/a | self.server = HTTPServer(('localhost', 0), self.request_handler) |
---|
45 | n/a | self.test_object.HOST, self.test_object.PORT = self.server.socket.getsockname() |
---|
46 | n/a | self.test_object.server_started.set() |
---|
47 | n/a | self.test_object = None |
---|
48 | n/a | try: |
---|
49 | n/a | self.server.serve_forever(0.05) |
---|
50 | n/a | finally: |
---|
51 | n/a | self.server.server_close() |
---|
52 | n/a | |
---|
53 | n/a | def stop(self): |
---|
54 | n/a | self.server.shutdown() |
---|
55 | n/a | |
---|
56 | n/a | |
---|
57 | n/a | class BaseTestCase(unittest.TestCase): |
---|
58 | n/a | def setUp(self): |
---|
59 | n/a | self._threads = support.threading_setup() |
---|
60 | n/a | os.environ = support.EnvironmentVarGuard() |
---|
61 | n/a | self.server_started = threading.Event() |
---|
62 | n/a | self.thread = TestServerThread(self, self.request_handler) |
---|
63 | n/a | self.thread.start() |
---|
64 | n/a | self.server_started.wait() |
---|
65 | n/a | |
---|
66 | n/a | def tearDown(self): |
---|
67 | n/a | self.thread.stop() |
---|
68 | n/a | self.thread = None |
---|
69 | n/a | os.environ.__exit__() |
---|
70 | n/a | support.threading_cleanup(*self._threads) |
---|
71 | n/a | |
---|
72 | n/a | def request(self, uri, method='GET', body=None, headers={}): |
---|
73 | n/a | self.connection = http.client.HTTPConnection(self.HOST, self.PORT) |
---|
74 | n/a | self.connection.request(method, uri, body, headers) |
---|
75 | n/a | return self.connection.getresponse() |
---|
76 | n/a | |
---|
77 | n/a | |
---|
78 | n/a | class BaseHTTPServerTestCase(BaseTestCase): |
---|
79 | n/a | class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler): |
---|
80 | n/a | protocol_version = 'HTTP/1.1' |
---|
81 | n/a | default_request_version = 'HTTP/1.1' |
---|
82 | n/a | |
---|
83 | n/a | def do_TEST(self): |
---|
84 | n/a | self.send_response(HTTPStatus.NO_CONTENT) |
---|
85 | n/a | self.send_header('Content-Type', 'text/html') |
---|
86 | n/a | self.send_header('Connection', 'close') |
---|
87 | n/a | self.end_headers() |
---|
88 | n/a | |
---|
89 | n/a | def do_KEEP(self): |
---|
90 | n/a | self.send_response(HTTPStatus.NO_CONTENT) |
---|
91 | n/a | self.send_header('Content-Type', 'text/html') |
---|
92 | n/a | self.send_header('Connection', 'keep-alive') |
---|
93 | n/a | self.end_headers() |
---|
94 | n/a | |
---|
95 | n/a | def do_KEYERROR(self): |
---|
96 | n/a | self.send_error(999) |
---|
97 | n/a | |
---|
98 | n/a | def do_NOTFOUND(self): |
---|
99 | n/a | self.send_error(HTTPStatus.NOT_FOUND) |
---|
100 | n/a | |
---|
101 | n/a | def do_EXPLAINERROR(self): |
---|
102 | n/a | self.send_error(999, "Short Message", |
---|
103 | n/a | "This is a long \n explanation") |
---|
104 | n/a | |
---|
105 | n/a | def do_CUSTOM(self): |
---|
106 | n/a | self.send_response(999) |
---|
107 | n/a | self.send_header('Content-Type', 'text/html') |
---|
108 | n/a | self.send_header('Connection', 'close') |
---|
109 | n/a | self.end_headers() |
---|
110 | n/a | |
---|
111 | n/a | def do_LATINONEHEADER(self): |
---|
112 | n/a | self.send_response(999) |
---|
113 | n/a | self.send_header('X-Special', 'Dängerous Mind') |
---|
114 | n/a | self.send_header('Connection', 'close') |
---|
115 | n/a | self.end_headers() |
---|
116 | n/a | body = self.headers['x-special-incoming'].encode('utf-8') |
---|
117 | n/a | self.wfile.write(body) |
---|
118 | n/a | |
---|
119 | n/a | def do_SEND_ERROR(self): |
---|
120 | n/a | self.send_error(int(self.path[1:])) |
---|
121 | n/a | |
---|
122 | n/a | def do_HEAD(self): |
---|
123 | n/a | self.send_error(int(self.path[1:])) |
---|
124 | n/a | |
---|
125 | n/a | def setUp(self): |
---|
126 | n/a | BaseTestCase.setUp(self) |
---|
127 | n/a | self.con = http.client.HTTPConnection(self.HOST, self.PORT) |
---|
128 | n/a | self.con.connect() |
---|
129 | n/a | |
---|
130 | n/a | def test_command(self): |
---|
131 | n/a | self.con.request('GET', '/') |
---|
132 | n/a | res = self.con.getresponse() |
---|
133 | n/a | self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) |
---|
134 | n/a | |
---|
135 | n/a | def test_request_line_trimming(self): |
---|
136 | n/a | self.con._http_vsn_str = 'HTTP/1.1\n' |
---|
137 | n/a | self.con.putrequest('XYZBOGUS', '/') |
---|
138 | n/a | self.con.endheaders() |
---|
139 | n/a | res = self.con.getresponse() |
---|
140 | n/a | self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) |
---|
141 | n/a | |
---|
142 | n/a | def test_version_bogus(self): |
---|
143 | n/a | self.con._http_vsn_str = 'FUBAR' |
---|
144 | n/a | self.con.putrequest('GET', '/') |
---|
145 | n/a | self.con.endheaders() |
---|
146 | n/a | res = self.con.getresponse() |
---|
147 | n/a | self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) |
---|
148 | n/a | |
---|
149 | n/a | def test_version_digits(self): |
---|
150 | n/a | self.con._http_vsn_str = 'HTTP/9.9.9' |
---|
151 | n/a | self.con.putrequest('GET', '/') |
---|
152 | n/a | self.con.endheaders() |
---|
153 | n/a | res = self.con.getresponse() |
---|
154 | n/a | self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) |
---|
155 | n/a | |
---|
156 | n/a | def test_version_none_get(self): |
---|
157 | n/a | self.con._http_vsn_str = '' |
---|
158 | n/a | self.con.putrequest('GET', '/') |
---|
159 | n/a | self.con.endheaders() |
---|
160 | n/a | res = self.con.getresponse() |
---|
161 | n/a | self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) |
---|
162 | n/a | |
---|
163 | n/a | def test_version_none(self): |
---|
164 | n/a | # Test that a valid method is rejected when not HTTP/1.x |
---|
165 | n/a | self.con._http_vsn_str = '' |
---|
166 | n/a | self.con.putrequest('CUSTOM', '/') |
---|
167 | n/a | self.con.endheaders() |
---|
168 | n/a | res = self.con.getresponse() |
---|
169 | n/a | self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) |
---|
170 | n/a | |
---|
171 | n/a | def test_version_invalid(self): |
---|
172 | n/a | self.con._http_vsn = 99 |
---|
173 | n/a | self.con._http_vsn_str = 'HTTP/9.9' |
---|
174 | n/a | self.con.putrequest('GET', '/') |
---|
175 | n/a | self.con.endheaders() |
---|
176 | n/a | res = self.con.getresponse() |
---|
177 | n/a | self.assertEqual(res.status, HTTPStatus.HTTP_VERSION_NOT_SUPPORTED) |
---|
178 | n/a | |
---|
179 | n/a | def test_send_blank(self): |
---|
180 | n/a | self.con._http_vsn_str = '' |
---|
181 | n/a | self.con.putrequest('', '') |
---|
182 | n/a | self.con.endheaders() |
---|
183 | n/a | res = self.con.getresponse() |
---|
184 | n/a | self.assertEqual(res.status, HTTPStatus.BAD_REQUEST) |
---|
185 | n/a | |
---|
186 | n/a | def test_header_close(self): |
---|
187 | n/a | self.con.putrequest('GET', '/') |
---|
188 | n/a | self.con.putheader('Connection', 'close') |
---|
189 | n/a | self.con.endheaders() |
---|
190 | n/a | res = self.con.getresponse() |
---|
191 | n/a | self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) |
---|
192 | n/a | |
---|
193 | n/a | def test_header_keep_alive(self): |
---|
194 | n/a | self.con._http_vsn_str = 'HTTP/1.1' |
---|
195 | n/a | self.con.putrequest('GET', '/') |
---|
196 | n/a | self.con.putheader('Connection', 'keep-alive') |
---|
197 | n/a | self.con.endheaders() |
---|
198 | n/a | res = self.con.getresponse() |
---|
199 | n/a | self.assertEqual(res.status, HTTPStatus.NOT_IMPLEMENTED) |
---|
200 | n/a | |
---|
201 | n/a | def test_handler(self): |
---|
202 | n/a | self.con.request('TEST', '/') |
---|
203 | n/a | res = self.con.getresponse() |
---|
204 | n/a | self.assertEqual(res.status, HTTPStatus.NO_CONTENT) |
---|
205 | n/a | |
---|
206 | n/a | def test_return_header_keep_alive(self): |
---|
207 | n/a | self.con.request('KEEP', '/') |
---|
208 | n/a | res = self.con.getresponse() |
---|
209 | n/a | self.assertEqual(res.getheader('Connection'), 'keep-alive') |
---|
210 | n/a | self.con.request('TEST', '/') |
---|
211 | n/a | self.addCleanup(self.con.close) |
---|
212 | n/a | |
---|
213 | n/a | def test_internal_key_error(self): |
---|
214 | n/a | self.con.request('KEYERROR', '/') |
---|
215 | n/a | res = self.con.getresponse() |
---|
216 | n/a | self.assertEqual(res.status, 999) |
---|
217 | n/a | |
---|
218 | n/a | def test_return_custom_status(self): |
---|
219 | n/a | self.con.request('CUSTOM', '/') |
---|
220 | n/a | res = self.con.getresponse() |
---|
221 | n/a | self.assertEqual(res.status, 999) |
---|
222 | n/a | |
---|
223 | n/a | def test_return_explain_error(self): |
---|
224 | n/a | self.con.request('EXPLAINERROR', '/') |
---|
225 | n/a | res = self.con.getresponse() |
---|
226 | n/a | self.assertEqual(res.status, 999) |
---|
227 | n/a | self.assertTrue(int(res.getheader('Content-Length'))) |
---|
228 | n/a | |
---|
229 | n/a | def test_latin1_header(self): |
---|
230 | n/a | self.con.request('LATINONEHEADER', '/', headers={ |
---|
231 | n/a | 'X-Special-Incoming': 'Ãrger mit Unicode' |
---|
232 | n/a | }) |
---|
233 | n/a | res = self.con.getresponse() |
---|
234 | n/a | self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind') |
---|
235 | n/a | self.assertEqual(res.read(), 'Ãrger mit Unicode'.encode('utf-8')) |
---|
236 | n/a | |
---|
237 | n/a | def test_error_content_length(self): |
---|
238 | n/a | # Issue #16088: standard error responses should have a content-length |
---|
239 | n/a | self.con.request('NOTFOUND', '/') |
---|
240 | n/a | res = self.con.getresponse() |
---|
241 | n/a | self.assertEqual(res.status, HTTPStatus.NOT_FOUND) |
---|
242 | n/a | |
---|
243 | n/a | data = res.read() |
---|
244 | n/a | self.assertEqual(int(res.getheader('Content-Length')), len(data)) |
---|
245 | n/a | |
---|
246 | n/a | def test_send_error(self): |
---|
247 | n/a | allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED, |
---|
248 | n/a | HTTPStatus.RESET_CONTENT) |
---|
249 | n/a | for code in (HTTPStatus.NO_CONTENT, HTTPStatus.NOT_MODIFIED, |
---|
250 | n/a | HTTPStatus.PROCESSING, HTTPStatus.RESET_CONTENT, |
---|
251 | n/a | HTTPStatus.SWITCHING_PROTOCOLS): |
---|
252 | n/a | self.con.request('SEND_ERROR', '/{}'.format(code)) |
---|
253 | n/a | res = self.con.getresponse() |
---|
254 | n/a | self.assertEqual(code, res.status) |
---|
255 | n/a | self.assertEqual(None, res.getheader('Content-Length')) |
---|
256 | n/a | self.assertEqual(None, res.getheader('Content-Type')) |
---|
257 | n/a | if code not in allow_transfer_encoding_codes: |
---|
258 | n/a | self.assertEqual(None, res.getheader('Transfer-Encoding')) |
---|
259 | n/a | |
---|
260 | n/a | data = res.read() |
---|
261 | n/a | self.assertEqual(b'', data) |
---|
262 | n/a | |
---|
263 | n/a | def test_head_via_send_error(self): |
---|
264 | n/a | allow_transfer_encoding_codes = (HTTPStatus.NOT_MODIFIED, |
---|
265 | n/a | HTTPStatus.RESET_CONTENT) |
---|
266 | n/a | for code in (HTTPStatus.OK, HTTPStatus.NO_CONTENT, |
---|
267 | n/a | HTTPStatus.NOT_MODIFIED, HTTPStatus.RESET_CONTENT, |
---|
268 | n/a | HTTPStatus.SWITCHING_PROTOCOLS): |
---|
269 | n/a | self.con.request('HEAD', '/{}'.format(code)) |
---|
270 | n/a | res = self.con.getresponse() |
---|
271 | n/a | self.assertEqual(code, res.status) |
---|
272 | n/a | if code == HTTPStatus.OK: |
---|
273 | n/a | self.assertTrue(int(res.getheader('Content-Length')) > 0) |
---|
274 | n/a | self.assertIn('text/html', res.getheader('Content-Type')) |
---|
275 | n/a | else: |
---|
276 | n/a | self.assertEqual(None, res.getheader('Content-Length')) |
---|
277 | n/a | self.assertEqual(None, res.getheader('Content-Type')) |
---|
278 | n/a | if code not in allow_transfer_encoding_codes: |
---|
279 | n/a | self.assertEqual(None, res.getheader('Transfer-Encoding')) |
---|
280 | n/a | |
---|
281 | n/a | data = res.read() |
---|
282 | n/a | self.assertEqual(b'', data) |
---|
283 | n/a | |
---|
284 | n/a | |
---|
285 | n/a | class RequestHandlerLoggingTestCase(BaseTestCase): |
---|
286 | n/a | class request_handler(BaseHTTPRequestHandler): |
---|
287 | n/a | protocol_version = 'HTTP/1.1' |
---|
288 | n/a | default_request_version = 'HTTP/1.1' |
---|
289 | n/a | |
---|
290 | n/a | def do_GET(self): |
---|
291 | n/a | self.send_response(HTTPStatus.OK) |
---|
292 | n/a | self.end_headers() |
---|
293 | n/a | |
---|
294 | n/a | def do_ERROR(self): |
---|
295 | n/a | self.send_error(HTTPStatus.NOT_FOUND, 'File not found') |
---|
296 | n/a | |
---|
297 | n/a | def test_get(self): |
---|
298 | n/a | self.con = http.client.HTTPConnection(self.HOST, self.PORT) |
---|
299 | n/a | self.con.connect() |
---|
300 | n/a | |
---|
301 | n/a | with support.captured_stderr() as err: |
---|
302 | n/a | self.con.request('GET', '/') |
---|
303 | n/a | self.con.getresponse() |
---|
304 | n/a | |
---|
305 | n/a | self.assertTrue( |
---|
306 | n/a | err.getvalue().endswith('"GET / HTTP/1.1" 200 -\n')) |
---|
307 | n/a | |
---|
308 | n/a | def test_err(self): |
---|
309 | n/a | self.con = http.client.HTTPConnection(self.HOST, self.PORT) |
---|
310 | n/a | self.con.connect() |
---|
311 | n/a | |
---|
312 | n/a | with support.captured_stderr() as err: |
---|
313 | n/a | self.con.request('ERROR', '/') |
---|
314 | n/a | self.con.getresponse() |
---|
315 | n/a | |
---|
316 | n/a | lines = err.getvalue().split('\n') |
---|
317 | n/a | self.assertTrue(lines[0].endswith('code 404, message File not found')) |
---|
318 | n/a | self.assertTrue(lines[1].endswith('"ERROR / HTTP/1.1" 404 -')) |
---|
319 | n/a | |
---|
320 | n/a | |
---|
321 | n/a | class SimpleHTTPServerTestCase(BaseTestCase): |
---|
322 | n/a | class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler): |
---|
323 | n/a | pass |
---|
324 | n/a | |
---|
325 | n/a | def setUp(self): |
---|
326 | n/a | BaseTestCase.setUp(self) |
---|
327 | n/a | self.cwd = os.getcwd() |
---|
328 | n/a | basetempdir = tempfile.gettempdir() |
---|
329 | n/a | os.chdir(basetempdir) |
---|
330 | n/a | self.data = b'We are the knights who say Ni!' |
---|
331 | n/a | self.tempdir = tempfile.mkdtemp(dir=basetempdir) |
---|
332 | n/a | self.tempdir_name = os.path.basename(self.tempdir) |
---|
333 | n/a | self.base_url = '/' + self.tempdir_name |
---|
334 | n/a | with open(os.path.join(self.tempdir, 'test'), 'wb') as temp: |
---|
335 | n/a | temp.write(self.data) |
---|
336 | n/a | |
---|
337 | n/a | def tearDown(self): |
---|
338 | n/a | try: |
---|
339 | n/a | os.chdir(self.cwd) |
---|
340 | n/a | try: |
---|
341 | n/a | shutil.rmtree(self.tempdir) |
---|
342 | n/a | except: |
---|
343 | n/a | pass |
---|
344 | n/a | finally: |
---|
345 | n/a | BaseTestCase.tearDown(self) |
---|
346 | n/a | |
---|
347 | n/a | def check_status_and_reason(self, response, status, data=None): |
---|
348 | n/a | def close_conn(): |
---|
349 | n/a | """Don't close reader yet so we can check if there was leftover |
---|
350 | n/a | buffered input""" |
---|
351 | n/a | nonlocal reader |
---|
352 | n/a | reader = response.fp |
---|
353 | n/a | response.fp = None |
---|
354 | n/a | reader = None |
---|
355 | n/a | response._close_conn = close_conn |
---|
356 | n/a | |
---|
357 | n/a | body = response.read() |
---|
358 | n/a | self.assertTrue(response) |
---|
359 | n/a | self.assertEqual(response.status, status) |
---|
360 | n/a | self.assertIsNotNone(response.reason) |
---|
361 | n/a | if data: |
---|
362 | n/a | self.assertEqual(data, body) |
---|
363 | n/a | # Ensure the server has not set up a persistent connection, and has |
---|
364 | n/a | # not sent any extra data |
---|
365 | n/a | self.assertEqual(response.version, 10) |
---|
366 | n/a | self.assertEqual(response.msg.get("Connection", "close"), "close") |
---|
367 | n/a | self.assertEqual(reader.read(30), b'', 'Connection should be closed') |
---|
368 | n/a | |
---|
369 | n/a | reader.close() |
---|
370 | n/a | return body |
---|
371 | n/a | |
---|
372 | n/a | @support.requires_mac_ver(10, 5) |
---|
373 | n/a | @unittest.skipIf(sys.platform == 'win32', |
---|
374 | n/a | 'undecodable name cannot be decoded on win32') |
---|
375 | n/a | @unittest.skipUnless(support.TESTFN_UNDECODABLE, |
---|
376 | n/a | 'need support.TESTFN_UNDECODABLE') |
---|
377 | n/a | def test_undecodable_filename(self): |
---|
378 | n/a | enc = sys.getfilesystemencoding() |
---|
379 | n/a | filename = os.fsdecode(support.TESTFN_UNDECODABLE) + '.txt' |
---|
380 | n/a | with open(os.path.join(self.tempdir, filename), 'wb') as f: |
---|
381 | n/a | f.write(support.TESTFN_UNDECODABLE) |
---|
382 | n/a | response = self.request(self.base_url + '/') |
---|
383 | n/a | if sys.platform == 'darwin': |
---|
384 | n/a | # On Mac OS the HFS+ filesystem replaces bytes that aren't valid |
---|
385 | n/a | # UTF-8 into a percent-encoded value. |
---|
386 | n/a | for name in os.listdir(self.tempdir): |
---|
387 | n/a | if name != 'test': # Ignore a filename created in setUp(). |
---|
388 | n/a | filename = name |
---|
389 | n/a | break |
---|
390 | n/a | body = self.check_status_and_reason(response, HTTPStatus.OK) |
---|
391 | n/a | quotedname = urllib.parse.quote(filename, errors='surrogatepass') |
---|
392 | n/a | self.assertIn(('href="%s"' % quotedname) |
---|
393 | n/a | .encode(enc, 'surrogateescape'), body) |
---|
394 | n/a | self.assertIn(('>%s<' % html.escape(filename, quote=False)) |
---|
395 | n/a | .encode(enc, 'surrogateescape'), body) |
---|
396 | n/a | response = self.request(self.base_url + '/' + quotedname) |
---|
397 | n/a | self.check_status_and_reason(response, HTTPStatus.OK, |
---|
398 | n/a | data=support.TESTFN_UNDECODABLE) |
---|
399 | n/a | |
---|
400 | n/a | def test_get(self): |
---|
401 | n/a | #constructs the path relative to the root directory of the HTTPServer |
---|
402 | n/a | response = self.request(self.base_url + '/test') |
---|
403 | n/a | self.check_status_and_reason(response, HTTPStatus.OK, data=self.data) |
---|
404 | n/a | # check for trailing "/" which should return 404. See Issue17324 |
---|
405 | n/a | response = self.request(self.base_url + '/test/') |
---|
406 | n/a | self.check_status_and_reason(response, HTTPStatus.NOT_FOUND) |
---|
407 | n/a | response = self.request(self.base_url + '/') |
---|
408 | n/a | self.check_status_and_reason(response, HTTPStatus.OK) |
---|
409 | n/a | response = self.request(self.base_url) |
---|
410 | n/a | self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY) |
---|
411 | n/a | response = self.request(self.base_url + '/?hi=2') |
---|
412 | n/a | self.check_status_and_reason(response, HTTPStatus.OK) |
---|
413 | n/a | response = self.request(self.base_url + '?hi=1') |
---|
414 | n/a | self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY) |
---|
415 | n/a | self.assertEqual(response.getheader("Location"), |
---|
416 | n/a | self.base_url + "/?hi=1") |
---|
417 | n/a | response = self.request('/ThisDoesNotExist') |
---|
418 | n/a | self.check_status_and_reason(response, HTTPStatus.NOT_FOUND) |
---|
419 | n/a | response = self.request('/' + 'ThisDoesNotExist' + '/') |
---|
420 | n/a | self.check_status_and_reason(response, HTTPStatus.NOT_FOUND) |
---|
421 | n/a | |
---|
422 | n/a | data = b"Dummy index file\r\n" |
---|
423 | n/a | with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f: |
---|
424 | n/a | f.write(data) |
---|
425 | n/a | response = self.request(self.base_url + '/') |
---|
426 | n/a | self.check_status_and_reason(response, HTTPStatus.OK, data) |
---|
427 | n/a | |
---|
428 | n/a | # chmod() doesn't work as expected on Windows, and filesystem |
---|
429 | n/a | # permissions are ignored by root on Unix. |
---|
430 | n/a | if os.name == 'posix' and os.geteuid() != 0: |
---|
431 | n/a | os.chmod(self.tempdir, 0) |
---|
432 | n/a | try: |
---|
433 | n/a | response = self.request(self.base_url + '/') |
---|
434 | n/a | self.check_status_and_reason(response, HTTPStatus.NOT_FOUND) |
---|
435 | n/a | finally: |
---|
436 | n/a | os.chmod(self.tempdir, 0o755) |
---|
437 | n/a | |
---|
438 | n/a | def test_head(self): |
---|
439 | n/a | response = self.request( |
---|
440 | n/a | self.base_url + '/test', method='HEAD') |
---|
441 | n/a | self.check_status_and_reason(response, HTTPStatus.OK) |
---|
442 | n/a | self.assertEqual(response.getheader('content-length'), |
---|
443 | n/a | str(len(self.data))) |
---|
444 | n/a | self.assertEqual(response.getheader('content-type'), |
---|
445 | n/a | 'application/octet-stream') |
---|
446 | n/a | |
---|
447 | n/a | def test_invalid_requests(self): |
---|
448 | n/a | response = self.request('/', method='FOO') |
---|
449 | n/a | self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED) |
---|
450 | n/a | # requests must be case sensitive,so this should fail too |
---|
451 | n/a | response = self.request('/', method='custom') |
---|
452 | n/a | self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED) |
---|
453 | n/a | response = self.request('/', method='GETs') |
---|
454 | n/a | self.check_status_and_reason(response, HTTPStatus.NOT_IMPLEMENTED) |
---|
455 | n/a | |
---|
456 | n/a | def test_path_without_leading_slash(self): |
---|
457 | n/a | response = self.request(self.tempdir_name + '/test') |
---|
458 | n/a | self.check_status_and_reason(response, HTTPStatus.OK, data=self.data) |
---|
459 | n/a | response = self.request(self.tempdir_name + '/test/') |
---|
460 | n/a | self.check_status_and_reason(response, HTTPStatus.NOT_FOUND) |
---|
461 | n/a | response = self.request(self.tempdir_name + '/') |
---|
462 | n/a | self.check_status_and_reason(response, HTTPStatus.OK) |
---|
463 | n/a | response = self.request(self.tempdir_name) |
---|
464 | n/a | self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY) |
---|
465 | n/a | response = self.request(self.tempdir_name + '/?hi=2') |
---|
466 | n/a | self.check_status_and_reason(response, HTTPStatus.OK) |
---|
467 | n/a | response = self.request(self.tempdir_name + '?hi=1') |
---|
468 | n/a | self.check_status_and_reason(response, HTTPStatus.MOVED_PERMANENTLY) |
---|
469 | n/a | self.assertEqual(response.getheader("Location"), |
---|
470 | n/a | self.tempdir_name + "/?hi=1") |
---|
471 | n/a | |
---|
472 | n/a | def test_html_escape_filename(self): |
---|
473 | n/a | filename = '<test&>.txt' |
---|
474 | n/a | fullpath = os.path.join(self.tempdir, filename) |
---|
475 | n/a | |
---|
476 | n/a | try: |
---|
477 | n/a | open(fullpath, 'w').close() |
---|
478 | n/a | except OSError: |
---|
479 | n/a | raise unittest.SkipTest('Can not create file %s on current file ' |
---|
480 | n/a | 'system' % filename) |
---|
481 | n/a | |
---|
482 | n/a | try: |
---|
483 | n/a | response = self.request(self.base_url + '/') |
---|
484 | n/a | body = self.check_status_and_reason(response, HTTPStatus.OK) |
---|
485 | n/a | enc = response.headers.get_content_charset() |
---|
486 | n/a | finally: |
---|
487 | n/a | os.unlink(fullpath) # avoid affecting test_undecodable_filename |
---|
488 | n/a | |
---|
489 | n/a | self.assertIsNotNone(enc) |
---|
490 | n/a | html_text = '>%s<' % html.escape(filename, quote=False) |
---|
491 | n/a | self.assertIn(html_text.encode(enc), body) |
---|
492 | n/a | |
---|
493 | n/a | |
---|
494 | n/a | cgi_file1 = """\ |
---|
495 | n/a | #!%s |
---|
496 | n/a | |
---|
497 | n/a | print("Content-type: text/html") |
---|
498 | n/a | print() |
---|
499 | n/a | print("Hello World") |
---|
500 | n/a | """ |
---|
501 | n/a | |
---|
502 | n/a | cgi_file2 = """\ |
---|
503 | n/a | #!%s |
---|
504 | n/a | import cgi |
---|
505 | n/a | |
---|
506 | n/a | print("Content-type: text/html") |
---|
507 | n/a | print() |
---|
508 | n/a | |
---|
509 | n/a | form = cgi.FieldStorage() |
---|
510 | n/a | print("%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"), |
---|
511 | n/a | form.getfirst("bacon"))) |
---|
512 | n/a | """ |
---|
513 | n/a | |
---|
514 | n/a | cgi_file4 = """\ |
---|
515 | n/a | #!%s |
---|
516 | n/a | import os |
---|
517 | n/a | |
---|
518 | n/a | print("Content-type: text/html") |
---|
519 | n/a | print() |
---|
520 | n/a | |
---|
521 | n/a | print(os.environ["%s"]) |
---|
522 | n/a | """ |
---|
523 | n/a | |
---|
524 | n/a | |
---|
525 | n/a | @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0, |
---|
526 | n/a | "This test can't be run reliably as root (issue #13308).") |
---|
527 | n/a | class CGIHTTPServerTestCase(BaseTestCase): |
---|
528 | n/a | class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler): |
---|
529 | n/a | pass |
---|
530 | n/a | |
---|
531 | n/a | linesep = os.linesep.encode('ascii') |
---|
532 | n/a | |
---|
533 | n/a | def setUp(self): |
---|
534 | n/a | BaseTestCase.setUp(self) |
---|
535 | n/a | self.cwd = os.getcwd() |
---|
536 | n/a | self.parent_dir = tempfile.mkdtemp() |
---|
537 | n/a | self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin') |
---|
538 | n/a | self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir') |
---|
539 | n/a | os.mkdir(self.cgi_dir) |
---|
540 | n/a | os.mkdir(self.cgi_child_dir) |
---|
541 | n/a | self.nocgi_path = None |
---|
542 | n/a | self.file1_path = None |
---|
543 | n/a | self.file2_path = None |
---|
544 | n/a | self.file3_path = None |
---|
545 | n/a | self.file4_path = None |
---|
546 | n/a | |
---|
547 | n/a | # The shebang line should be pure ASCII: use symlink if possible. |
---|
548 | n/a | # See issue #7668. |
---|
549 | n/a | if support.can_symlink(): |
---|
550 | n/a | self.pythonexe = os.path.join(self.parent_dir, 'python') |
---|
551 | n/a | os.symlink(sys.executable, self.pythonexe) |
---|
552 | n/a | else: |
---|
553 | n/a | self.pythonexe = sys.executable |
---|
554 | n/a | |
---|
555 | n/a | try: |
---|
556 | n/a | # The python executable path is written as the first line of the |
---|
557 | n/a | # CGI Python script. The encoding cookie cannot be used, and so the |
---|
558 | n/a | # path should be encodable to the default script encoding (utf-8) |
---|
559 | n/a | self.pythonexe.encode('utf-8') |
---|
560 | n/a | except UnicodeEncodeError: |
---|
561 | n/a | self.tearDown() |
---|
562 | n/a | self.skipTest("Python executable path is not encodable to utf-8") |
---|
563 | n/a | |
---|
564 | n/a | self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py') |
---|
565 | n/a | with open(self.nocgi_path, 'w') as fp: |
---|
566 | n/a | fp.write(cgi_file1 % self.pythonexe) |
---|
567 | n/a | os.chmod(self.nocgi_path, 0o777) |
---|
568 | n/a | |
---|
569 | n/a | self.file1_path = os.path.join(self.cgi_dir, 'file1.py') |
---|
570 | n/a | with open(self.file1_path, 'w', encoding='utf-8') as file1: |
---|
571 | n/a | file1.write(cgi_file1 % self.pythonexe) |
---|
572 | n/a | os.chmod(self.file1_path, 0o777) |
---|
573 | n/a | |
---|
574 | n/a | self.file2_path = os.path.join(self.cgi_dir, 'file2.py') |
---|
575 | n/a | with open(self.file2_path, 'w', encoding='utf-8') as file2: |
---|
576 | n/a | file2.write(cgi_file2 % self.pythonexe) |
---|
577 | n/a | os.chmod(self.file2_path, 0o777) |
---|
578 | n/a | |
---|
579 | n/a | self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py') |
---|
580 | n/a | with open(self.file3_path, 'w', encoding='utf-8') as file3: |
---|
581 | n/a | file3.write(cgi_file1 % self.pythonexe) |
---|
582 | n/a | os.chmod(self.file3_path, 0o777) |
---|
583 | n/a | |
---|
584 | n/a | self.file4_path = os.path.join(self.cgi_dir, 'file4.py') |
---|
585 | n/a | with open(self.file4_path, 'w', encoding='utf-8') as file4: |
---|
586 | n/a | file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING')) |
---|
587 | n/a | os.chmod(self.file4_path, 0o777) |
---|
588 | n/a | |
---|
589 | n/a | os.chdir(self.parent_dir) |
---|
590 | n/a | |
---|
591 | n/a | def tearDown(self): |
---|
592 | n/a | try: |
---|
593 | n/a | os.chdir(self.cwd) |
---|
594 | n/a | if self.pythonexe != sys.executable: |
---|
595 | n/a | os.remove(self.pythonexe) |
---|
596 | n/a | if self.nocgi_path: |
---|
597 | n/a | os.remove(self.nocgi_path) |
---|
598 | n/a | if self.file1_path: |
---|
599 | n/a | os.remove(self.file1_path) |
---|
600 | n/a | if self.file2_path: |
---|
601 | n/a | os.remove(self.file2_path) |
---|
602 | n/a | if self.file3_path: |
---|
603 | n/a | os.remove(self.file3_path) |
---|
604 | n/a | if self.file4_path: |
---|
605 | n/a | os.remove(self.file4_path) |
---|
606 | n/a | os.rmdir(self.cgi_child_dir) |
---|
607 | n/a | os.rmdir(self.cgi_dir) |
---|
608 | n/a | os.rmdir(self.parent_dir) |
---|
609 | n/a | finally: |
---|
610 | n/a | BaseTestCase.tearDown(self) |
---|
611 | n/a | |
---|
612 | n/a | def test_url_collapse_path(self): |
---|
613 | n/a | # verify tail is the last portion and head is the rest on proper urls |
---|
614 | n/a | test_vectors = { |
---|
615 | n/a | '': '//', |
---|
616 | n/a | '..': IndexError, |
---|
617 | n/a | '/.//..': IndexError, |
---|
618 | n/a | '/': '//', |
---|
619 | n/a | '//': '//', |
---|
620 | n/a | '/\\': '//\\', |
---|
621 | n/a | '/.//': '//', |
---|
622 | n/a | 'cgi-bin/file1.py': '/cgi-bin/file1.py', |
---|
623 | n/a | '/cgi-bin/file1.py': '/cgi-bin/file1.py', |
---|
624 | n/a | 'a': '//a', |
---|
625 | n/a | '/a': '//a', |
---|
626 | n/a | '//a': '//a', |
---|
627 | n/a | './a': '//a', |
---|
628 | n/a | './C:/': '/C:/', |
---|
629 | n/a | '/a/b': '/a/b', |
---|
630 | n/a | '/a/b/': '/a/b/', |
---|
631 | n/a | '/a/b/.': '/a/b/', |
---|
632 | n/a | '/a/b/c/..': '/a/b/', |
---|
633 | n/a | '/a/b/c/../d': '/a/b/d', |
---|
634 | n/a | '/a/b/c/../d/e/../f': '/a/b/d/f', |
---|
635 | n/a | '/a/b/c/../d/e/../../f': '/a/b/f', |
---|
636 | n/a | '/a/b/c/../d/e/.././././..//f': '/a/b/f', |
---|
637 | n/a | '../a/b/c/../d/e/.././././..//f': IndexError, |
---|
638 | n/a | '/a/b/c/../d/e/../../../f': '/a/f', |
---|
639 | n/a | '/a/b/c/../d/e/../../../../f': '//f', |
---|
640 | n/a | '/a/b/c/../d/e/../../../../../f': IndexError, |
---|
641 | n/a | '/a/b/c/../d/e/../../../../f/..': '//', |
---|
642 | n/a | '/a/b/c/../d/e/../../../../f/../.': '//', |
---|
643 | n/a | } |
---|
644 | n/a | for path, expected in test_vectors.items(): |
---|
645 | n/a | if isinstance(expected, type) and issubclass(expected, Exception): |
---|
646 | n/a | self.assertRaises(expected, |
---|
647 | n/a | server._url_collapse_path, path) |
---|
648 | n/a | else: |
---|
649 | n/a | actual = server._url_collapse_path(path) |
---|
650 | n/a | self.assertEqual(expected, actual, |
---|
651 | n/a | msg='path = %r\nGot: %r\nWanted: %r' % |
---|
652 | n/a | (path, actual, expected)) |
---|
653 | n/a | |
---|
654 | n/a | def test_headers_and_content(self): |
---|
655 | n/a | res = self.request('/cgi-bin/file1.py') |
---|
656 | n/a | self.assertEqual( |
---|
657 | n/a | (res.read(), res.getheader('Content-type'), res.status), |
---|
658 | n/a | (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK)) |
---|
659 | n/a | |
---|
660 | n/a | def test_issue19435(self): |
---|
661 | n/a | res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh') |
---|
662 | n/a | self.assertEqual(res.status, HTTPStatus.NOT_FOUND) |
---|
663 | n/a | |
---|
664 | n/a | def test_post(self): |
---|
665 | n/a | params = urllib.parse.urlencode( |
---|
666 | n/a | {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456}) |
---|
667 | n/a | headers = {'Content-type' : 'application/x-www-form-urlencoded'} |
---|
668 | n/a | res = self.request('/cgi-bin/file2.py', 'POST', params, headers) |
---|
669 | n/a | |
---|
670 | n/a | self.assertEqual(res.read(), b'1, python, 123456' + self.linesep) |
---|
671 | n/a | |
---|
672 | n/a | def test_invaliduri(self): |
---|
673 | n/a | res = self.request('/cgi-bin/invalid') |
---|
674 | n/a | res.read() |
---|
675 | n/a | self.assertEqual(res.status, HTTPStatus.NOT_FOUND) |
---|
676 | n/a | |
---|
677 | n/a | def test_authorization(self): |
---|
678 | n/a | headers = {b'Authorization' : b'Basic ' + |
---|
679 | n/a | base64.b64encode(b'username:pass')} |
---|
680 | n/a | res = self.request('/cgi-bin/file1.py', 'GET', headers=headers) |
---|
681 | n/a | self.assertEqual( |
---|
682 | n/a | (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), |
---|
683 | n/a | (res.read(), res.getheader('Content-type'), res.status)) |
---|
684 | n/a | |
---|
685 | n/a | def test_no_leading_slash(self): |
---|
686 | n/a | # http://bugs.python.org/issue2254 |
---|
687 | n/a | res = self.request('cgi-bin/file1.py') |
---|
688 | n/a | self.assertEqual( |
---|
689 | n/a | (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), |
---|
690 | n/a | (res.read(), res.getheader('Content-type'), res.status)) |
---|
691 | n/a | |
---|
692 | n/a | def test_os_environ_is_not_altered(self): |
---|
693 | n/a | signature = "Test CGI Server" |
---|
694 | n/a | os.environ['SERVER_SOFTWARE'] = signature |
---|
695 | n/a | res = self.request('/cgi-bin/file1.py') |
---|
696 | n/a | self.assertEqual( |
---|
697 | n/a | (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), |
---|
698 | n/a | (res.read(), res.getheader('Content-type'), res.status)) |
---|
699 | n/a | self.assertEqual(os.environ['SERVER_SOFTWARE'], signature) |
---|
700 | n/a | |
---|
701 | n/a | def test_urlquote_decoding_in_cgi_check(self): |
---|
702 | n/a | res = self.request('/cgi-bin%2ffile1.py') |
---|
703 | n/a | self.assertEqual( |
---|
704 | n/a | (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), |
---|
705 | n/a | (res.read(), res.getheader('Content-type'), res.status)) |
---|
706 | n/a | |
---|
707 | n/a | def test_nested_cgi_path_issue21323(self): |
---|
708 | n/a | res = self.request('/cgi-bin/child-dir/file3.py') |
---|
709 | n/a | self.assertEqual( |
---|
710 | n/a | (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), |
---|
711 | n/a | (res.read(), res.getheader('Content-type'), res.status)) |
---|
712 | n/a | |
---|
713 | n/a | def test_query_with_multiple_question_mark(self): |
---|
714 | n/a | res = self.request('/cgi-bin/file4.py?a=b?c=d') |
---|
715 | n/a | self.assertEqual( |
---|
716 | n/a | (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK), |
---|
717 | n/a | (res.read(), res.getheader('Content-type'), res.status)) |
---|
718 | n/a | |
---|
719 | n/a | def test_query_with_continuous_slashes(self): |
---|
720 | n/a | res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//') |
---|
721 | n/a | self.assertEqual( |
---|
722 | n/a | (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep, |
---|
723 | n/a | 'text/html', HTTPStatus.OK), |
---|
724 | n/a | (res.read(), res.getheader('Content-type'), res.status)) |
---|
725 | n/a | |
---|
726 | n/a | |
---|
727 | n/a | class SocketlessRequestHandler(SimpleHTTPRequestHandler): |
---|
728 | n/a | def __init__(self): |
---|
729 | n/a | self.get_called = False |
---|
730 | n/a | self.protocol_version = "HTTP/1.1" |
---|
731 | n/a | |
---|
732 | n/a | def do_GET(self): |
---|
733 | n/a | self.get_called = True |
---|
734 | n/a | self.send_response(HTTPStatus.OK) |
---|
735 | n/a | self.send_header('Content-Type', 'text/html') |
---|
736 | n/a | self.end_headers() |
---|
737 | n/a | self.wfile.write(b'<html><body>Data</body></html>\r\n') |
---|
738 | n/a | |
---|
739 | n/a | def log_message(self, format, *args): |
---|
740 | n/a | pass |
---|
741 | n/a | |
---|
742 | n/a | class RejectingSocketlessRequestHandler(SocketlessRequestHandler): |
---|
743 | n/a | def handle_expect_100(self): |
---|
744 | n/a | self.send_error(HTTPStatus.EXPECTATION_FAILED) |
---|
745 | n/a | return False |
---|
746 | n/a | |
---|
747 | n/a | |
---|
748 | n/a | class AuditableBytesIO: |
---|
749 | n/a | |
---|
750 | n/a | def __init__(self): |
---|
751 | n/a | self.datas = [] |
---|
752 | n/a | |
---|
753 | n/a | def write(self, data): |
---|
754 | n/a | self.datas.append(data) |
---|
755 | n/a | |
---|
756 | n/a | def getData(self): |
---|
757 | n/a | return b''.join(self.datas) |
---|
758 | n/a | |
---|
759 | n/a | @property |
---|
760 | n/a | def numWrites(self): |
---|
761 | n/a | return len(self.datas) |
---|
762 | n/a | |
---|
763 | n/a | |
---|
764 | n/a | class BaseHTTPRequestHandlerTestCase(unittest.TestCase): |
---|
765 | n/a | """Test the functionality of the BaseHTTPServer. |
---|
766 | n/a | |
---|
767 | n/a | Test the support for the Expect 100-continue header. |
---|
768 | n/a | """ |
---|
769 | n/a | |
---|
770 | n/a | HTTPResponseMatch = re.compile(b'HTTP/1.[0-9]+ 200 OK') |
---|
771 | n/a | |
---|
772 | n/a | def setUp (self): |
---|
773 | n/a | self.handler = SocketlessRequestHandler() |
---|
774 | n/a | |
---|
775 | n/a | def send_typical_request(self, message): |
---|
776 | n/a | input = BytesIO(message) |
---|
777 | n/a | output = BytesIO() |
---|
778 | n/a | self.handler.rfile = input |
---|
779 | n/a | self.handler.wfile = output |
---|
780 | n/a | self.handler.handle_one_request() |
---|
781 | n/a | output.seek(0) |
---|
782 | n/a | return output.readlines() |
---|
783 | n/a | |
---|
784 | n/a | def verify_get_called(self): |
---|
785 | n/a | self.assertTrue(self.handler.get_called) |
---|
786 | n/a | |
---|
787 | n/a | def verify_expected_headers(self, headers): |
---|
788 | n/a | for fieldName in b'Server: ', b'Date: ', b'Content-Type: ': |
---|
789 | n/a | self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1) |
---|
790 | n/a | |
---|
791 | n/a | def verify_http_server_response(self, response): |
---|
792 | n/a | match = self.HTTPResponseMatch.search(response) |
---|
793 | n/a | self.assertIsNotNone(match) |
---|
794 | n/a | |
---|
795 | n/a | def test_http_1_1(self): |
---|
796 | n/a | result = self.send_typical_request(b'GET / HTTP/1.1\r\n\r\n') |
---|
797 | n/a | self.verify_http_server_response(result[0]) |
---|
798 | n/a | self.verify_expected_headers(result[1:-1]) |
---|
799 | n/a | self.verify_get_called() |
---|
800 | n/a | self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n') |
---|
801 | n/a | self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1') |
---|
802 | n/a | self.assertEqual(self.handler.command, 'GET') |
---|
803 | n/a | self.assertEqual(self.handler.path, '/') |
---|
804 | n/a | self.assertEqual(self.handler.request_version, 'HTTP/1.1') |
---|
805 | n/a | self.assertSequenceEqual(self.handler.headers.items(), ()) |
---|
806 | n/a | |
---|
807 | n/a | def test_http_1_0(self): |
---|
808 | n/a | result = self.send_typical_request(b'GET / HTTP/1.0\r\n\r\n') |
---|
809 | n/a | self.verify_http_server_response(result[0]) |
---|
810 | n/a | self.verify_expected_headers(result[1:-1]) |
---|
811 | n/a | self.verify_get_called() |
---|
812 | n/a | self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n') |
---|
813 | n/a | self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0') |
---|
814 | n/a | self.assertEqual(self.handler.command, 'GET') |
---|
815 | n/a | self.assertEqual(self.handler.path, '/') |
---|
816 | n/a | self.assertEqual(self.handler.request_version, 'HTTP/1.0') |
---|
817 | n/a | self.assertSequenceEqual(self.handler.headers.items(), ()) |
---|
818 | n/a | |
---|
819 | n/a | def test_http_0_9(self): |
---|
820 | n/a | result = self.send_typical_request(b'GET / HTTP/0.9\r\n\r\n') |
---|
821 | n/a | self.assertEqual(len(result), 1) |
---|
822 | n/a | self.assertEqual(result[0], b'<html><body>Data</body></html>\r\n') |
---|
823 | n/a | self.verify_get_called() |
---|
824 | n/a | |
---|
825 | n/a | def test_extra_space(self): |
---|
826 | n/a | result = self.send_typical_request( |
---|
827 | n/a | b'GET /spaced out HTTP/1.1\r\n' |
---|
828 | n/a | b'Host: dummy\r\n' |
---|
829 | n/a | b'\r\n' |
---|
830 | n/a | ) |
---|
831 | n/a | self.assertTrue(result[0].startswith(b'HTTP/1.1 400 ')) |
---|
832 | n/a | self.verify_expected_headers(result[1:result.index(b'\r\n')]) |
---|
833 | n/a | self.assertFalse(self.handler.get_called) |
---|
834 | n/a | |
---|
835 | n/a | def test_with_continue_1_0(self): |
---|
836 | n/a | result = self.send_typical_request(b'GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n') |
---|
837 | n/a | self.verify_http_server_response(result[0]) |
---|
838 | n/a | self.verify_expected_headers(result[1:-1]) |
---|
839 | n/a | self.verify_get_called() |
---|
840 | n/a | self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n') |
---|
841 | n/a | self.assertEqual(self.handler.requestline, 'GET / HTTP/1.0') |
---|
842 | n/a | self.assertEqual(self.handler.command, 'GET') |
---|
843 | n/a | self.assertEqual(self.handler.path, '/') |
---|
844 | n/a | self.assertEqual(self.handler.request_version, 'HTTP/1.0') |
---|
845 | n/a | headers = (("Expect", "100-continue"),) |
---|
846 | n/a | self.assertSequenceEqual(self.handler.headers.items(), headers) |
---|
847 | n/a | |
---|
848 | n/a | def test_with_continue_1_1(self): |
---|
849 | n/a | result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n') |
---|
850 | n/a | self.assertEqual(result[0], b'HTTP/1.1 100 Continue\r\n') |
---|
851 | n/a | self.assertEqual(result[1], b'\r\n') |
---|
852 | n/a | self.assertEqual(result[2], b'HTTP/1.1 200 OK\r\n') |
---|
853 | n/a | self.verify_expected_headers(result[2:-1]) |
---|
854 | n/a | self.verify_get_called() |
---|
855 | n/a | self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n') |
---|
856 | n/a | self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1') |
---|
857 | n/a | self.assertEqual(self.handler.command, 'GET') |
---|
858 | n/a | self.assertEqual(self.handler.path, '/') |
---|
859 | n/a | self.assertEqual(self.handler.request_version, 'HTTP/1.1') |
---|
860 | n/a | headers = (("Expect", "100-continue"),) |
---|
861 | n/a | self.assertSequenceEqual(self.handler.headers.items(), headers) |
---|
862 | n/a | |
---|
863 | n/a | def test_header_buffering_of_send_error(self): |
---|
864 | n/a | |
---|
865 | n/a | input = BytesIO(b'GET / HTTP/1.1\r\n\r\n') |
---|
866 | n/a | output = AuditableBytesIO() |
---|
867 | n/a | handler = SocketlessRequestHandler() |
---|
868 | n/a | handler.rfile = input |
---|
869 | n/a | handler.wfile = output |
---|
870 | n/a | handler.request_version = 'HTTP/1.1' |
---|
871 | n/a | handler.requestline = '' |
---|
872 | n/a | handler.command = None |
---|
873 | n/a | |
---|
874 | n/a | handler.send_error(418) |
---|
875 | n/a | self.assertEqual(output.numWrites, 2) |
---|
876 | n/a | |
---|
877 | n/a | def test_header_buffering_of_send_response_only(self): |
---|
878 | n/a | |
---|
879 | n/a | input = BytesIO(b'GET / HTTP/1.1\r\n\r\n') |
---|
880 | n/a | output = AuditableBytesIO() |
---|
881 | n/a | handler = SocketlessRequestHandler() |
---|
882 | n/a | handler.rfile = input |
---|
883 | n/a | handler.wfile = output |
---|
884 | n/a | handler.request_version = 'HTTP/1.1' |
---|
885 | n/a | |
---|
886 | n/a | handler.send_response_only(418) |
---|
887 | n/a | self.assertEqual(output.numWrites, 0) |
---|
888 | n/a | handler.end_headers() |
---|
889 | n/a | self.assertEqual(output.numWrites, 1) |
---|
890 | n/a | |
---|
891 | n/a | def test_header_buffering_of_send_header(self): |
---|
892 | n/a | |
---|
893 | n/a | input = BytesIO(b'GET / HTTP/1.1\r\n\r\n') |
---|
894 | n/a | output = AuditableBytesIO() |
---|
895 | n/a | handler = SocketlessRequestHandler() |
---|
896 | n/a | handler.rfile = input |
---|
897 | n/a | handler.wfile = output |
---|
898 | n/a | handler.request_version = 'HTTP/1.1' |
---|
899 | n/a | |
---|
900 | n/a | handler.send_header('Foo', 'foo') |
---|
901 | n/a | handler.send_header('bar', 'bar') |
---|
902 | n/a | self.assertEqual(output.numWrites, 0) |
---|
903 | n/a | handler.end_headers() |
---|
904 | n/a | self.assertEqual(output.getData(), b'Foo: foo\r\nbar: bar\r\n\r\n') |
---|
905 | n/a | self.assertEqual(output.numWrites, 1) |
---|
906 | n/a | |
---|
907 | n/a | def test_header_unbuffered_when_continue(self): |
---|
908 | n/a | |
---|
909 | n/a | def _readAndReseek(f): |
---|
910 | n/a | pos = f.tell() |
---|
911 | n/a | f.seek(0) |
---|
912 | n/a | data = f.read() |
---|
913 | n/a | f.seek(pos) |
---|
914 | n/a | return data |
---|
915 | n/a | |
---|
916 | n/a | input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n') |
---|
917 | n/a | output = BytesIO() |
---|
918 | n/a | self.handler.rfile = input |
---|
919 | n/a | self.handler.wfile = output |
---|
920 | n/a | self.handler.request_version = 'HTTP/1.1' |
---|
921 | n/a | |
---|
922 | n/a | self.handler.handle_one_request() |
---|
923 | n/a | self.assertNotEqual(_readAndReseek(output), b'') |
---|
924 | n/a | result = _readAndReseek(output).split(b'\r\n') |
---|
925 | n/a | self.assertEqual(result[0], b'HTTP/1.1 100 Continue') |
---|
926 | n/a | self.assertEqual(result[1], b'') |
---|
927 | n/a | self.assertEqual(result[2], b'HTTP/1.1 200 OK') |
---|
928 | n/a | |
---|
929 | n/a | def test_with_continue_rejected(self): |
---|
930 | n/a | usual_handler = self.handler # Save to avoid breaking any subsequent tests. |
---|
931 | n/a | self.handler = RejectingSocketlessRequestHandler() |
---|
932 | n/a | result = self.send_typical_request(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n') |
---|
933 | n/a | self.assertEqual(result[0], b'HTTP/1.1 417 Expectation Failed\r\n') |
---|
934 | n/a | self.verify_expected_headers(result[1:-1]) |
---|
935 | n/a | # The expect handler should short circuit the usual get method by |
---|
936 | n/a | # returning false here, so get_called should be false |
---|
937 | n/a | self.assertFalse(self.handler.get_called) |
---|
938 | n/a | self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1) |
---|
939 | n/a | self.handler = usual_handler # Restore to avoid breaking any subsequent tests. |
---|
940 | n/a | |
---|
941 | n/a | def test_request_length(self): |
---|
942 | n/a | # Issue #10714: huge request lines are discarded, to avoid Denial |
---|
943 | n/a | # of Service attacks. |
---|
944 | n/a | result = self.send_typical_request(b'GET ' + b'x' * 65537) |
---|
945 | n/a | self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n') |
---|
946 | n/a | self.assertFalse(self.handler.get_called) |
---|
947 | n/a | self.assertIsInstance(self.handler.requestline, str) |
---|
948 | n/a | |
---|
949 | n/a | def test_header_length(self): |
---|
950 | n/a | # Issue #6791: same for headers |
---|
951 | n/a | result = self.send_typical_request( |
---|
952 | n/a | b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n') |
---|
953 | n/a | self.assertEqual(result[0], b'HTTP/1.1 431 Line too long\r\n') |
---|
954 | n/a | self.assertFalse(self.handler.get_called) |
---|
955 | n/a | self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1') |
---|
956 | n/a | |
---|
957 | n/a | def test_too_many_headers(self): |
---|
958 | n/a | result = self.send_typical_request( |
---|
959 | n/a | b'GET / HTTP/1.1\r\n' + b'X-Foo: bar\r\n' * 101 + b'\r\n') |
---|
960 | n/a | self.assertEqual(result[0], b'HTTP/1.1 431 Too many headers\r\n') |
---|
961 | n/a | self.assertFalse(self.handler.get_called) |
---|
962 | n/a | self.assertEqual(self.handler.requestline, 'GET / HTTP/1.1') |
---|
963 | n/a | |
---|
964 | n/a | def test_html_escape_on_error(self): |
---|
965 | n/a | result = self.send_typical_request( |
---|
966 | n/a | b'<script>alert("hello")</script> / HTTP/1.1') |
---|
967 | n/a | result = b''.join(result) |
---|
968 | n/a | text = '<script>alert("hello")</script>' |
---|
969 | n/a | self.assertIn(html.escape(text, quote=False).encode('ascii'), result) |
---|
970 | n/a | |
---|
971 | n/a | def test_close_connection(self): |
---|
972 | n/a | # handle_one_request() should be repeatedly called until |
---|
973 | n/a | # it sets close_connection |
---|
974 | n/a | def handle_one_request(): |
---|
975 | n/a | self.handler.close_connection = next(close_values) |
---|
976 | n/a | self.handler.handle_one_request = handle_one_request |
---|
977 | n/a | |
---|
978 | n/a | close_values = iter((True,)) |
---|
979 | n/a | self.handler.handle() |
---|
980 | n/a | self.assertRaises(StopIteration, next, close_values) |
---|
981 | n/a | |
---|
982 | n/a | close_values = iter((False, False, True)) |
---|
983 | n/a | self.handler.handle() |
---|
984 | n/a | self.assertRaises(StopIteration, next, close_values) |
---|
985 | n/a | |
---|
986 | n/a | def test_date_time_string(self): |
---|
987 | n/a | now = time.time() |
---|
988 | n/a | # this is the old code that formats the timestamp |
---|
989 | n/a | year, month, day, hh, mm, ss, wd, y, z = time.gmtime(now) |
---|
990 | n/a | expected = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( |
---|
991 | n/a | self.handler.weekdayname[wd], |
---|
992 | n/a | day, |
---|
993 | n/a | self.handler.monthname[month], |
---|
994 | n/a | year, hh, mm, ss |
---|
995 | n/a | ) |
---|
996 | n/a | self.assertEqual(self.handler.date_time_string(timestamp=now), expected) |
---|
997 | n/a | |
---|
998 | n/a | |
---|
999 | n/a | class SimpleHTTPRequestHandlerTestCase(unittest.TestCase): |
---|
1000 | n/a | """ Test url parsing """ |
---|
1001 | n/a | def setUp(self): |
---|
1002 | n/a | self.translated = os.getcwd() |
---|
1003 | n/a | self.translated = os.path.join(self.translated, 'filename') |
---|
1004 | n/a | self.handler = SocketlessRequestHandler() |
---|
1005 | n/a | |
---|
1006 | n/a | def test_query_arguments(self): |
---|
1007 | n/a | path = self.handler.translate_path('/filename') |
---|
1008 | n/a | self.assertEqual(path, self.translated) |
---|
1009 | n/a | path = self.handler.translate_path('/filename?foo=bar') |
---|
1010 | n/a | self.assertEqual(path, self.translated) |
---|
1011 | n/a | path = self.handler.translate_path('/filename?a=b&spam=eggs#zot') |
---|
1012 | n/a | self.assertEqual(path, self.translated) |
---|
1013 | n/a | |
---|
1014 | n/a | def test_start_with_double_slash(self): |
---|
1015 | n/a | path = self.handler.translate_path('//filename') |
---|
1016 | n/a | self.assertEqual(path, self.translated) |
---|
1017 | n/a | path = self.handler.translate_path('//filename?foo=bar') |
---|
1018 | n/a | self.assertEqual(path, self.translated) |
---|
1019 | n/a | |
---|
1020 | n/a | def test_windows_colon(self): |
---|
1021 | n/a | with support.swap_attr(server.os, 'path', ntpath): |
---|
1022 | n/a | path = self.handler.translate_path('c:c:c:foo/filename') |
---|
1023 | n/a | path = path.replace(ntpath.sep, os.sep) |
---|
1024 | n/a | self.assertEqual(path, self.translated) |
---|
1025 | n/a | |
---|
1026 | n/a | path = self.handler.translate_path('\\c:../filename') |
---|
1027 | n/a | path = path.replace(ntpath.sep, os.sep) |
---|
1028 | n/a | self.assertEqual(path, self.translated) |
---|
1029 | n/a | |
---|
1030 | n/a | path = self.handler.translate_path('c:\\c:..\\foo/filename') |
---|
1031 | n/a | path = path.replace(ntpath.sep, os.sep) |
---|
1032 | n/a | self.assertEqual(path, self.translated) |
---|
1033 | n/a | |
---|
1034 | n/a | path = self.handler.translate_path('c:c:foo\\c:c:bar/filename') |
---|
1035 | n/a | path = path.replace(ntpath.sep, os.sep) |
---|
1036 | n/a | self.assertEqual(path, self.translated) |
---|
1037 | n/a | |
---|
1038 | n/a | |
---|
1039 | n/a | class MiscTestCase(unittest.TestCase): |
---|
1040 | n/a | def test_all(self): |
---|
1041 | n/a | expected = [] |
---|
1042 | n/a | blacklist = {'executable', 'nobody_uid', 'test'} |
---|
1043 | n/a | for name in dir(server): |
---|
1044 | n/a | if name.startswith('_') or name in blacklist: |
---|
1045 | n/a | continue |
---|
1046 | n/a | module_object = getattr(server, name) |
---|
1047 | n/a | if getattr(module_object, '__module__', None) == 'http.server': |
---|
1048 | n/a | expected.append(name) |
---|
1049 | n/a | self.assertCountEqual(server.__all__, expected) |
---|
1050 | n/a | |
---|
1051 | n/a | |
---|
1052 | n/a | def test_main(verbose=None): |
---|
1053 | n/a | cwd = os.getcwd() |
---|
1054 | n/a | try: |
---|
1055 | n/a | support.run_unittest( |
---|
1056 | n/a | RequestHandlerLoggingTestCase, |
---|
1057 | n/a | BaseHTTPRequestHandlerTestCase, |
---|
1058 | n/a | BaseHTTPServerTestCase, |
---|
1059 | n/a | SimpleHTTPServerTestCase, |
---|
1060 | n/a | CGIHTTPServerTestCase, |
---|
1061 | n/a | SimpleHTTPRequestHandlerTestCase, |
---|
1062 | n/a | MiscTestCase, |
---|
1063 | n/a | ) |
---|
1064 | n/a | finally: |
---|
1065 | n/a | os.chdir(cwd) |
---|
1066 | n/a | |
---|
1067 | n/a | if __name__ == '__main__': |
---|
1068 | n/a | test_main() |
---|