test_https.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """unit tests module for ndg.httpsclient.https.HTTPSconnection class
  2. PyOpenSSL utility to make a httplib-like interface suitable for use with
  3. urllib2
  4. """
  5. __author__ = "P J Kershaw (STFC)"
  6. __date__ = "06/01/12"
  7. __copyright__ = "(C) 2012 Science and Technology Facilities Council"
  8. __license__ = "BSD - see LICENSE file in top-level directory"
  9. __contact__ = "Philip.Kershaw@stfc.ac.uk"
  10. __revision__ = '$Id$'
  11. import logging
  12. logging.basicConfig(level=logging.DEBUG)
  13. log = logging.getLogger(__name__)
  14. import unittest
  15. import socket
  16. from OpenSSL import SSL
  17. from ndg.httpsclient.test import Constants
  18. from ndg.httpsclient.https import HTTPSConnection
  19. class TestHTTPSConnection(unittest.TestCase):
  20. '''Test ndg HTTPS client HTTPSConnection class'''
  21. def test01_open(self):
  22. conn = HTTPSConnection(Constants.HOSTNAME, port=Constants.PORT)
  23. conn.connect()
  24. conn.request('GET', '/')
  25. resp = conn.getresponse()
  26. print('Response = %s' % resp.read())
  27. conn.close()
  28. def test02_open_fails(self):
  29. conn = HTTPSConnection(Constants.HOSTNAME, port=Constants.PORT2)
  30. self.failUnlessRaises(socket.error, conn.connect)
  31. def test03_ssl_verification_of_peer_fails(self):
  32. ctx = SSL.Context(SSL.SSLv3_METHOD)
  33. def verify_callback(conn, x509, errnum, errdepth, preverify_ok):
  34. log.debug('SSL peer certificate verification failed for %r',
  35. x509.get_subject())
  36. return preverify_ok
  37. ctx.set_verify(SSL.VERIFY_PEER, verify_callback)
  38. ctx.set_verify_depth(9)
  39. # Set bad location - unit test dir has no CA certs to verify with
  40. ctx.load_verify_locations(None, Constants.UNITTEST_DIR)
  41. conn = HTTPSConnection(Constants.HOSTNAME, port=Constants.PORT,
  42. ssl_context=ctx)
  43. conn.connect()
  44. self.failUnlessRaises(SSL.Error, conn.request, 'GET', '/')
  45. def test03_ssl_verification_of_peer_succeeds(self):
  46. ctx = SSL.Context(SSL.SSLv3_METHOD)
  47. verify_callback = lambda conn, x509, errnum, errdepth, preverify_ok: \
  48. preverify_ok
  49. ctx.set_verify(SSL.VERIFY_PEER, verify_callback)
  50. ctx.set_verify_depth(9)
  51. # Set correct location for CA certs to verify with
  52. ctx.load_verify_locations(None, Constants.CACERT_DIR)
  53. conn = HTTPSConnection(Constants.HOSTNAME, port=Constants.PORT,
  54. ssl_context=ctx)
  55. conn.connect()
  56. conn.request('GET', '/')
  57. resp = conn.getresponse()
  58. print('Response = %s' % resp.read())
  59. if __name__ == "__main__":
  60. unittest.main()