Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(db_api): allow file path for credentials #221

Merged
merged 5 commits into from Mar 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
18 changes: 13 additions & 5 deletions google/cloud/spanner_dbapi/connection.py
Expand Up @@ -353,10 +353,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.

Expand All @@ -380,9 +383,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():
Expand Down
25 changes: 25 additions & 0 deletions tests/unit/spanner_dbapi/test_connect.py
Expand Up @@ -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
)