test_urllib2.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. """unit tests module for ndg.httpsclient.urllib2_build_opener module
  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. from urllib2 import URLError
  12. import unittest
  13. from OpenSSL import SSL
  14. from ndg.httpsclient.test import Constants
  15. from ndg.httpsclient.urllib2_build_opener import build_opener
  16. class Urllib2TestCase(unittest.TestCase):
  17. """Unit tests for urllib2 functionality"""
  18. def test01_urllib2_build_opener(self):
  19. opener = build_opener()
  20. self.assert_(opener)
  21. def test02_open(self):
  22. opener = build_opener()
  23. res = opener.open(Constants.TEST_URI)
  24. self.assert_(res)
  25. print("res = %s" % res.read())
  26. def test03_open_fails_unknown_loc(self):
  27. opener = build_opener()
  28. self.failUnlessRaises(URLError, opener.open, Constants.TEST_URI2)
  29. def test04_open_peer_cert_verification_fails(self):
  30. # Explicitly set empty CA directory to make verification fail
  31. ctx = SSL.Context(SSL.SSLv3_METHOD)
  32. verify_callback = lambda conn, x509, errnum, errdepth, preverify_ok: \
  33. preverify_ok
  34. ctx.set_verify(SSL.VERIFY_PEER, verify_callback)
  35. ctx.load_verify_locations(None, './')
  36. opener = build_opener(ssl_context=ctx)
  37. self.failUnlessRaises(SSL.Error, opener.open, Constants.TEST_URI)
  38. if __name__ == "__main__":
  39. unittest.main()