test_httpservers.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. """Unittests for the various HTTPServer modules.
  2. Written by Cody A.W. Somerville <cody-somerville@ubuntu.com>,
  3. Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest.
  4. """
  5. import os
  6. import sys
  7. import re
  8. import base64
  9. import ntpath
  10. import shutil
  11. import urllib
  12. import httplib
  13. import tempfile
  14. import unittest
  15. import CGIHTTPServer
  16. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  17. from SimpleHTTPServer import SimpleHTTPRequestHandler
  18. from CGIHTTPServer import CGIHTTPRequestHandler
  19. from StringIO import StringIO
  20. from test import test_support
  21. threading = test_support.import_module('threading')
  22. class NoLogRequestHandler:
  23. def log_message(self, *args):
  24. # don't write log messages to stderr
  25. pass
  26. class SocketlessRequestHandler(SimpleHTTPRequestHandler):
  27. def __init__(self):
  28. self.get_called = False
  29. self.protocol_version = "HTTP/1.1"
  30. def do_GET(self):
  31. self.get_called = True
  32. self.send_response(200)
  33. self.send_header('Content-Type', 'text/html')
  34. self.end_headers()
  35. self.wfile.write(b'<html><body>Data</body></html>\r\n')
  36. def log_message(self, fmt, *args):
  37. pass
  38. class TestServerThread(threading.Thread):
  39. def __init__(self, test_object, request_handler):
  40. threading.Thread.__init__(self)
  41. self.request_handler = request_handler
  42. self.test_object = test_object
  43. def run(self):
  44. self.server = HTTPServer(('', 0), self.request_handler)
  45. self.test_object.PORT = self.server.socket.getsockname()[1]
  46. self.test_object.server_started.set()
  47. self.test_object = None
  48. try:
  49. self.server.serve_forever(0.05)
  50. finally:
  51. self.server.server_close()
  52. def stop(self):
  53. self.server.shutdown()
  54. class BaseTestCase(unittest.TestCase):
  55. def setUp(self):
  56. self._threads = test_support.threading_setup()
  57. os.environ = test_support.EnvironmentVarGuard()
  58. self.server_started = threading.Event()
  59. self.thread = TestServerThread(self, self.request_handler)
  60. self.thread.start()
  61. self.server_started.wait()
  62. def tearDown(self):
  63. self.thread.stop()
  64. os.environ.__exit__()
  65. test_support.threading_cleanup(*self._threads)
  66. def request(self, uri, method='GET', body=None, headers={}):
  67. self.connection = httplib.HTTPConnection('localhost', self.PORT)
  68. self.connection.request(method, uri, body, headers)
  69. return self.connection.getresponse()
  70. class BaseHTTPRequestHandlerTestCase(unittest.TestCase):
  71. """Test the functionality of the BaseHTTPServer focussing on
  72. BaseHTTPRequestHandler.
  73. """
  74. HTTPResponseMatch = re.compile('HTTP/1.[0-9]+ 200 OK')
  75. def setUp (self):
  76. self.handler = SocketlessRequestHandler()
  77. def send_typical_request(self, message):
  78. input_msg = StringIO(message)
  79. output = StringIO()
  80. self.handler.rfile = input_msg
  81. self.handler.wfile = output
  82. self.handler.handle_one_request()
  83. output.seek(0)
  84. return output.readlines()
  85. def verify_get_called(self):
  86. self.assertTrue(self.handler.get_called)
  87. def verify_expected_headers(self, headers):
  88. for fieldName in 'Server: ', 'Date: ', 'Content-Type: ':
  89. self.assertEqual(sum(h.startswith(fieldName) for h in headers), 1)
  90. def verify_http_server_response(self, response):
  91. match = self.HTTPResponseMatch.search(response)
  92. self.assertIsNotNone(match)
  93. def test_http_1_1(self):
  94. result = self.send_typical_request('GET / HTTP/1.1\r\n\r\n')
  95. self.verify_http_server_response(result[0])
  96. self.verify_expected_headers(result[1:-1])
  97. self.verify_get_called()
  98. self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
  99. def test_http_1_0(self):
  100. result = self.send_typical_request('GET / HTTP/1.0\r\n\r\n')
  101. self.verify_http_server_response(result[0])
  102. self.verify_expected_headers(result[1:-1])
  103. self.verify_get_called()
  104. self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
  105. def test_http_0_9(self):
  106. result = self.send_typical_request('GET / HTTP/0.9\r\n\r\n')
  107. self.assertEqual(len(result), 1)
  108. self.assertEqual(result[0], '<html><body>Data</body></html>\r\n')
  109. self.verify_get_called()
  110. def test_with_continue_1_0(self):
  111. result = self.send_typical_request('GET / HTTP/1.0\r\nExpect: 100-continue\r\n\r\n')
  112. self.verify_http_server_response(result[0])
  113. self.verify_expected_headers(result[1:-1])
  114. self.verify_get_called()
  115. self.assertEqual(result[-1], '<html><body>Data</body></html>\r\n')
  116. def test_request_length(self):
  117. # Issue #10714: huge request lines are discarded, to avoid Denial
  118. # of Service attacks.
  119. result = self.send_typical_request(b'GET ' + b'x' * 65537)
  120. self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
  121. self.assertFalse(self.handler.get_called)
  122. class BaseHTTPServerTestCase(BaseTestCase):
  123. class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
  124. protocol_version = 'HTTP/1.1'
  125. default_request_version = 'HTTP/1.1'
  126. def do_TEST(self):
  127. self.send_response(204)
  128. self.send_header('Content-Type', 'text/html')
  129. self.send_header('Connection', 'close')
  130. self.end_headers()
  131. def do_KEEP(self):
  132. self.send_response(204)
  133. self.send_header('Content-Type', 'text/html')
  134. self.send_header('Connection', 'keep-alive')
  135. self.end_headers()
  136. def do_KEYERROR(self):
  137. self.send_error(999)
  138. def do_CUSTOM(self):
  139. self.send_response(999)
  140. self.send_header('Content-Type', 'text/html')
  141. self.send_header('Connection', 'close')
  142. self.end_headers()
  143. def do_SEND_ERROR(self):
  144. self.send_error(int(self.path[1:]))
  145. def do_HEAD(self):
  146. self.send_error(int(self.path[1:]))
  147. def setUp(self):
  148. BaseTestCase.setUp(self)
  149. self.con = httplib.HTTPConnection('localhost', self.PORT)
  150. self.con.connect()
  151. def test_command(self):
  152. self.con.request('GET', '/')
  153. res = self.con.getresponse()
  154. self.assertEqual(res.status, 501)
  155. def test_request_line_trimming(self):
  156. self.con._http_vsn_str = 'HTTP/1.1\n'
  157. self.con.putrequest('XYZBOGUS', '/')
  158. self.con.endheaders()
  159. res = self.con.getresponse()
  160. self.assertEqual(res.status, 501)
  161. def test_version_bogus(self):
  162. self.con._http_vsn_str = 'FUBAR'
  163. self.con.putrequest('GET', '/')
  164. self.con.endheaders()
  165. res = self.con.getresponse()
  166. self.assertEqual(res.status, 400)
  167. def test_version_digits(self):
  168. self.con._http_vsn_str = 'HTTP/9.9.9'
  169. self.con.putrequest('GET', '/')
  170. self.con.endheaders()
  171. res = self.con.getresponse()
  172. self.assertEqual(res.status, 400)
  173. def test_version_none_get(self):
  174. self.con._http_vsn_str = ''
  175. self.con.putrequest('GET', '/')
  176. self.con.endheaders()
  177. res = self.con.getresponse()
  178. self.assertEqual(res.status, 501)
  179. def test_version_none(self):
  180. # Test that a valid method is rejected when not HTTP/1.x
  181. self.con._http_vsn_str = ''
  182. self.con.putrequest('CUSTOM', '/')
  183. self.con.endheaders()
  184. res = self.con.getresponse()
  185. self.assertEqual(res.status, 400)
  186. def test_version_invalid(self):
  187. self.con._http_vsn = 99
  188. self.con._http_vsn_str = 'HTTP/9.9'
  189. self.con.putrequest('GET', '/')
  190. self.con.endheaders()
  191. res = self.con.getresponse()
  192. self.assertEqual(res.status, 505)
  193. def test_send_blank(self):
  194. self.con._http_vsn_str = ''
  195. self.con.putrequest('', '')
  196. self.con.endheaders()
  197. res = self.con.getresponse()
  198. self.assertEqual(res.status, 400)
  199. def test_header_close(self):
  200. self.con.putrequest('GET', '/')
  201. self.con.putheader('Connection', 'close')
  202. self.con.endheaders()
  203. res = self.con.getresponse()
  204. self.assertEqual(res.status, 501)
  205. def test_head_keep_alive(self):
  206. self.con._http_vsn_str = 'HTTP/1.1'
  207. self.con.putrequest('GET', '/')
  208. self.con.putheader('Connection', 'keep-alive')
  209. self.con.endheaders()
  210. res = self.con.getresponse()
  211. self.assertEqual(res.status, 501)
  212. def test_handler(self):
  213. self.con.request('TEST', '/')
  214. res = self.con.getresponse()
  215. self.assertEqual(res.status, 204)
  216. def test_return_header_keep_alive(self):
  217. self.con.request('KEEP', '/')
  218. res = self.con.getresponse()
  219. self.assertEqual(res.getheader('Connection'), 'keep-alive')
  220. self.con.request('TEST', '/')
  221. self.addCleanup(self.con.close)
  222. def test_internal_key_error(self):
  223. self.con.request('KEYERROR', '/')
  224. res = self.con.getresponse()
  225. self.assertEqual(res.status, 999)
  226. def test_return_custom_status(self):
  227. self.con.request('CUSTOM', '/')
  228. res = self.con.getresponse()
  229. self.assertEqual(res.status, 999)
  230. def test_send_error(self):
  231. allow_transfer_encoding_codes = (205, 304)
  232. for code in (101, 102, 204, 205, 304):
  233. self.con.request('SEND_ERROR', '/{}'.format(code))
  234. res = self.con.getresponse()
  235. self.assertEqual(code, res.status)
  236. self.assertEqual(None, res.getheader('Content-Length'))
  237. self.assertEqual(None, res.getheader('Content-Type'))
  238. if code not in allow_transfer_encoding_codes:
  239. self.assertEqual(None, res.getheader('Transfer-Encoding'))
  240. data = res.read()
  241. self.assertEqual(b'', data)
  242. def test_head_via_send_error(self):
  243. allow_transfer_encoding_codes = (205, 304)
  244. for code in (101, 200, 204, 205, 304):
  245. self.con.request('HEAD', '/{}'.format(code))
  246. res = self.con.getresponse()
  247. self.assertEqual(code, res.status)
  248. if code == 200:
  249. self.assertEqual(None, res.getheader('Content-Length'))
  250. self.assertIn('text/html', res.getheader('Content-Type'))
  251. else:
  252. self.assertEqual(None, res.getheader('Content-Length'))
  253. self.assertEqual(None, res.getheader('Content-Type'))
  254. if code not in allow_transfer_encoding_codes:
  255. self.assertEqual(None, res.getheader('Transfer-Encoding'))
  256. data = res.read()
  257. self.assertEqual(b'', data)
  258. class SimpleHTTPServerTestCase(BaseTestCase):
  259. class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
  260. pass
  261. def setUp(self):
  262. BaseTestCase.setUp(self)
  263. self.cwd = os.getcwd()
  264. basetempdir = tempfile.gettempdir()
  265. os.chdir(basetempdir)
  266. self.data = 'We are the knights who say Ni!'
  267. self.tempdir = tempfile.mkdtemp(dir=basetempdir)
  268. self.tempdir_name = os.path.basename(self.tempdir)
  269. self.base_url = '/' + self.tempdir_name
  270. temp = open(os.path.join(self.tempdir, 'test'), 'wb')
  271. temp.write(self.data)
  272. temp.close()
  273. def tearDown(self):
  274. try:
  275. os.chdir(self.cwd)
  276. try:
  277. shutil.rmtree(self.tempdir)
  278. except OSError:
  279. pass
  280. finally:
  281. BaseTestCase.tearDown(self)
  282. def check_status_and_reason(self, response, status, data=None):
  283. body = response.read()
  284. self.assertTrue(response)
  285. self.assertEqual(response.status, status)
  286. self.assertIsNotNone(response.reason)
  287. if data:
  288. self.assertEqual(data, body)
  289. def test_get(self):
  290. #constructs the path relative to the root directory of the HTTPServer
  291. response = self.request(self.base_url + '/test')
  292. self.check_status_and_reason(response, 200, data=self.data)
  293. # check for trailing "/" which should return 404. See Issue17324
  294. response = self.request(self.base_url + '/test/')
  295. self.check_status_and_reason(response, 404)
  296. response = self.request(self.base_url + '/')
  297. self.check_status_and_reason(response, 200)
  298. response = self.request(self.base_url)
  299. self.check_status_and_reason(response, 301)
  300. response = self.request(self.base_url + '/?hi=2')
  301. self.check_status_and_reason(response, 200)
  302. response = self.request(self.base_url + '?hi=1')
  303. self.check_status_and_reason(response, 301)
  304. self.assertEqual(response.getheader("Location"),
  305. self.base_url + "/?hi=1")
  306. response = self.request('/ThisDoesNotExist')
  307. self.check_status_and_reason(response, 404)
  308. response = self.request('/' + 'ThisDoesNotExist' + '/')
  309. self.check_status_and_reason(response, 404)
  310. with open(os.path.join(self.tempdir_name, 'index.html'), 'w') as fp:
  311. response = self.request(self.base_url + '/')
  312. self.check_status_and_reason(response, 200)
  313. # chmod() doesn't work as expected on Windows, and filesystem
  314. # permissions are ignored by root on Unix.
  315. if os.name == 'posix' and os.geteuid() != 0:
  316. os.chmod(self.tempdir, 0)
  317. response = self.request(self.base_url + '/')
  318. self.check_status_and_reason(response, 404)
  319. os.chmod(self.tempdir, 0755)
  320. def test_head(self):
  321. response = self.request(
  322. self.base_url + '/test', method='HEAD')
  323. self.check_status_and_reason(response, 200)
  324. self.assertEqual(response.getheader('content-length'),
  325. str(len(self.data)))
  326. self.assertEqual(response.getheader('content-type'),
  327. 'application/octet-stream')
  328. def test_invalid_requests(self):
  329. response = self.request('/', method='FOO')
  330. self.check_status_and_reason(response, 501)
  331. # requests must be case sensitive,so this should fail too
  332. response = self.request('/', method='custom')
  333. self.check_status_and_reason(response, 501)
  334. response = self.request('/', method='GETs')
  335. self.check_status_and_reason(response, 501)
  336. def test_path_without_leading_slash(self):
  337. response = self.request(self.tempdir_name + '/test')
  338. self.check_status_and_reason(response, 200, data=self.data)
  339. response = self.request(self.tempdir_name + '/test/')
  340. self.check_status_and_reason(response, 404)
  341. response = self.request(self.tempdir_name + '/')
  342. self.check_status_and_reason(response, 200)
  343. response = self.request(self.tempdir_name)
  344. self.check_status_and_reason(response, 301)
  345. response = self.request(self.tempdir_name + '/?hi=2')
  346. self.check_status_and_reason(response, 200)
  347. response = self.request(self.tempdir_name + '?hi=1')
  348. self.check_status_and_reason(response, 301)
  349. self.assertEqual(response.getheader("Location"),
  350. self.tempdir_name + "/?hi=1")
  351. cgi_file1 = """\
  352. #!%s
  353. print "Content-type: text/html"
  354. print
  355. print "Hello World"
  356. """
  357. cgi_file2 = """\
  358. #!%s
  359. import cgi
  360. print "Content-type: text/html"
  361. print
  362. form = cgi.FieldStorage()
  363. print "%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),
  364. form.getfirst("bacon"))
  365. """
  366. cgi_file4 = """\
  367. #!%s
  368. import os
  369. print("Content-type: text/html")
  370. print()
  371. print(os.environ["%s"])
  372. """
  373. @unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0,
  374. "This test can't be run reliably as root (issue #13308).")
  375. class CGIHTTPServerTestCase(BaseTestCase):
  376. class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
  377. pass
  378. def setUp(self):
  379. BaseTestCase.setUp(self)
  380. self.parent_dir = tempfile.mkdtemp()
  381. self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
  382. self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir')
  383. os.mkdir(self.cgi_dir)
  384. os.mkdir(self.cgi_child_dir)
  385. # The shebang line should be pure ASCII: use symlink if possible.
  386. # See issue #7668.
  387. if hasattr(os, 'symlink'):
  388. self.pythonexe = os.path.join(self.parent_dir, 'python')
  389. os.symlink(sys.executable, self.pythonexe)
  390. else:
  391. self.pythonexe = sys.executable
  392. self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py')
  393. with open(self.nocgi_path, 'w') as fp:
  394. fp.write(cgi_file1 % self.pythonexe)
  395. os.chmod(self.nocgi_path, 0777)
  396. self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
  397. with open(self.file1_path, 'w') as file1:
  398. file1.write(cgi_file1 % self.pythonexe)
  399. os.chmod(self.file1_path, 0777)
  400. self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
  401. with open(self.file2_path, 'w') as file2:
  402. file2.write(cgi_file2 % self.pythonexe)
  403. os.chmod(self.file2_path, 0777)
  404. self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py')
  405. with open(self.file3_path, 'w') as file3:
  406. file3.write(cgi_file1 % self.pythonexe)
  407. os.chmod(self.file3_path, 0777)
  408. self.file4_path = os.path.join(self.cgi_dir, 'file4.py')
  409. with open(self.file4_path, 'w') as file4:
  410. file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING'))
  411. os.chmod(self.file4_path, 0o777)
  412. self.cwd = os.getcwd()
  413. os.chdir(self.parent_dir)
  414. def tearDown(self):
  415. try:
  416. os.chdir(self.cwd)
  417. if self.pythonexe != sys.executable:
  418. os.remove(self.pythonexe)
  419. os.remove(self.nocgi_path)
  420. os.remove(self.file1_path)
  421. os.remove(self.file2_path)
  422. os.remove(self.file3_path)
  423. os.remove(self.file4_path)
  424. os.rmdir(self.cgi_child_dir)
  425. os.rmdir(self.cgi_dir)
  426. os.rmdir(self.parent_dir)
  427. finally:
  428. BaseTestCase.tearDown(self)
  429. def test_url_collapse_path(self):
  430. # verify tail is the last portion and head is the rest on proper urls
  431. test_vectors = {
  432. '': '//',
  433. '..': IndexError,
  434. '/.//..': IndexError,
  435. '/': '//',
  436. '//': '//',
  437. '/\\': '//\\',
  438. '/.//': '//',
  439. 'cgi-bin/file1.py': '/cgi-bin/file1.py',
  440. '/cgi-bin/file1.py': '/cgi-bin/file1.py',
  441. 'a': '//a',
  442. '/a': '//a',
  443. '//a': '//a',
  444. './a': '//a',
  445. './C:/': '/C:/',
  446. '/a/b': '/a/b',
  447. '/a/b/': '/a/b/',
  448. '/a/b/.': '/a/b/',
  449. '/a/b/c/..': '/a/b/',
  450. '/a/b/c/../d': '/a/b/d',
  451. '/a/b/c/../d/e/../f': '/a/b/d/f',
  452. '/a/b/c/../d/e/../../f': '/a/b/f',
  453. '/a/b/c/../d/e/.././././..//f': '/a/b/f',
  454. '../a/b/c/../d/e/.././././..//f': IndexError,
  455. '/a/b/c/../d/e/../../../f': '/a/f',
  456. '/a/b/c/../d/e/../../../../f': '//f',
  457. '/a/b/c/../d/e/../../../../../f': IndexError,
  458. '/a/b/c/../d/e/../../../../f/..': '//',
  459. '/a/b/c/../d/e/../../../../f/../.': '//',
  460. }
  461. for path, expected in test_vectors.iteritems():
  462. if isinstance(expected, type) and issubclass(expected, Exception):
  463. self.assertRaises(expected,
  464. CGIHTTPServer._url_collapse_path, path)
  465. else:
  466. actual = CGIHTTPServer._url_collapse_path(path)
  467. self.assertEqual(expected, actual,
  468. msg='path = %r\nGot: %r\nWanted: %r' %
  469. (path, actual, expected))
  470. def test_headers_and_content(self):
  471. res = self.request('/cgi-bin/file1.py')
  472. self.assertEqual(('Hello World\n', 'text/html', 200),
  473. (res.read(), res.getheader('Content-type'), res.status))
  474. def test_issue19435(self):
  475. res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh')
  476. self.assertEqual(res.status, 404)
  477. def test_post(self):
  478. params = urllib.urlencode({'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
  479. headers = {'Content-type' : 'application/x-www-form-urlencoded'}
  480. res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
  481. self.assertEqual(res.read(), '1, python, 123456\n')
  482. def test_invaliduri(self):
  483. res = self.request('/cgi-bin/invalid')
  484. res.read()
  485. self.assertEqual(res.status, 404)
  486. def test_authorization(self):
  487. headers = {'Authorization' : 'Basic %s' %
  488. base64.b64encode('username:pass')}
  489. res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
  490. self.assertEqual(('Hello World\n', 'text/html', 200),
  491. (res.read(), res.getheader('Content-type'), res.status))
  492. def test_no_leading_slash(self):
  493. # http://bugs.python.org/issue2254
  494. res = self.request('cgi-bin/file1.py')
  495. self.assertEqual(('Hello World\n', 'text/html', 200),
  496. (res.read(), res.getheader('Content-type'), res.status))
  497. def test_os_environ_is_not_altered(self):
  498. signature = "Test CGI Server"
  499. os.environ['SERVER_SOFTWARE'] = signature
  500. res = self.request('/cgi-bin/file1.py')
  501. self.assertEqual((b'Hello World\n', 'text/html', 200),
  502. (res.read(), res.getheader('Content-type'), res.status))
  503. self.assertEqual(os.environ['SERVER_SOFTWARE'], signature)
  504. def test_urlquote_decoding_in_cgi_check(self):
  505. res = self.request('/cgi-bin%2ffile1.py')
  506. self.assertEqual((b'Hello World\n', 'text/html', 200),
  507. (res.read(), res.getheader('Content-type'), res.status))
  508. def test_nested_cgi_path_issue21323(self):
  509. res = self.request('/cgi-bin/child-dir/file3.py')
  510. self.assertEqual((b'Hello World\n', 'text/html', 200),
  511. (res.read(), res.getheader('Content-type'), res.status))
  512. def test_query_with_multiple_question_mark(self):
  513. res = self.request('/cgi-bin/file4.py?a=b?c=d')
  514. self.assertEqual(
  515. (b'a=b?c=d\n', 'text/html', 200),
  516. (res.read(), res.getheader('Content-type'), res.status))
  517. def test_query_with_continuous_slashes(self):
  518. res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//')
  519. self.assertEqual(
  520. (b'k=aa%2F%2Fbb&//q//p//=//a//b//\n',
  521. 'text/html', 200),
  522. (res.read(), res.getheader('Content-type'), res.status))
  523. class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
  524. """ Test url parsing """
  525. def setUp(self):
  526. self.translated = os.getcwd()
  527. self.translated = os.path.join(self.translated, 'filename')
  528. self.handler = SocketlessRequestHandler()
  529. def test_query_arguments(self):
  530. path = self.handler.translate_path('/filename')
  531. self.assertEqual(path, self.translated)
  532. path = self.handler.translate_path('/filename?foo=bar')
  533. self.assertEqual(path, self.translated)
  534. path = self.handler.translate_path('/filename?a=b&spam=eggs#zot')
  535. self.assertEqual(path, self.translated)
  536. def test_start_with_double_slash(self):
  537. path = self.handler.translate_path('//filename')
  538. self.assertEqual(path, self.translated)
  539. path = self.handler.translate_path('//filename?foo=bar')
  540. self.assertEqual(path, self.translated)
  541. def test_windows_colon(self):
  542. import SimpleHTTPServer
  543. with test_support.swap_attr(SimpleHTTPServer.os, 'path', ntpath):
  544. path = self.handler.translate_path('c:c:c:foo/filename')
  545. path = path.replace(ntpath.sep, os.sep)
  546. self.assertEqual(path, self.translated)
  547. path = self.handler.translate_path('\\c:../filename')
  548. path = path.replace(ntpath.sep, os.sep)
  549. self.assertEqual(path, self.translated)
  550. path = self.handler.translate_path('c:\\c:..\\foo/filename')
  551. path = path.replace(ntpath.sep, os.sep)
  552. self.assertEqual(path, self.translated)
  553. path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
  554. path = path.replace(ntpath.sep, os.sep)
  555. self.assertEqual(path, self.translated)
  556. def test_main(verbose=None):
  557. try:
  558. cwd = os.getcwd()
  559. test_support.run_unittest(BaseHTTPRequestHandlerTestCase,
  560. SimpleHTTPRequestHandlerTestCase,
  561. BaseHTTPServerTestCase,
  562. SimpleHTTPServerTestCase,
  563. CGIHTTPServerTestCase
  564. )
  565. finally:
  566. os.chdir(cwd)
  567. if __name__ == '__main__':
  568. test_main()