1616import os
1717
1818from flask .testing import FlaskClient
19-
19+ from google .auth import default
20+ import google .auth .transport .requests
2021import pytest
22+ import requests
2123
2224import app
2325
2426logger = logging .getLogger ()
2527
2628
29+ CA_FILENAME = "certs/ca.pem"
30+ SQLADMIN_API_ENDPOINT = "https://sqladmin.googleapis.com"
31+ SQLADMIN_API_VERSION = "v1beta4"
32+
33+
2734# load proper environment variables
2835def setup_test_env ():
2936 os .environ ["DB_USER" ] = os .environ ["SQLSERVER_USER" ]
@@ -33,6 +40,32 @@ def setup_test_env():
3340 os .environ ["INSTANCE_HOST" ] = os .environ ["SQLSERVER_INSTANCE_HOST" ]
3441 os .environ ["INSTANCE_CONNECTION_NAME" ] = os .environ ["SQLSERVER_INSTANCE" ]
3542
43+ project , _ , instance = os .environ ["INSTANCE_CONNECTION_NAME" ].split (":" )
44+ download_ca_cert (project , instance )
45+ os .environ ["DB_ROOT_CERT" ] = CA_FILENAME
46+
47+
48+ def download_ca_cert (project , instance ):
49+ """ Download server CA cert"""
50+ scopes = ["https://www.googleapis.com/auth/sqlservice.admin" ]
51+ credentials , _ = default (scopes = scopes )
52+
53+ if not credentials .valid :
54+ request = google .auth .transport .requests .Request ()
55+ credentials .refresh (request )
56+
57+ headers = {
58+ "Authorization" : f"Bearer { credentials .token } " ,
59+ }
60+ url = (f"{ SQLADMIN_API_ENDPOINT } /sql/{ SQLADMIN_API_VERSION } "
61+ f"/projects/{ project } /instances/{ instance } /connectSettings" )
62+
63+ resp = requests .get (url , headers = headers )
64+ server_ca_cert = resp .json ()["serverCaCert" ]["cert" ]
65+
66+ with open (CA_FILENAME , "w+" ) as ca_out :
67+ ca_out .write (server_ca_cert )
68+
3669
3770@pytest .fixture (scope = "module" )
3871def client () -> FlaskClient :
0 commit comments