4
4
from http .server import HTTPServer , SimpleHTTPRequestHandler
5
5
from ssl import PROTOCOL_TLS_SERVER , SSLContext
6
6
7
+ import pytest
8
+ from requests .exceptions import SSLError
9
+
7
10
from test .test_base_service import AnyServiceV1
8
11
from ibm_cloud_sdk_core .authenticators import NoAuthAuthenticator
9
12
10
13
11
- def test_no_ssl_verification ():
14
+ def test_ssl_verification ():
12
15
# Load the certificate and the key files.
13
16
cert = os .path .join (os .path .dirname (__file__ ), '../resources/test_ssl.cert' )
14
17
key = os .path .join (os .path .dirname (__file__ ), '../resources/test_ssl.key' )
@@ -17,20 +20,28 @@ def test_no_ssl_verification():
17
20
ssl_context = SSLContext (PROTOCOL_TLS_SERVER )
18
21
ssl_context .load_cert_chain (certfile = cert , keyfile = key )
19
22
20
- # Create and start the server.
21
- server = HTTPServer (('localhost ' , 3333 ), SimpleHTTPRequestHandler )
23
+ # Create and start the server on a separate thread .
24
+ server = HTTPServer (('127.0.0.1 ' , 3333 ), SimpleHTTPRequestHandler )
22
25
server .socket = ssl_context .wrap_socket (server .socket , server_side = True )
23
26
t = threading .Thread (target = server .serve_forever )
24
27
t .start ()
25
28
26
- # Now create the service and call our server via HTTPS but without SSL verification.
27
- service = AnyServiceV1 ('2024-01-23' , authenticator = NoAuthAuthenticator ())
28
- service .set_service_url ('https://127.0.0.1:3333' )
29
- service .set_disable_ssl_verification (True )
30
- prepped = service .prepare_request ('GET' , url = '' )
31
-
32
- # Make the reqests, check the result and shutdown the server.
29
+ # We run everything in a big try-except-finally block to make sure we always
30
+ # shutdown the HTTP server gracefully .
33
31
try :
32
+ service = AnyServiceV1 ('2024-01-23' , service_url = 'https://127.0.0.1:3333' , authenticator = NoAuthAuthenticator ())
33
+ #
34
+ # First call the server with the default configuration.
35
+ # It should fail due to the invalid SSL cert.
36
+ assert service .disable_ssl_verification is False
37
+ prepped = service .prepare_request ('GET' , url = '/' )
38
+ with pytest .raises (SSLError ):
39
+ res = service .send (prepped )
40
+
41
+ # Now disable the SSL verification. The request shouldn't raise any issue.
42
+ service .set_disable_ssl_verification (True )
43
+ assert service .disable_ssl_verification is True
44
+ prepped = service .prepare_request ('GET' , url = '/' )
34
45
res = service .send (prepped )
35
46
assert res is not None
36
47
except Exception : # pylint: disable=try-except-raise
0 commit comments