def test_self_signed_cert(self): # start and connect to a local https server using a self-signed cert. local_server = None host = 'localhost' port = 4443 cert_file_path = join(dirname(realpath(__file__)), 'self_signed.pem') try: local_server = SimpleHTTPSServer(cert_file_path=cert_file_path, host=host, port=port) local_server.start() urlopen(_make_url(host, port=port)) except URLError as e: if e.reason and isinstance(e.reason, ssl.SSLError): # this is the right error. pass else: raise else: # we don't expect zero errors. self.fail("Didn't encounter expected error") finally: if local_server: local_server.stop()
def test_cert_with_different_domain(self): # connect using IP address instead of name in cert; this should fail # cert domain validation. url_cert_wrong_domain = _make_url(socket.gethostbyname(_SERVER)) if six.PY2: with self.assertRaises((ssl.CertificateError, URLError)): urlopen(url_cert_wrong_domain) else: with self.assertRaises(URLError) as cm: urlopen(url_cert_wrong_domain) self.assertIsInstance(cm.exception.reason, ssl.CertificateError)
def side_effect(*args, **kwargs): http.urlopen("https://localhost/error")
def test_no_https(self): # try http; should complete without any certificate-related error. res = urlopen(_make_url(_SERVER, protocol="http")) self.assertEqual(res.getcode(), _SUCCESS_RESPONSE_CODE)
def test_valid_cert(self): # Connect to server with a valid cert signed by a CA. res = urlopen(_make_url(_SERVER)) self.assertEqual(res.getcode(), _SUCCESS_RESPONSE_CODE)
def error(*args, **kwargs): http.urlopen("https://localhost/error")