mirror of
https://github.com/encounter/adk-python.git
synced 2026-07-09 18:19:28 -07:00
feat: add Spanner first-party toolset (breaking change to BigQueryTool, consolidating into generic GoogleTool)
Spanner toolset support basic operations to interact with Spanner table metadata and query results. Consolidate BigQueryTool into generic GoogleTool, so that BigQueryToolset and SpannerToolset can share. PiperOrigin-RevId: 794259782
This commit is contained in:
committed by
Copybara-Service
parent
10e3dfab1a
commit
1fc8d20ae8
@@ -74,8 +74,8 @@ def test_ask_data_insights_success(mock_get_stream):
|
||||
# 2. Create mock inputs for the function call
|
||||
mock_creds = mock.Mock()
|
||||
mock_creds.token = "fake-token"
|
||||
mock_config = mock.Mock()
|
||||
mock_config.max_query_result_rows = 100
|
||||
mock_settings = mock.Mock()
|
||||
mock_settings.max_query_result_rows = 100
|
||||
|
||||
# 3. Call the function under test
|
||||
result = data_insights_tool.ask_data_insights(
|
||||
@@ -83,7 +83,7 @@ def test_ask_data_insights_success(mock_get_stream):
|
||||
user_query_with_context="test query",
|
||||
table_references=[],
|
||||
credentials=mock_creds,
|
||||
config=mock_config,
|
||||
settings=mock_settings,
|
||||
)
|
||||
|
||||
# 4. Assert the results are as expected
|
||||
@@ -101,7 +101,7 @@ def test_ask_data_insights_handles_exception(mock_get_stream):
|
||||
# 2. Create mock inputs
|
||||
mock_creds = mock.Mock()
|
||||
mock_creds.token = "fake-token"
|
||||
mock_config = mock.Mock()
|
||||
mock_settings = mock.Mock()
|
||||
|
||||
# 3. Call the function
|
||||
result = data_insights_tool.ask_data_insights(
|
||||
@@ -109,7 +109,7 @@ def test_ask_data_insights_handles_exception(mock_get_stream):
|
||||
user_query_with_context="test query",
|
||||
table_references=[],
|
||||
credentials=mock_creds,
|
||||
config=mock_config,
|
||||
settings=mock_settings,
|
||||
)
|
||||
|
||||
# 4. Assert that the error was caught and formatted correctly
|
||||
|
||||
@@ -37,7 +37,7 @@ import pytest
|
||||
|
||||
|
||||
async def get_tool(
|
||||
name: str, tool_config: Optional[BigQueryToolConfig] = None
|
||||
name: str, tool_settings: Optional[BigQueryToolConfig] = None
|
||||
) -> BaseTool:
|
||||
"""Get a tool from BigQuery toolset.
|
||||
|
||||
@@ -54,7 +54,7 @@ async def get_tool(
|
||||
toolset = BigQueryToolset(
|
||||
credentials_config=credentials_config,
|
||||
tool_filter=[name],
|
||||
bigquery_tool_config=tool_config,
|
||||
bigquery_tool_config=tool_settings,
|
||||
)
|
||||
|
||||
tools = await toolset.get_tools()
|
||||
@@ -64,7 +64,7 @@ async def get_tool(
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("tool_config",),
|
||||
("tool_settings",),
|
||||
[
|
||||
pytest.param(None, id="no-config"),
|
||||
pytest.param(BigQueryToolConfig(), id="default-config"),
|
||||
@@ -75,14 +75,14 @@ async def get_tool(
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_sql_declaration_read_only(tool_config):
|
||||
async def test_execute_sql_declaration_read_only(tool_settings):
|
||||
"""Test BigQuery execute_sql tool declaration in read-only mode.
|
||||
|
||||
This test verifies that the execute_sql tool declaration reflects the
|
||||
read-only capability.
|
||||
"""
|
||||
tool_name = "execute_sql"
|
||||
tool = await get_tool(tool_name, tool_config)
|
||||
tool = await get_tool(tool_name, tool_settings)
|
||||
assert tool.name == tool_name
|
||||
assert tool.description == textwrap.dedent("""\
|
||||
Run a BigQuery or BigQuery ML SQL query in the project and return the result.
|
||||
@@ -92,7 +92,7 @@ async def test_execute_sql_declaration_read_only(tool_config):
|
||||
executed.
|
||||
query (str): The BigQuery SQL query to be executed.
|
||||
credentials (Credentials): The credentials to use for the request.
|
||||
config (BigQueryToolConfig): The configuration for the tool.
|
||||
settings (BigQueryToolConfig): The settings for the tool.
|
||||
tool_context (ToolContext): The context for the tool.
|
||||
|
||||
Returns:
|
||||
@@ -127,7 +127,7 @@ async def test_execute_sql_declaration_read_only(tool_config):
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("tool_config",),
|
||||
("tool_settings",),
|
||||
[
|
||||
pytest.param(
|
||||
BigQueryToolConfig(write_mode=WriteMode.ALLOWED),
|
||||
@@ -136,14 +136,14 @@ async def test_execute_sql_declaration_read_only(tool_config):
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_sql_declaration_write(tool_config):
|
||||
async def test_execute_sql_declaration_write(tool_settings):
|
||||
"""Test BigQuery execute_sql tool declaration with all writes enabled.
|
||||
|
||||
This test verifies that the execute_sql tool declaration reflects the write
|
||||
capability.
|
||||
"""
|
||||
tool_name = "execute_sql"
|
||||
tool = await get_tool(tool_name, tool_config)
|
||||
tool = await get_tool(tool_name, tool_settings)
|
||||
assert tool.name == tool_name
|
||||
assert tool.description == textwrap.dedent("""\
|
||||
Run a BigQuery or BigQuery ML SQL query in the project and return the result.
|
||||
@@ -153,7 +153,7 @@ async def test_execute_sql_declaration_write(tool_config):
|
||||
executed.
|
||||
query (str): The BigQuery SQL query to be executed.
|
||||
credentials (Credentials): The credentials to use for the request.
|
||||
config (BigQueryToolConfig): The configuration for the tool.
|
||||
settings (BigQueryToolConfig): The settings for the tool.
|
||||
tool_context (ToolContext): The context for the tool.
|
||||
|
||||
Returns:
|
||||
@@ -326,7 +326,7 @@ async def test_execute_sql_declaration_write(tool_config):
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("tool_config",),
|
||||
("tool_settings",),
|
||||
[
|
||||
pytest.param(
|
||||
BigQueryToolConfig(write_mode=WriteMode.PROTECTED),
|
||||
@@ -335,14 +335,14 @@ async def test_execute_sql_declaration_write(tool_config):
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_sql_declaration_protected_write(tool_config):
|
||||
async def test_execute_sql_declaration_protected_write(tool_settings):
|
||||
"""Test BigQuery execute_sql tool declaration with protected writes enabled.
|
||||
|
||||
This test verifies that the execute_sql tool declaration reflects the
|
||||
protected write capability.
|
||||
"""
|
||||
tool_name = "execute_sql"
|
||||
tool = await get_tool(tool_name, tool_config)
|
||||
tool = await get_tool(tool_name, tool_settings)
|
||||
assert tool.name == tool_name
|
||||
assert tool.description == textwrap.dedent("""\
|
||||
Run a BigQuery or BigQuery ML SQL query in the project and return the result.
|
||||
@@ -352,7 +352,7 @@ async def test_execute_sql_declaration_protected_write(tool_config):
|
||||
executed.
|
||||
query (str): The BigQuery SQL query to be executed.
|
||||
credentials (Credentials): The credentials to use for the request.
|
||||
config (BigQueryToolConfig): The configuration for the tool.
|
||||
settings (BigQueryToolConfig): The settings for the tool.
|
||||
tool_context (ToolContext): The context for the tool.
|
||||
|
||||
Returns:
|
||||
@@ -530,7 +530,7 @@ def test_execute_sql_select_stmt(write_mode):
|
||||
statement_type = "SELECT"
|
||||
query_result = [{"num": 123}]
|
||||
credentials = mock.create_autospec(Credentials, instance=True)
|
||||
tool_config = BigQueryToolConfig(write_mode=write_mode)
|
||||
tool_settings = BigQueryToolConfig(write_mode=write_mode)
|
||||
tool_context = mock.create_autospec(ToolContext, instance=True)
|
||||
tool_context.state.get.return_value = (
|
||||
"test-bq-session-id",
|
||||
@@ -550,7 +550,9 @@ def test_execute_sql_select_stmt(write_mode):
|
||||
bq_client.query_and_wait.return_value = query_result
|
||||
|
||||
# Test the tool
|
||||
result = execute_sql(project, query, credentials, tool_config, tool_context)
|
||||
result = execute_sql(
|
||||
project, query, credentials, tool_settings, tool_context
|
||||
)
|
||||
assert result == {"status": "SUCCESS", "rows": query_result}
|
||||
|
||||
|
||||
@@ -586,7 +588,7 @@ def test_execute_sql_non_select_stmt_write_allowed(query, statement_type):
|
||||
project = "my_project"
|
||||
query_result = []
|
||||
credentials = mock.create_autospec(Credentials, instance=True)
|
||||
tool_config = BigQueryToolConfig(write_mode=WriteMode.ALLOWED)
|
||||
tool_settings = BigQueryToolConfig(write_mode=WriteMode.ALLOWED)
|
||||
tool_context = mock.create_autospec(ToolContext, instance=True)
|
||||
|
||||
with mock.patch("google.cloud.bigquery.Client", autospec=False) as Client:
|
||||
@@ -602,7 +604,9 @@ def test_execute_sql_non_select_stmt_write_allowed(query, statement_type):
|
||||
bq_client.query_and_wait.return_value = query_result
|
||||
|
||||
# Test the tool
|
||||
result = execute_sql(project, query, credentials, tool_config, tool_context)
|
||||
result = execute_sql(
|
||||
project, query, credentials, tool_settings, tool_context
|
||||
)
|
||||
assert result == {"status": "SUCCESS", "rows": query_result}
|
||||
|
||||
|
||||
@@ -638,7 +642,7 @@ def test_execute_sql_non_select_stmt_write_blocked(query, statement_type):
|
||||
project = "my_project"
|
||||
query_result = []
|
||||
credentials = mock.create_autospec(Credentials, instance=True)
|
||||
tool_config = BigQueryToolConfig(write_mode=WriteMode.BLOCKED)
|
||||
tool_settings = BigQueryToolConfig(write_mode=WriteMode.BLOCKED)
|
||||
tool_context = mock.create_autospec(ToolContext, instance=True)
|
||||
|
||||
with mock.patch("google.cloud.bigquery.Client", autospec=False) as Client:
|
||||
@@ -654,7 +658,9 @@ def test_execute_sql_non_select_stmt_write_blocked(query, statement_type):
|
||||
bq_client.query_and_wait.return_value = query_result
|
||||
|
||||
# Test the tool
|
||||
result = execute_sql(project, query, credentials, tool_config, tool_context)
|
||||
result = execute_sql(
|
||||
project, query, credentials, tool_settings, tool_context
|
||||
)
|
||||
assert result == {
|
||||
"status": "ERROR",
|
||||
"error_details": "Read-only mode only supports SELECT statements.",
|
||||
@@ -693,7 +699,7 @@ def test_execute_sql_non_select_stmt_write_protected(query, statement_type):
|
||||
project = "my_project"
|
||||
query_result = []
|
||||
credentials = mock.create_autospec(Credentials, instance=True)
|
||||
tool_config = BigQueryToolConfig(write_mode=WriteMode.PROTECTED)
|
||||
tool_settings = BigQueryToolConfig(write_mode=WriteMode.PROTECTED)
|
||||
tool_context = mock.create_autospec(ToolContext, instance=True)
|
||||
tool_context.state.get.return_value = (
|
||||
"test-bq-session-id",
|
||||
@@ -714,7 +720,9 @@ def test_execute_sql_non_select_stmt_write_protected(query, statement_type):
|
||||
bq_client.query_and_wait.return_value = query_result
|
||||
|
||||
# Test the tool
|
||||
result = execute_sql(project, query, credentials, tool_config, tool_context)
|
||||
result = execute_sql(
|
||||
project, query, credentials, tool_settings, tool_context
|
||||
)
|
||||
assert result == {"status": "SUCCESS", "rows": query_result}
|
||||
|
||||
|
||||
@@ -756,7 +764,7 @@ def test_execute_sql_non_select_stmt_write_protected_persistent_target(
|
||||
project = "my_project"
|
||||
query_result = []
|
||||
credentials = mock.create_autospec(Credentials, instance=True)
|
||||
tool_config = BigQueryToolConfig(write_mode=WriteMode.PROTECTED)
|
||||
tool_settings = BigQueryToolConfig(write_mode=WriteMode.PROTECTED)
|
||||
tool_context = mock.create_autospec(ToolContext, instance=True)
|
||||
tool_context.state.get.return_value = (
|
||||
"test-bq-session-id",
|
||||
@@ -777,7 +785,9 @@ def test_execute_sql_non_select_stmt_write_protected_persistent_target(
|
||||
bq_client.query_and_wait.return_value = query_result
|
||||
|
||||
# Test the tool
|
||||
result = execute_sql(project, query, credentials, tool_config, tool_context)
|
||||
result = execute_sql(
|
||||
project, query, credentials, tool_settings, tool_context
|
||||
)
|
||||
assert result == {
|
||||
"status": "ERROR",
|
||||
"error_details": (
|
||||
@@ -808,7 +818,7 @@ def test_execute_sql_no_default_auth(
|
||||
statement_type = "SELECT"
|
||||
query_result = [{"num": 123}]
|
||||
credentials = mock.create_autospec(Credentials, instance=True)
|
||||
tool_config = BigQueryToolConfig(write_mode=write_mode)
|
||||
tool_settings = BigQueryToolConfig(write_mode=write_mode)
|
||||
tool_context = mock.create_autospec(ToolContext, instance=True)
|
||||
tool_context.state.get.return_value = (
|
||||
"test-bq-session-id",
|
||||
@@ -830,7 +840,7 @@ def test_execute_sql_no_default_auth(
|
||||
mock_query_and_wait.return_value = query_result
|
||||
|
||||
# Test the tool worked without invoking default auth
|
||||
result = execute_sql(project, query, credentials, tool_config, tool_context)
|
||||
result = execute_sql(project, query, credentials, tool_settings, tool_context)
|
||||
assert result == {"status": "SUCCESS", "rows": query_result}
|
||||
mock_default_auth.assert_not_called()
|
||||
|
||||
@@ -959,7 +969,7 @@ def test_execute_sql_result_dtype(
|
||||
project = "my_project"
|
||||
statement_type = "SELECT"
|
||||
credentials = mock.create_autospec(Credentials, instance=True)
|
||||
tool_config = BigQueryToolConfig()
|
||||
tool_settings = BigQueryToolConfig()
|
||||
tool_context = mock.create_autospec(ToolContext, instance=True)
|
||||
|
||||
# Simulate the result of query API
|
||||
@@ -971,5 +981,5 @@ def test_execute_sql_result_dtype(
|
||||
mock_query_and_wait.return_value = query_result
|
||||
|
||||
# Test the tool worked without invoking default auth
|
||||
result = execute_sql(project, query, credentials, tool_config, tool_context)
|
||||
result = execute_sql(project, query, credentials, tool_settings, tool_context)
|
||||
assert result == {"status": "SUCCESS", "rows": tool_result_rows}
|
||||
|
||||
@@ -15,8 +15,9 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from google.adk.tools.bigquery import BigQueryCredentialsConfig
|
||||
from google.adk.tools.bigquery import BigQueryTool
|
||||
from google.adk.tools.bigquery import BigQueryToolset
|
||||
from google.adk.tools.bigquery.config import BigQueryToolConfig
|
||||
from google.adk.tools.google_tool import GoogleTool
|
||||
import pytest
|
||||
|
||||
|
||||
@@ -30,12 +31,18 @@ async def test_bigquery_toolset_tools_default():
|
||||
credentials_config = BigQueryCredentialsConfig(
|
||||
client_id="abc", client_secret="def"
|
||||
)
|
||||
toolset = BigQueryToolset(credentials_config=credentials_config)
|
||||
toolset = BigQueryToolset(
|
||||
credentials_config=credentials_config, bigquery_tool_config=None
|
||||
)
|
||||
# Verify that the tool config is initialized to default values.
|
||||
assert isinstance(toolset._tool_settings, BigQueryToolConfig) # pylint: disable=protected-access
|
||||
assert toolset._tool_settings.__dict__ == BigQueryToolConfig().__dict__ # pylint: disable=protected-access
|
||||
|
||||
tools = await toolset.get_tools()
|
||||
assert tools is not None
|
||||
|
||||
assert len(tools) == 5
|
||||
assert all([isinstance(tool, BigQueryTool) for tool in tools])
|
||||
assert all([isinstance(tool, GoogleTool) for tool in tools])
|
||||
|
||||
expected_tool_names = set([
|
||||
"list_dataset_ids",
|
||||
@@ -77,7 +84,7 @@ async def test_bigquery_toolset_tools_selective(selected_tools):
|
||||
assert tools is not None
|
||||
|
||||
assert len(tools) == len(selected_tools)
|
||||
assert all([isinstance(tool, BigQueryTool) for tool in tools])
|
||||
assert all([isinstance(tool, GoogleTool) for tool in tools])
|
||||
|
||||
expected_tool_names = set(selected_tools)
|
||||
actual_tool_names = set([tool.name for tool in tools])
|
||||
@@ -114,7 +121,7 @@ async def test_bigquery_toolset_unknown_tool(selected_tools, returned_tools):
|
||||
assert tools is not None
|
||||
|
||||
assert len(tools) == len(returned_tools)
|
||||
assert all([isinstance(tool, BigQueryTool) for tool in tools])
|
||||
assert all([isinstance(tool, GoogleTool) for tool in tools])
|
||||
|
||||
expected_tool_names = set(returned_tools)
|
||||
actual_tool_names = set([tool.name for tool in tools])
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# Copyright 2025 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
@@ -0,0 +1,142 @@
|
||||
# Copyright 2025 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from unittest import mock
|
||||
|
||||
from google.adk.tools.spanner.client import get_spanner_client
|
||||
from google.auth.exceptions import DefaultCredentialsError
|
||||
from google.oauth2.credentials import Credentials
|
||||
import pytest
|
||||
|
||||
|
||||
def test_spanner_client_project():
|
||||
"""Test spanner client project."""
|
||||
# Trigger the spanner client creation
|
||||
client = get_spanner_client(
|
||||
project="test-gcp-project",
|
||||
credentials=mock.create_autospec(Credentials, instance=True),
|
||||
)
|
||||
|
||||
# Verify that the client has the desired project set
|
||||
assert client.project == "test-gcp-project"
|
||||
|
||||
|
||||
def test_spanner_client_project_set_explicit():
|
||||
"""Test spanner client creation does not invoke default auth."""
|
||||
# Let's simulate that no environment variables are set, so that any project
|
||||
# set in there does not interfere with this test
|
||||
with mock.patch.dict(os.environ, {}, clear=True):
|
||||
with mock.patch("google.auth.default", autospec=True) as mock_default_auth:
|
||||
# Simulate exception from default auth
|
||||
mock_default_auth.side_effect = DefaultCredentialsError(
|
||||
"Your default credentials were not found"
|
||||
)
|
||||
|
||||
# Trigger the spanner client creation
|
||||
client = get_spanner_client(
|
||||
project="test-gcp-project",
|
||||
credentials=mock.create_autospec(Credentials, instance=True),
|
||||
)
|
||||
|
||||
# If we are here that already means client creation did not call default
|
||||
# auth (otherwise we would have run into DefaultCredentialsError set
|
||||
# above). For the sake of explicitness, trivially assert that the default
|
||||
# auth was not called, and yet the project was set correctly
|
||||
mock_default_auth.assert_not_called()
|
||||
assert client.project == "test-gcp-project"
|
||||
|
||||
|
||||
def test_spanner_client_project_set_with_default_auth():
|
||||
"""Test spanner client creation invokes default auth to set the project."""
|
||||
# Let's simulate that no environment variables are set, so that any project
|
||||
# set in there does not interfere with this test
|
||||
with mock.patch.dict(os.environ, {}, clear=True):
|
||||
with mock.patch("google.auth.default", autospec=True) as mock_default_auth:
|
||||
# Simulate credentials
|
||||
mock_creds = mock.create_autospec(Credentials, instance=True)
|
||||
|
||||
# Simulate output of the default auth
|
||||
mock_default_auth.return_value = (mock_creds, "test-gcp-project")
|
||||
|
||||
# Trigger the spanner client creation
|
||||
client = get_spanner_client(
|
||||
project=None,
|
||||
credentials=mock_creds,
|
||||
)
|
||||
|
||||
# Verify that default auth was called once to set the client project
|
||||
mock_default_auth.assert_called_once()
|
||||
assert client.project == "test-gcp-project"
|
||||
|
||||
|
||||
def test_spanner_client_project_set_with_env():
|
||||
"""Test spanner client creation sets the project from environment variable."""
|
||||
# Let's simulate the project set in environment variables
|
||||
with mock.patch.dict(
|
||||
os.environ, {"GOOGLE_CLOUD_PROJECT": "test-gcp-project"}, clear=True
|
||||
):
|
||||
with mock.patch("google.auth.default", autospec=True) as mock_default_auth:
|
||||
# Simulate exception from default auth
|
||||
mock_default_auth.side_effect = DefaultCredentialsError(
|
||||
"Your default credentials were not found"
|
||||
)
|
||||
|
||||
# Trigger the spanner client creation
|
||||
client = get_spanner_client(
|
||||
project=None,
|
||||
credentials=mock.create_autospec(Credentials, instance=True),
|
||||
)
|
||||
|
||||
# If we are here that already means client creation did not call default
|
||||
# auth (otherwise we would have run into DefaultCredentialsError set
|
||||
# above). For the sake of explicitness, trivially assert that the default
|
||||
# auth was not called, and yet the project was set correctly
|
||||
mock_default_auth.assert_not_called()
|
||||
assert client.project == "test-gcp-project"
|
||||
|
||||
|
||||
def test_spanner_client_user_agent():
|
||||
"""Test spanner client user agent."""
|
||||
# Patch the Client constructor
|
||||
with mock.patch(
|
||||
"google.cloud.spanner.Client", autospec=True
|
||||
) as mock_client_class:
|
||||
# The mock instance that will be returned by spanner.Client()
|
||||
mock_instance = mock_client_class.return_value
|
||||
# The real spanner.Client instance has a `_client_info` attribute.
|
||||
# We need to add it to our mock instance so that the user_agent can be set.
|
||||
mock_instance._client_info = mock.Mock()
|
||||
|
||||
# Call the function that creates the client
|
||||
client = get_spanner_client(
|
||||
project="test-gcp-project",
|
||||
credentials=mock.create_autospec(Credentials, instance=True),
|
||||
)
|
||||
|
||||
# Verify that the Spanner Client was instantiated.
|
||||
mock_client_class.assert_called_once_with(
|
||||
project="test-gcp-project",
|
||||
credentials=mock.ANY,
|
||||
)
|
||||
|
||||
# Verify that the user_agent was set on the client instance.
|
||||
# The client returned by get_spanner_client is the mock instance.
|
||||
assert re.search(
|
||||
r"adk-spanner-tool google-adk/([0-9A-Za-z._\-+/]+)",
|
||||
client._client_info.user_agent,
|
||||
)
|
||||
@@ -0,0 +1,54 @@
|
||||
# Copyright 2025 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from google.adk.tools.spanner.spanner_credentials import SpannerCredentialsConfig
|
||||
# Mock the Google OAuth and API dependencies
|
||||
import google.auth.credentials
|
||||
import google.oauth2.credentials
|
||||
import pytest
|
||||
|
||||
|
||||
class TestSpannerCredentials:
|
||||
"""Test suite for Spanner credentials configuration validation.
|
||||
|
||||
This class tests the credential configuration logic that ensures
|
||||
either existing credentials or client ID/secret pairs are provided.
|
||||
"""
|
||||
|
||||
def test_valid_credentials_object_oauth2_credentials(self):
|
||||
"""Test that providing valid Credentials object works correctly with google.oauth2.credentials.Credentials.
|
||||
|
||||
When a user already has valid OAuth credentials, they should be able
|
||||
to pass them directly without needing to provide client ID/secret.
|
||||
"""
|
||||
# Create a mock oauth2 credentials object
|
||||
oauth2_creds = google.oauth2.credentials.Credentials(
|
||||
"test_token",
|
||||
client_id="test_client_id",
|
||||
client_secret="test_client_secret",
|
||||
scopes=[],
|
||||
)
|
||||
|
||||
config = SpannerCredentialsConfig(credentials=oauth2_creds)
|
||||
|
||||
# Verify that the credentials are properly stored and attributes are
|
||||
# extracted
|
||||
assert config.credentials == oauth2_creds
|
||||
assert config.client_id == "test_client_id"
|
||||
assert config.client_secret == "test_client_secret"
|
||||
assert config.scopes == [
|
||||
"https://www.googleapis.com/auth/spanner.data",
|
||||
]
|
||||
|
||||
assert config._token_cache_key == "spanner_token_cache" # pylint: disable=protected-access
|
||||
@@ -0,0 +1,27 @@
|
||||
# Copyright 2025 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from google.adk.tools.spanner.settings import SpannerToolSettings
|
||||
import pytest
|
||||
|
||||
|
||||
def test_spanner_tool_settings_experimental_warning():
|
||||
"""Test SpannerToolSettings experimental warning."""
|
||||
with pytest.warns(
|
||||
UserWarning,
|
||||
match="Tool settings defaults may have breaking change in the future.",
|
||||
):
|
||||
SpannerToolSettings()
|
||||
@@ -0,0 +1,185 @@
|
||||
# Copyright 2025 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from google.adk.tools.google_tool import GoogleTool
|
||||
from google.adk.tools.spanner import SpannerCredentialsConfig
|
||||
from google.adk.tools.spanner import SpannerToolset
|
||||
from google.adk.tools.spanner.settings import SpannerToolSettings
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_spanner_toolset_tools_default():
|
||||
"""Test default Spanner toolset.
|
||||
|
||||
This test verifies the behavior of the Spanner toolset when no filter is
|
||||
specified.
|
||||
"""
|
||||
credentials_config = SpannerCredentialsConfig(
|
||||
client_id="abc", client_secret="def"
|
||||
)
|
||||
toolset = SpannerToolset(credentials_config=credentials_config)
|
||||
assert isinstance(toolset._tool_settings, SpannerToolSettings) # pylint: disable=protected-access
|
||||
assert toolset._tool_settings.__dict__ == SpannerToolSettings().__dict__ # pylint: disable=protected-access
|
||||
tools = await toolset.get_tools()
|
||||
assert tools is not None
|
||||
|
||||
assert len(tools) == 6
|
||||
assert all([isinstance(tool, GoogleTool) for tool in tools])
|
||||
|
||||
expected_tool_names = set([
|
||||
"list_table_names",
|
||||
"list_table_indexes",
|
||||
"list_table_index_columns",
|
||||
"list_named_schemas",
|
||||
"get_table_schema",
|
||||
"execute_sql",
|
||||
])
|
||||
actual_tool_names = set([tool.name for tool in tools])
|
||||
assert actual_tool_names == expected_tool_names
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"selected_tools",
|
||||
[
|
||||
pytest.param([], id="None"),
|
||||
pytest.param(
|
||||
["list_table_names", "get_table_schema"],
|
||||
id="table-metadata",
|
||||
),
|
||||
pytest.param(["execute_sql"], id="query"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_spanner_toolset_selective(selected_tools):
|
||||
"""Test selective Spanner toolset.
|
||||
|
||||
This test verifies the behavior of the Spanner toolset when a filter is
|
||||
specified.
|
||||
|
||||
Args:
|
||||
selected_tools: A list of tool names to filter.
|
||||
"""
|
||||
credentials_config = SpannerCredentialsConfig(
|
||||
client_id="abc", client_secret="def"
|
||||
)
|
||||
toolset = SpannerToolset(
|
||||
credentials_config=credentials_config,
|
||||
tool_filter=selected_tools,
|
||||
spanner_tool_settings=SpannerToolSettings(),
|
||||
)
|
||||
tools = await toolset.get_tools()
|
||||
assert tools is not None
|
||||
|
||||
assert len(tools) == len(selected_tools)
|
||||
assert all([isinstance(tool, GoogleTool) for tool in tools])
|
||||
|
||||
expected_tool_names = set(selected_tools)
|
||||
actual_tool_names = set([tool.name for tool in tools])
|
||||
assert actual_tool_names == expected_tool_names
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("selected_tools", "returned_tools"),
|
||||
[
|
||||
pytest.param(["unknown"], [], id="all-unknown"),
|
||||
pytest.param(
|
||||
["unknown", "execute_sql"],
|
||||
["execute_sql"],
|
||||
id="mixed-known-unknown",
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_spanner_toolset_unknown_tool(selected_tools, returned_tools):
|
||||
"""Test Spanner toolset with unknown tools.
|
||||
|
||||
This test verifies the behavior of the Spanner toolset when unknown tools are
|
||||
specified in the filter.
|
||||
|
||||
Args:
|
||||
selected_tools: A list of tool names to filter, including unknown ones.
|
||||
returned_tools: A list of tool names that are expected to be returned.
|
||||
"""
|
||||
credentials_config = SpannerCredentialsConfig(
|
||||
client_id="abc", client_secret="def"
|
||||
)
|
||||
|
||||
toolset = SpannerToolset(
|
||||
credentials_config=credentials_config,
|
||||
tool_filter=selected_tools,
|
||||
spanner_tool_settings=SpannerToolSettings(),
|
||||
)
|
||||
|
||||
tools = await toolset.get_tools()
|
||||
assert tools is not None
|
||||
|
||||
assert len(tools) == len(returned_tools)
|
||||
assert all([isinstance(tool, GoogleTool) for tool in tools])
|
||||
|
||||
expected_tool_names = set(returned_tools)
|
||||
actual_tool_names = set([tool.name for tool in tools])
|
||||
assert actual_tool_names == expected_tool_names
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("selected_tools", "returned_tools"),
|
||||
[
|
||||
pytest.param(
|
||||
["execute_sql", "list_table_names"],
|
||||
["list_table_names"],
|
||||
id="read-not-added",
|
||||
),
|
||||
pytest.param(
|
||||
["list_table_names", "list_table_indexes"],
|
||||
["list_table_names", "list_table_indexes"],
|
||||
id="no-effect",
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_spanner_toolset_without_read_capability(
|
||||
selected_tools, returned_tools
|
||||
):
|
||||
"""Test Spanner toolset without read capability.
|
||||
|
||||
This test verifies the behavior of the Spanner toolset when read capability is
|
||||
not enabled.
|
||||
|
||||
Args:
|
||||
selected_tools: A list of tool names to filter.
|
||||
returned_tools: A list of tool names that are expected to be returned.
|
||||
"""
|
||||
credentials_config = SpannerCredentialsConfig(
|
||||
client_id="abc", client_secret="def"
|
||||
)
|
||||
|
||||
spanner_tool_settings = SpannerToolSettings(capabilities=[])
|
||||
toolset = SpannerToolset(
|
||||
credentials_config=credentials_config,
|
||||
tool_filter=selected_tools,
|
||||
spanner_tool_settings=spanner_tool_settings,
|
||||
)
|
||||
|
||||
tools = await toolset.get_tools()
|
||||
assert tools is not None
|
||||
|
||||
assert len(tools) == len(returned_tools)
|
||||
assert all([isinstance(tool, GoogleTool) for tool in tools])
|
||||
|
||||
expected_tool_names = set(returned_tools)
|
||||
actual_tool_names = set([tool.name for tool in tools])
|
||||
assert actual_tool_names == expected_tool_names
|
||||
+9
-9
@@ -18,9 +18,9 @@ from unittest.mock import Mock
|
||||
from unittest.mock import patch
|
||||
|
||||
from google.adk.auth.auth_tool import AuthConfig
|
||||
from google.adk.tools._google_credentials import GoogleCredentialsManager
|
||||
from google.adk.tools.bigquery.bigquery_credentials import BIGQUERY_TOKEN_CACHE_KEY
|
||||
from google.adk.tools.bigquery.bigquery_credentials import BigQueryCredentialsConfig
|
||||
from google.adk.tools.bigquery.bigquery_credentials import BigQueryCredentialsManager
|
||||
from google.adk.tools.tool_context import ToolContext
|
||||
from google.auth.credentials import Credentials as AuthCredentials
|
||||
from google.auth.exceptions import RefreshError
|
||||
@@ -29,8 +29,8 @@ from google.oauth2.credentials import Credentials as OAuthCredentials
|
||||
import pytest
|
||||
|
||||
|
||||
class TestBigQueryCredentialsManager:
|
||||
"""Test suite for BigQueryCredentialsManager OAuth flow handling.
|
||||
class TestGoogleCredentialsManager:
|
||||
"""Test suite for GoogleCredentialsManager OAuth flow handling.
|
||||
|
||||
This class tests the complex credential management logic including
|
||||
credential validation, refresh, OAuth flow orchestration, and the
|
||||
@@ -63,7 +63,7 @@ class TestBigQueryCredentialsManager:
|
||||
@pytest.fixture
|
||||
def manager(self, credentials_config):
|
||||
"""Create a credentials manager instance for testing."""
|
||||
return BigQueryCredentialsManager(credentials_config)
|
||||
return GoogleCredentialsManager(credentials_config)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("credentials_class",),
|
||||
@@ -336,7 +336,7 @@ class TestBigQueryCredentialsManager:
|
||||
|
||||
# Use the full module path as it appears in the project structure
|
||||
with patch(
|
||||
"google.adk.tools.bigquery.bigquery_credentials.google.oauth2.credentials.Credentials",
|
||||
"google.adk.tools._google_credentials.google.oauth2.credentials.Credentials",
|
||||
return_value=mock_creds,
|
||||
) as mock_credentials_class:
|
||||
result = await manager.get_valid_credentials(mock_tool_context)
|
||||
@@ -388,7 +388,7 @@ class TestBigQueryCredentialsManager:
|
||||
credential manager, avoiding redundant OAuth flows.
|
||||
"""
|
||||
# Create first manager instance and simulate OAuth completion
|
||||
manager1 = BigQueryCredentialsManager(credentials_config)
|
||||
manager1 = GoogleCredentialsManager(credentials_config)
|
||||
|
||||
# Mock OAuth response for first manager
|
||||
mock_auth_response = Mock()
|
||||
@@ -412,7 +412,7 @@ class TestBigQueryCredentialsManager:
|
||||
|
||||
# Use the correct module path - without the 'src.' prefix
|
||||
with patch(
|
||||
"google.adk.tools.bigquery.bigquery_credentials.google.oauth2.credentials.Credentials",
|
||||
"google.adk.tools._google_credentials.google.oauth2.credentials.Credentials",
|
||||
return_value=mock_creds,
|
||||
) as mock_credentials_class:
|
||||
# Complete OAuth flow with first manager
|
||||
@@ -424,7 +424,7 @@ class TestBigQueryCredentialsManager:
|
||||
assert cached_creds_json == mock_creds_json
|
||||
|
||||
# Create second manager instance (simulating new request/session)
|
||||
manager2 = BigQueryCredentialsManager(credentials_config)
|
||||
manager2 = GoogleCredentialsManager(credentials_config)
|
||||
credentials_config.credentials = None
|
||||
|
||||
# Reset auth response to None (no new OAuth flow available)
|
||||
@@ -432,7 +432,7 @@ class TestBigQueryCredentialsManager:
|
||||
|
||||
# Mock the from_authorized_user_info method for the second manager
|
||||
with patch(
|
||||
"google.adk.tools.bigquery.bigquery_credentials.google.oauth2.credentials.Credentials.from_authorized_user_info"
|
||||
"google.adk.tools._google_credentials.google.oauth2.credentials.Credentials.from_authorized_user_info"
|
||||
) as mock_from_json:
|
||||
mock_cached_creds = Mock(spec=OAuthCredentials)
|
||||
mock_cached_creds.valid = True
|
||||
+39
-24
@@ -16,18 +16,19 @@
|
||||
from unittest.mock import Mock
|
||||
from unittest.mock import patch
|
||||
|
||||
from google.adk.tools._google_credentials import GoogleCredentialsManager
|
||||
from google.adk.tools.bigquery.bigquery_credentials import BigQueryCredentialsConfig
|
||||
from google.adk.tools.bigquery.bigquery_credentials import BigQueryCredentialsManager
|
||||
from google.adk.tools.bigquery.bigquery_tool import BigQueryTool
|
||||
from google.adk.tools.bigquery.config import BigQueryToolConfig
|
||||
from google.adk.tools.google_tool import GoogleTool
|
||||
from google.adk.tools.spanner.settings import SpannerToolSettings
|
||||
from google.adk.tools.tool_context import ToolContext
|
||||
# Mock the Google OAuth and API dependencies
|
||||
from google.oauth2.credentials import Credentials
|
||||
import pytest
|
||||
|
||||
|
||||
class TestBigQueryTool:
|
||||
"""Test suite for BigQueryTool OAuth integration and execution.
|
||||
class TestGoogleTool:
|
||||
"""Test suite for GoogleTool OAuth integration and execution.
|
||||
|
||||
This class tests the high-level tool execution logic that combines
|
||||
credential management with actual function execution.
|
||||
@@ -88,18 +89,18 @@ class TestBigQueryTool:
|
||||
def test_tool_initialization_with_credentials(
|
||||
self, sample_function, credentials_config
|
||||
):
|
||||
"""Test that BigQueryTool initializes correctly with credentials.
|
||||
"""Test that GoogleTool initializes correctly with credentials.
|
||||
|
||||
The tool should properly inherit from FunctionTool while adding
|
||||
Google API specific credential management capabilities.
|
||||
"""
|
||||
tool = BigQueryTool(
|
||||
tool = GoogleTool(
|
||||
func=sample_function, credentials_config=credentials_config
|
||||
)
|
||||
|
||||
assert tool.func == sample_function
|
||||
assert tool._credentials_manager is not None
|
||||
assert isinstance(tool._credentials_manager, BigQueryCredentialsManager)
|
||||
assert isinstance(tool._credentials_manager, GoogleCredentialsManager)
|
||||
# Verify that 'credentials' parameter is ignored in function signature analysis
|
||||
assert "credentials" in tool._ignore_params
|
||||
|
||||
@@ -109,7 +110,7 @@ class TestBigQueryTool:
|
||||
Some tools might handle authentication externally or use service
|
||||
accounts, so credential management should be optional.
|
||||
"""
|
||||
tool = BigQueryTool(func=sample_function, credentials_config=None)
|
||||
tool = GoogleTool(func=sample_function, credentials_config=None)
|
||||
|
||||
assert tool.func == sample_function
|
||||
assert tool._credentials_manager is None
|
||||
@@ -123,7 +124,7 @@ class TestBigQueryTool:
|
||||
This tests the main happy path where credentials are available
|
||||
and the underlying function executes successfully.
|
||||
"""
|
||||
tool = BigQueryTool(
|
||||
tool = GoogleTool(
|
||||
func=sample_function, credentials_config=credentials_config
|
||||
)
|
||||
|
||||
@@ -152,7 +153,7 @@ class TestBigQueryTool:
|
||||
When credentials aren't available and OAuth flow is needed,
|
||||
the tool should return a user-friendly message rather than failing.
|
||||
"""
|
||||
tool = BigQueryTool(
|
||||
tool = GoogleTool(
|
||||
func=sample_function, credentials_config=credentials_config
|
||||
)
|
||||
|
||||
@@ -178,7 +179,7 @@ class TestBigQueryTool:
|
||||
Tools without credential managers should execute normally,
|
||||
passing None for credentials if the function accepts them.
|
||||
"""
|
||||
tool = BigQueryTool(func=sample_function, credentials_config=None)
|
||||
tool = GoogleTool(func=sample_function, credentials_config=None)
|
||||
|
||||
result = await tool.run_async(
|
||||
args={"param1": "test_value"}, tool_context=mock_tool_context
|
||||
@@ -196,7 +197,7 @@ class TestBigQueryTool:
|
||||
The tool should correctly detect and execute async functions,
|
||||
which is important for tools that make async API calls.
|
||||
"""
|
||||
tool = BigQueryTool(
|
||||
tool = GoogleTool(
|
||||
func=async_sample_function, credentials_config=credentials_config
|
||||
)
|
||||
|
||||
@@ -227,7 +228,7 @@ class TestBigQueryTool:
|
||||
def failing_function(param1: str, credentials: Credentials = None) -> dict:
|
||||
raise ValueError("Something went wrong")
|
||||
|
||||
tool = BigQueryTool(
|
||||
tool = GoogleTool(
|
||||
func=failing_function, credentials_config=credentials_config
|
||||
)
|
||||
|
||||
@@ -259,7 +260,7 @@ class TestBigQueryTool:
|
||||
) -> dict:
|
||||
return {"success": True}
|
||||
|
||||
tool = BigQueryTool(
|
||||
tool = GoogleTool(
|
||||
func=complex_function, credentials_config=credentials_config
|
||||
)
|
||||
|
||||
@@ -270,7 +271,7 @@ class TestBigQueryTool:
|
||||
assert "optional_param" not in mandatory_args
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"input_config, expected_config",
|
||||
"input_settings, expected_settings",
|
||||
[
|
||||
pytest.param(
|
||||
BigQueryToolConfig(
|
||||
@@ -281,22 +282,36 @@ class TestBigQueryTool:
|
||||
),
|
||||
id="with_provided_config",
|
||||
),
|
||||
pytest.param(
|
||||
None,
|
||||
BigQueryToolConfig(),
|
||||
id="with_none_config_creates_default",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_tool_config_initialization(self, input_config, expected_config):
|
||||
"""Tests that self._tool_config is correctly initialized by comparing its
|
||||
def test_tool_bigquery_config_initialization(
|
||||
self, input_settings, expected_settings
|
||||
):
|
||||
"""Tests that self._tool_settings is correctly initialized by comparing its
|
||||
|
||||
final state to an expected configuration object.
|
||||
"""
|
||||
# 1. Initialize the tool with the parameterized config
|
||||
tool = BigQueryTool(func=None, bigquery_tool_config=input_config)
|
||||
tool = GoogleTool(func=None, tool_settings=input_settings)
|
||||
|
||||
# 2. Assert that the tool's config has the same attribute values
|
||||
# as the expected config. Comparing the __dict__ is a robust
|
||||
# way to check for value equality.
|
||||
assert tool._tool_config.__dict__ == expected_config.__dict__ # pylint: disable=protected-access
|
||||
assert tool._tool_settings.__dict__ == expected_settings.__dict__ # pylint: disable=protected-access
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"input_settings, expected_settings",
|
||||
[
|
||||
pytest.param(
|
||||
SpannerToolSettings(max_executed_query_result_rows=10),
|
||||
SpannerToolSettings(max_executed_query_result_rows=10),
|
||||
id="with_provided_settings",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_tool_spanner_settings_initialization(
|
||||
self, input_settings, expected_settings
|
||||
):
|
||||
"""Tests that self._tool_settings is correctly initialized with SpannerToolSettings by comparing its final state to an expected configuration object."""
|
||||
tool = GoogleTool(func=None, tool_settings=input_settings)
|
||||
assert tool._tool_settings.__dict__ == expected_settings.__dict__ # pylint: disable=protected-access
|
||||
Reference in New Issue
Block a user