/
test_https.py
92 lines (67 loc) · 3.06 KB
/
test_https.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import logging
import ssl
import sys
import unittest
from dummyserver.testcase import HTTPSDummyServerTestCase
from dummyserver.server import DEFAULT_CA, DEFAULT_CA_BAD
from urllib3 import HTTPSConnectionPool
from urllib3.connectionpool import VerifiedHTTPSConnection
from urllib3.exceptions import SSLError
log = logging.getLogger('urllib3.connectionpool')
log.setLevel(logging.NOTSET)
log.addHandler(logging.StreamHandler(sys.stdout))
class TestHTTPS(HTTPSDummyServerTestCase):
def setUp(self):
self._pool = HTTPSConnectionPool(self.host, self.port)
def test_simple(self):
r = self._pool.request('GET', '/specific_method',
fields={'method': 'GET'})
self.assertEqual(r.status, 200, r.data)
def test_set_ssl_version_to_tlsv1(self):
self._pool.ssl_version = ssl.PROTOCOL_TLSv1
r = self._pool.request('GET', '/specific_method',
fields={'method': 'GET'})
self.assertEqual(r.status, 200, r.data)
def test_set_ssl_version_to_sslv2(self):
self._pool.ssl_version = ssl.PROTOCOL_SSLv2
with self.assertRaises(SSLError):
r = self._pool.request('GET', '/specific_method',
fields={'method': 'GET'})
def test_verified(self):
https_pool = HTTPSConnectionPool(self.host, self.port,
cert_reqs='CERT_REQUIRED')
conn = https_pool._new_conn()
self.assertEqual(conn.__class__, VerifiedHTTPSConnection)
self.assertRaises(SSLError, https_pool.request, 'GET', '/')
https_pool.ca_certs = DEFAULT_CA_BAD
try:
https_pool.request('GET', '/')
self.fail("Didn't raise SSL error with wrong CA")
except SSLError as e:
self.assertTrue('certificate verify failed' in str(e),
"Expected 'certificate verify failed', instead got: %r" % e)
https_pool.ca_certs = DEFAULT_CA
https_pool.request('GET', '/') # Should succeed without exceptions.
https_fail_pool = HTTPSConnectionPool('127.0.0.1', self.port,
cert_reqs='CERT_REQUIRED')
https_fail_pool.ca_certs = DEFAULT_CA
try:
https_fail_pool.request('GET', '/')
self.fail("Didn't raise SSL invalid common name")
except SSLError as e:
self.assertTrue("doesn't match" in str(e))
def test_no_ssl(self):
import urllib3.connectionpool
OriginalHTTPSConnection = urllib3.connectionpool.HTTPSConnection
OriginalSSL = urllib3.connectionpool.ssl
urllib3.connectionpool.HTTPSConnection = None
urllib3.connectionpool.ssl = None
self.assertRaises(SSLError, self._pool._new_conn)
self.assertRaises(SSLError,
lambda: self._pool.request('GET', '/specific_method',
fields={'method': 'GET'}))
# Undo
urllib3.HTTPSConnection = OriginalHTTPSConnection
urllib3.connectionpool.ssl = OriginalSSL
if __name__ == '__main__':
unittest.main()