PageRenderTime 22ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/IronPython_Main/External.LCA_RESTRICTED/Languages/IronPython/26/Lib/test/test_httpservers.py

#
Python | 354 lines | 335 code | 12 blank | 7 comment | 0 complexity | 68e51889eaa0a42b698a119cb01ec8f2 MD5 | raw file
Possible License(s): GPL-2.0, MPL-2.0-no-copyleft-exception, CPL-1.0, CC-BY-SA-3.0, BSD-3-Clause, ISC, AGPL-3.0, LGPL-2.1, Apache-2.0
  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. from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
  6. from SimpleHTTPServer import SimpleHTTPRequestHandler
  7. from CGIHTTPServer import CGIHTTPRequestHandler
  8. import os
  9. import sys
  10. import base64
  11. import shutil
  12. import urllib
  13. import httplib
  14. import tempfile
  15. import threading
  16. import unittest
  17. from test import test_support
  18. class NoLogRequestHandler:
  19. def log_message(self, *args):
  20. # don't write log messages to stderr
  21. pass
  22. class TestServerThread(threading.Thread):
  23. def __init__(self, test_object, request_handler):
  24. threading.Thread.__init__(self)
  25. self.request_handler = request_handler
  26. self.test_object = test_object
  27. self.test_object.lock.acquire()
  28. def run(self):
  29. self.server = HTTPServer(('', 0), self.request_handler)
  30. self.test_object.PORT = self.server.socket.getsockname()[1]
  31. self.test_object.lock.release()
  32. try:
  33. self.server.serve_forever()
  34. finally:
  35. self.server.server_close()
  36. def stop(self):
  37. self.server.shutdown()
  38. class BaseTestCase(unittest.TestCase):
  39. def setUp(self):
  40. self.lock = threading.Lock()
  41. self.thread = TestServerThread(self, self.request_handler)
  42. self.thread.start()
  43. self.lock.acquire()
  44. def tearDown(self):
  45. self.lock.release()
  46. self.thread.stop()
  47. def request(self, uri, method='GET', body=None, headers={}):
  48. self.connection = httplib.HTTPConnection('localhost', self.PORT)
  49. self.connection.request(method, uri, body, headers)
  50. return self.connection.getresponse()
  51. class BaseHTTPServerTestCase(BaseTestCase):
  52. class request_handler(NoLogRequestHandler, BaseHTTPRequestHandler):
  53. protocol_version = 'HTTP/1.1'
  54. default_request_version = 'HTTP/1.1'
  55. def do_TEST(self):
  56. self.send_response(204)
  57. self.send_header('Content-Type', 'text/html')
  58. self.send_header('Connection', 'close')
  59. self.end_headers()
  60. def do_KEEP(self):
  61. self.send_response(204)
  62. self.send_header('Content-Type', 'text/html')
  63. self.send_header('Connection', 'keep-alive')
  64. self.end_headers()
  65. def do_KEYERROR(self):
  66. self.send_error(999)
  67. def do_CUSTOM(self):
  68. self.send_response(999)
  69. self.send_header('Content-Type', 'text/html')
  70. self.send_header('Connection', 'close')
  71. self.end_headers()
  72. def setUp(self):
  73. BaseTestCase.setUp(self)
  74. self.con = httplib.HTTPConnection('localhost', self.PORT)
  75. self.con.connect()
  76. def test_command(self):
  77. self.con.request('GET', '/')
  78. res = self.con.getresponse()
  79. self.assertEquals(res.status, 501)
  80. def test_request_line_trimming(self):
  81. self.con._http_vsn_str = 'HTTP/1.1\n'
  82. self.con.putrequest('GET', '/')
  83. self.con.endheaders()
  84. res = self.con.getresponse()
  85. self.assertEquals(res.status, 501)
  86. def test_version_bogus(self):
  87. self.con._http_vsn_str = 'FUBAR'
  88. self.con.putrequest('GET', '/')
  89. self.con.endheaders()
  90. res = self.con.getresponse()
  91. self.assertEquals(res.status, 400)
  92. def test_version_digits(self):
  93. self.con._http_vsn_str = 'HTTP/9.9.9'
  94. self.con.putrequest('GET', '/')
  95. self.con.endheaders()
  96. res = self.con.getresponse()
  97. self.assertEquals(res.status, 400)
  98. def test_version_none_get(self):
  99. self.con._http_vsn_str = ''
  100. self.con.putrequest('GET', '/')
  101. self.con.endheaders()
  102. res = self.con.getresponse()
  103. self.assertEquals(res.status, 501)
  104. def test_version_none(self):
  105. self.con._http_vsn_str = ''
  106. self.con.putrequest('PUT', '/')
  107. self.con.endheaders()
  108. res = self.con.getresponse()
  109. self.assertEquals(res.status, 400)
  110. def test_version_invalid(self):
  111. self.con._http_vsn = 99
  112. self.con._http_vsn_str = 'HTTP/9.9'
  113. self.con.putrequest('GET', '/')
  114. self.con.endheaders()
  115. res = self.con.getresponse()
  116. self.assertEquals(res.status, 505)
  117. def test_send_blank(self):
  118. self.con._http_vsn_str = ''
  119. self.con.putrequest('', '')
  120. self.con.endheaders()
  121. res = self.con.getresponse()
  122. self.assertEquals(res.status, 400)
  123. def test_header_close(self):
  124. self.con.putrequest('GET', '/')
  125. self.con.putheader('Connection', 'close')
  126. self.con.endheaders()
  127. res = self.con.getresponse()
  128. self.assertEquals(res.status, 501)
  129. def test_head_keep_alive(self):
  130. self.con._http_vsn_str = 'HTTP/1.1'
  131. self.con.putrequest('GET', '/')
  132. self.con.putheader('Connection', 'keep-alive')
  133. self.con.endheaders()
  134. res = self.con.getresponse()
  135. self.assertEquals(res.status, 501)
  136. def test_handler(self):
  137. self.con.request('TEST', '/')
  138. res = self.con.getresponse()
  139. self.assertEquals(res.status, 204)
  140. def test_return_header_keep_alive(self):
  141. self.con.request('KEEP', '/')
  142. res = self.con.getresponse()
  143. self.assertEquals(res.getheader('Connection'), 'keep-alive')
  144. self.con.request('TEST', '/')
  145. def test_internal_key_error(self):
  146. self.con.request('KEYERROR', '/')
  147. res = self.con.getresponse()
  148. self.assertEquals(res.status, 999)
  149. def test_return_custom_status(self):
  150. self.con.request('CUSTOM', '/')
  151. res = self.con.getresponse()
  152. self.assertEquals(res.status, 999)
  153. class SimpleHTTPServerTestCase(BaseTestCase):
  154. class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
  155. pass
  156. def setUp(self):
  157. BaseTestCase.setUp(self)
  158. self.cwd = os.getcwd()
  159. basetempdir = tempfile.gettempdir()
  160. os.chdir(basetempdir)
  161. self.data = 'We are the knights who say Ni!'
  162. self.tempdir = tempfile.mkdtemp(dir=basetempdir)
  163. self.tempdir_name = os.path.basename(self.tempdir)
  164. temp = open(os.path.join(self.tempdir, 'test'), 'wb')
  165. temp.write(self.data)
  166. temp.close()
  167. def tearDown(self):
  168. try:
  169. os.chdir(self.cwd)
  170. try:
  171. shutil.rmtree(self.tempdir)
  172. except:
  173. pass
  174. finally:
  175. BaseTestCase.tearDown(self)
  176. def check_status_and_reason(self, response, status, data=None):
  177. body = response.read()
  178. self.assert_(response)
  179. self.assertEquals(response.status, status)
  180. self.assert_(response.reason != None)
  181. if data:
  182. self.assertEqual(data, body)
  183. def test_get(self):
  184. #constructs the path relative to the root directory of the HTTPServer
  185. response = self.request(self.tempdir_name + '/test')
  186. self.check_status_and_reason(response, 200, data=self.data)
  187. response = self.request(self.tempdir_name + '/')
  188. self.check_status_and_reason(response, 200)
  189. response = self.request(self.tempdir_name)
  190. self.check_status_and_reason(response, 301)
  191. response = self.request('/ThisDoesNotExist')
  192. self.check_status_and_reason(response, 404)
  193. response = self.request('/' + 'ThisDoesNotExist' + '/')
  194. self.check_status_and_reason(response, 404)
  195. f = open(os.path.join(self.tempdir_name, 'index.html'), 'w')
  196. response = self.request('/' + self.tempdir_name + '/')
  197. self.check_status_and_reason(response, 200)
  198. if os.name == 'posix':
  199. # chmod won't work as expected on Windows platforms
  200. os.chmod(self.tempdir, 0)
  201. response = self.request(self.tempdir_name + '/')
  202. self.check_status_and_reason(response, 404)
  203. os.chmod(self.tempdir, 0755)
  204. def test_head(self):
  205. response = self.request(
  206. self.tempdir_name + '/test', method='HEAD')
  207. self.check_status_and_reason(response, 200)
  208. self.assertEqual(response.getheader('content-length'),
  209. str(len(self.data)))
  210. self.assertEqual(response.getheader('content-type'),
  211. 'application/octet-stream')
  212. def test_invalid_requests(self):
  213. response = self.request('/', method='FOO')
  214. self.check_status_and_reason(response, 501)
  215. # requests must be case sensitive,so this should fail too
  216. response = self.request('/', method='get')
  217. self.check_status_and_reason(response, 501)
  218. response = self.request('/', method='GETs')
  219. self.check_status_and_reason(response, 501)
  220. cgi_file1 = """\
  221. #!%s
  222. print "Content-type: text/html"
  223. print
  224. print "Hello World"
  225. """
  226. cgi_file2 = """\
  227. #!%s
  228. import cgi
  229. print "Content-type: text/html"
  230. print
  231. form = cgi.FieldStorage()
  232. print "%%s, %%s, %%s" %% (form.getfirst("spam"), form.getfirst("eggs"),\
  233. form.getfirst("bacon"))
  234. """
  235. class CGIHTTPServerTestCase(BaseTestCase):
  236. class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler):
  237. pass
  238. def setUp(self):
  239. BaseTestCase.setUp(self)
  240. self.parent_dir = tempfile.mkdtemp()
  241. self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin')
  242. os.mkdir(self.cgi_dir)
  243. self.file1_path = os.path.join(self.cgi_dir, 'file1.py')
  244. with open(self.file1_path, 'w') as file1:
  245. file1.write(cgi_file1 % sys.executable)
  246. os.chmod(self.file1_path, 0777)
  247. self.file2_path = os.path.join(self.cgi_dir, 'file2.py')
  248. with open(self.file2_path, 'w') as file2:
  249. file2.write(cgi_file2 % sys.executable)
  250. os.chmod(self.file2_path, 0777)
  251. self.cwd = os.getcwd()
  252. os.chdir(self.parent_dir)
  253. def tearDown(self):
  254. try:
  255. os.chdir(self.cwd)
  256. os.remove(self.file1_path)
  257. os.remove(self.file2_path)
  258. os.rmdir(self.cgi_dir)
  259. os.rmdir(self.parent_dir)
  260. finally:
  261. BaseTestCase.tearDown(self)
  262. def test_headers_and_content(self):
  263. res = self.request('/cgi-bin/file1.py')
  264. self.assertEquals(('Hello World\n', 'text/html', 200), \
  265. (res.read(), res.getheader('Content-type'), res.status))
  266. def test_post(self):
  267. params = urllib.urlencode({'spam' : 1, 'eggs' : 'python', 'bacon' : 123456})
  268. headers = {'Content-type' : 'application/x-www-form-urlencoded'}
  269. res = self.request('/cgi-bin/file2.py', 'POST', params, headers)
  270. self.assertEquals(res.read(), '1, python, 123456\n')
  271. def test_invaliduri(self):
  272. res = self.request('/cgi-bin/invalid')
  273. res.read()
  274. self.assertEquals(res.status, 404)
  275. def test_authorization(self):
  276. headers = {'Authorization' : 'Basic %s' % \
  277. base64.b64encode('username:pass')}
  278. res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
  279. self.assertEquals(('Hello World\n', 'text/html', 200), \
  280. (res.read(), res.getheader('Content-type'), res.status))
  281. def test_main(verbose=None):
  282. try:
  283. cwd = os.getcwd()
  284. test_support.run_unittest(BaseHTTPServerTestCase,
  285. SimpleHTTPServerTestCase,
  286. CGIHTTPServerTestCase
  287. )
  288. finally:
  289. os.chdir(cwd)
  290. if __name__ == '__main__':
  291. test_main()