diff --git a/google/cloud/spanner_dbapi/connection.py b/google/cloud/spanner_dbapi/connection.py index 382882e516..9befe2027d 100644 --- a/google/cloud/spanner_dbapi/connection.py +++ b/google/cloud/spanner_dbapi/connection.py @@ -357,10 +357,13 @@ def connect( instances, tables and data. If not provided, will attempt to determine from the environment. - :type credentials: :class:`~google.auth.credentials.Credentials` + :type credentials: Union[:class:`~google.auth.credentials.Credentials`, str] :param credentials: (Optional) The authorization credentials to attach to requests. These credentials identify this application - to the service. If none are specified, the client will + to the service. These credentials may be specified as + a file path indicating where to retrieve the service + account JSON for the credentials to connect to + Cloud Spanner. If none are specified, the client will attempt to ascertain the credentials from the environment. @@ -384,9 +387,14 @@ def connect( user_agent=user_agent or DEFAULT_USER_AGENT, python_version=PY_VERSION ) - client = spanner.Client( - project=project, credentials=credentials, client_info=client_info - ) + if isinstance(credentials, str): + client = spanner.Client.from_service_account_json( + credentials, project=project, client_info=client_info + ) + else: + client = spanner.Client( + project=project, credentials=credentials, client_info=client_info + ) instance = client.instance(instance_id) if not instance.exists(): diff --git a/tests/unit/spanner_dbapi/test_connect.py b/tests/unit/spanner_dbapi/test_connect.py index 771b9d4a7f..a18781ffd1 100644 --- a/tests/unit/spanner_dbapi/test_connect.py +++ b/tests/unit/spanner_dbapi/test_connect.py @@ -139,3 +139,28 @@ def test_sessions_pool(self): ): connect("test-instance", database_id, pool=pool) database_mock.assert_called_once_with(database_id, pool=pool) + + def test_connect_w_credential_file_path(self): + from google.cloud.spanner_dbapi import connect + from google.cloud.spanner_dbapi import Connection + + PROJECT = "test-project" + USER_AGENT = "user-agent" + credentials = "dummy/file/path.json" + + with mock.patch( + "google.cloud.spanner_v1.Client.from_service_account_json" + ) as client_mock: + connection = connect( + "test-instance", + "test-database", + PROJECT, + credentials=credentials, + user_agent=USER_AGENT, + ) + + self.assertIsInstance(connection, Connection) + + client_mock.assert_called_once_with( + credentials, project=PROJECT, client_info=mock.ANY + )