chore: import upstream snapshot with attribution
Continuous Integration / Pre-commit Linter (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.10) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.11) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.12) (push) Has been cancelled
Continuous Integration / Mypy Check (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.12) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / Unit Tests (Python 3.14) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Has been cancelled
Copybara PR Handler / close-imported-pr (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Has been cancelled
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:25:13 +08:00
commit ec2b666284
2231 changed files with 491535 additions and 0 deletions
@@ -0,0 +1,135 @@
# Copyright 2026 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 unittest import mock
from google.adk.tools.pubsub import client
from google.cloud import pubsub_v1
from google.oauth2.credentials import Credentials
import pytest
# Save original Pub/Sub classes before patching.
# This is necessary because create_autospec cannot be used on a mock object,
# and mock.patch.object(..., autospec=True) replaces the class with a mock.
# We need the original class to create spec'd mocks in side_effect.
ORIG_PUBLISHER = pubsub_v1.PublisherClient
ORIG_SUBSCRIBER = pubsub_v1.SubscriberClient
@pytest.fixture(autouse=True)
def cleanup_pubsub_clients():
"""Automatically clean up Pub/Sub client caches after each test.
This fixture runs automatically for all tests in this file,
ensuring that client caches are cleared between tests to prevent
state leakage and ensure test isolation.
"""
yield
client.cleanup_clients()
@mock.patch.object(pubsub_v1, "PublisherClient", autospec=True)
def test_get_publisher_client(mock_publisher_client):
"""Test get_publisher_client factory."""
mock_creds = mock.create_autospec(Credentials, instance=True, spec_set=True)
client.get_publisher_client(credentials=mock_creds)
mock_publisher_client.assert_called_once()
_, kwargs = mock_publisher_client.call_args
assert kwargs["credentials"] == mock_creds
assert "client_info" in kwargs
assert isinstance(kwargs["batch_settings"], pubsub_v1.types.BatchSettings)
assert kwargs["batch_settings"].max_messages == 1
@mock.patch.object(pubsub_v1, "PublisherClient", autospec=True)
def test_get_publisher_client_with_options(mock_publisher_client):
"""Test get_publisher_client factory with options."""
mock_creds = mock.create_autospec(Credentials, instance=True, spec_set=True)
mock_options = mock.create_autospec(
pubsub_v1.types.PublisherOptions, instance=True, spec_set=True
)
client.get_publisher_client(
credentials=mock_creds, publisher_options=mock_options
)
mock_publisher_client.assert_called_once()
_, kwargs = mock_publisher_client.call_args
assert kwargs["credentials"] == mock_creds
assert kwargs["publisher_options"] == mock_options
assert "client_info" in kwargs
assert isinstance(kwargs["batch_settings"], pubsub_v1.types.BatchSettings)
assert kwargs["batch_settings"].max_messages == 1
@mock.patch.object(pubsub_v1, "PublisherClient", autospec=True)
def test_get_publisher_client_caching(mock_publisher_client):
"""Test get_publisher_client caching behavior."""
mock_creds = mock.create_autospec(Credentials, instance=True, spec_set=True)
mock_publisher_client.side_effect = [
mock.create_autospec(ORIG_PUBLISHER, instance=True, spec_set=True),
mock.create_autospec(ORIG_PUBLISHER, instance=True, spec_set=True),
]
# First call - should create client
client1 = client.get_publisher_client(credentials=mock_creds)
mock_publisher_client.assert_called_once()
# Second call with same args - should return cached client
client2 = client.get_publisher_client(credentials=mock_creds)
assert client1 is client2
mock_publisher_client.assert_called_once() # Still called only once
# Call with different args - should create new client
mock_creds2 = mock.create_autospec(Credentials, instance=True, spec_set=True)
client3 = client.get_publisher_client(credentials=mock_creds2)
assert client3 is not client1
assert mock_publisher_client.call_count == 2
@mock.patch.object(pubsub_v1, "SubscriberClient", autospec=True)
def test_get_subscriber_client(mock_subscriber_client):
"""Test get_subscriber_client factory."""
mock_creds = mock.create_autospec(Credentials, instance=True, spec_set=True)
client.get_subscriber_client(credentials=mock_creds)
mock_subscriber_client.assert_called_once()
_, kwargs = mock_subscriber_client.call_args
assert kwargs["credentials"] == mock_creds
assert "client_info" in kwargs
@mock.patch.object(pubsub_v1, "SubscriberClient", autospec=True)
def test_get_subscriber_client_caching(mock_subscriber_client):
"""Test get_subscriber_client caching behavior."""
mock_creds = mock.create_autospec(Credentials, instance=True, spec_set=True)
mock_subscriber_client.side_effect = [
mock.create_autospec(ORIG_SUBSCRIBER, instance=True, spec_set=True),
mock.create_autospec(ORIG_SUBSCRIBER, instance=True, spec_set=True),
]
# First call - should create client
client1 = client.get_subscriber_client(credentials=mock_creds)
mock_subscriber_client.assert_called_once()
# Second call with same args - should return cached client
client2 = client.get_subscriber_client(credentials=mock_creds)
assert client1 is client2
mock_subscriber_client.assert_called_once() # Still called only once
# Call with different args - should create new client
mock_creds2 = mock.create_autospec(Credentials, instance=True, spec_set=True)
client3 = client.get_subscriber_client(credentials=mock_creds2)
assert client3 is not client1
assert mock_subscriber_client.call_count == 2
@@ -0,0 +1,27 @@
# Copyright 2026 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.pubsub.config import PubSubToolConfig
def test_pubsub_tool_config_init():
"""Test PubSubToolConfig initialization."""
config = PubSubToolConfig(project_id="my-project")
assert config.project_id == "my-project"
def test_pubsub_tool_config_default():
"""Test PubSubToolConfig default initialization."""
config = PubSubToolConfig()
assert config.project_id is None
@@ -0,0 +1,133 @@
# Copyright 2026 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 unittest import mock
from google.adk.tools.pubsub.pubsub_credentials import PUBSUB_DEFAULT_SCOPE
from google.adk.tools.pubsub.pubsub_credentials import PubSubCredentialsConfig
from google.auth.credentials import Credentials
import google.oauth2.credentials
import pytest
"""Test suite for PubSub credentials configuration validation.
This class tests the credential configuration logic that ensures
either existing credentials or client ID/secret pairs are provided.
"""
def test_pubsub_credentials_config_client_id_secret():
"""Test PubSubCredentialsConfig with client_id and client_secret.
Ensures that when client_id and client_secret are provided, the config
object is created with the correct attributes.
"""
config = PubSubCredentialsConfig(client_id="abc", client_secret="def")
assert config.client_id == "abc"
assert config.client_secret == "def"
assert config.scopes == PUBSUB_DEFAULT_SCOPE
assert config.credentials is None
def test_pubsub_credentials_config_existing_creds():
"""Test PubSubCredentialsConfig with existing generic credentials.
Ensures that when a generic Credentials object is provided, it is
stored correctly.
"""
mock_creds = mock.create_autospec(Credentials, instance=True)
config = PubSubCredentialsConfig(credentials=mock_creds)
assert config.credentials == mock_creds
assert config.client_id is None
assert config.client_secret is None
def test_pubsub_credentials_config_oauth2_creds():
"""Test PubSubCredentialsConfig with existing OAuth2 credentials.
Ensures that when a google.oauth2.credentials.Credentials object is
provided, the client_id, client_secret, and scopes are extracted
from the credentials object.
"""
mock_creds = mock.create_autospec(
google.oauth2.credentials.Credentials, instance=True
)
mock_creds.client_id = "oauth_client_id"
mock_creds.client_secret = "oauth_client_secret"
mock_creds.scopes = ["fake_scope"]
config = PubSubCredentialsConfig(credentials=mock_creds)
assert config.client_id == "oauth_client_id"
assert config.client_secret == "oauth_client_secret"
assert config.scopes == ["fake_scope"]
@pytest.mark.parametrize(
"credentials, client_id, client_secret",
[
# No arguments provided
(None, None, None),
# Only client_id is provided
(None, "abc", None),
],
)
def test_pubsub_credentials_config_validation_errors(
credentials, client_id, client_secret
):
"""Test PubSubCredentialsConfig validation errors.
Ensures that ValueError is raised when invalid combinations of credentials
and client ID/secret are provided.
Args:
credentials: The credentials object to pass.
client_id: The client ID to pass.
client_secret: The client secret to pass.
"""
with pytest.raises(
ValueError,
match=(
"Must provide one of credentials, external_access_token_key, or"
" client_id and client_secret pair."
),
):
PubSubCredentialsConfig(
credentials=credentials,
client_id=client_id,
client_secret=client_secret,
)
def test_pubsub_credentials_config_both_credentials_and_client_provided():
"""Test PubSubCredentialsConfig validation errors.
Ensures that ValueError is raised when invalid combinations of credentials
and client ID/secret are provided.
Args:
credentials: The credentials object to pass.
client_id: The client ID to pass.
client_secret: The client secret to pass.
"""
with pytest.raises(
ValueError,
match=(
"If credentials are provided, external_access_token_key, client_id,"
" client_secret, and scopes must not be provided."
),
):
PubSubCredentialsConfig(
credentials=mock.create_autospec(Credentials, instance=True),
client_id="abc",
client_secret="def",
)
@@ -0,0 +1,330 @@
# Copyright 2026 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
from unittest import mock
from google.adk.tools.pubsub import client as pubsub_client_lib
from google.adk.tools.pubsub import message_tool
from google.adk.tools.pubsub.config import PubSubToolConfig
from google.api_core import future
from google.cloud import pubsub_v1
from google.cloud.pubsub_v1 import types
from google.oauth2.credentials import Credentials
from google.protobuf import timestamp_pb2
@mock.patch.dict(os.environ, {}, clear=True)
@mock.patch.object(pubsub_v1.PublisherClient, "publish", autospec=True)
@mock.patch.object(pubsub_client_lib, "get_publisher_client", autospec=True)
def test_publish_message(mock_get_publisher_client, mock_publish):
"""Test publish_message tool invocation."""
topic_name = "projects/my_project_id/topics/my_topic"
message = "Hello World"
mock_credentials = mock.create_autospec(Credentials, instance=True)
tool_settings = PubSubToolConfig(project_id="my_project_id")
mock_publisher_client = mock.create_autospec(
pubsub_v1.PublisherClient, instance=True
)
mock_get_publisher_client.return_value = mock_publisher_client
mock_future = mock.create_autospec(future.Future, instance=True)
mock_future.result.return_value = "message_id"
mock_publisher_client.publish.return_value = mock_future
result = message_tool.publish_message(
topic_name, message, mock_credentials, tool_settings
)
assert result["message_id"] == "message_id"
mock_get_publisher_client.assert_called_once()
mock_publisher_client.publish.assert_called_once()
@mock.patch.dict(os.environ, {}, clear=True)
@mock.patch.object(pubsub_v1.PublisherClient, "publish", autospec=True)
@mock.patch.object(pubsub_client_lib, "get_publisher_client", autospec=True)
def test_publish_message_with_ordering_key(
mock_get_publisher_client, mock_publish
):
"""Test publish_message tool invocation with ordering_key."""
topic_name = "projects/my_project_id/topics/my_topic"
message = "Hello World"
ordering_key = "key1"
mock_credentials = mock.create_autospec(Credentials, instance=True)
tool_settings = PubSubToolConfig(project_id="my_project_id")
mock_publisher_client = mock.create_autospec(
pubsub_v1.PublisherClient, instance=True
)
mock_get_publisher_client.return_value = mock_publisher_client
mock_future = mock.create_autospec(future.Future, instance=True)
mock_future.result.return_value = "message_id"
mock_publisher_client.publish.return_value = mock_future
result = message_tool.publish_message(
topic_name,
message,
mock_credentials,
tool_settings,
ordering_key=ordering_key,
)
assert result["message_id"] == "message_id"
mock_get_publisher_client.assert_called_once()
_, kwargs = mock_get_publisher_client.call_args
assert kwargs["publisher_options"].enable_message_ordering is True
mock_publisher_client.publish.assert_called_once()
# Verify ordering_key was passed
_, kwargs = mock_publisher_client.publish.call_args
assert kwargs["ordering_key"] == ordering_key
@mock.patch.dict(os.environ, {}, clear=True)
@mock.patch.object(pubsub_v1.PublisherClient, "publish", autospec=True)
@mock.patch.object(pubsub_client_lib, "get_publisher_client", autospec=True)
def test_publish_message_with_attributes(
mock_get_publisher_client, mock_publish
):
"""Test publish_message tool invocation with attributes."""
topic_name = "projects/my_project_id/topics/my_topic"
message = "Hello World"
attributes = {"key1": "value1", "key2": "value2"}
mock_credentials = mock.create_autospec(Credentials, instance=True)
tool_settings = PubSubToolConfig(project_id="my_project_id")
mock_publisher_client = mock.create_autospec(
pubsub_v1.PublisherClient, instance=True
)
mock_get_publisher_client.return_value = mock_publisher_client
mock_future = mock.create_autospec(future.Future, instance=True)
mock_future.result.return_value = "message_id"
mock_publisher_client.publish.return_value = mock_future
result = message_tool.publish_message(
topic_name,
message,
mock_credentials,
tool_settings,
attributes=attributes,
)
assert result["message_id"] == "message_id"
mock_get_publisher_client.assert_called_once()
mock_publisher_client.publish.assert_called_once()
# Verify attributes were passed
_, kwargs = mock_publisher_client.publish.call_args
assert kwargs["key1"] == "value1"
assert kwargs["key2"] == "value2"
@mock.patch.dict(os.environ, {}, clear=True)
@mock.patch.object(pubsub_v1.PublisherClient, "publish", autospec=True)
@mock.patch.object(pubsub_client_lib, "get_publisher_client", autospec=True)
def test_publish_message_exception(mock_get_publisher_client, mock_publish):
"""Test publish_message tool invocation when exception occurs."""
topic_name = "projects/my_project_id/topics/my_topic"
message = "Hello World"
mock_credentials = mock.create_autospec(Credentials, instance=True)
tool_settings = PubSubToolConfig(project_id="my_project_id")
mock_publisher_client = mock.create_autospec(
pubsub_v1.PublisherClient, instance=True
)
mock_get_publisher_client.return_value = mock_publisher_client
# Simulate an exception during publish
mock_publisher_client.publish.side_effect = Exception("Publish failed")
result = message_tool.publish_message(
topic_name,
message,
mock_credentials,
tool_settings,
)
assert result["status"] == "ERROR"
assert "Publish failed" in result["error_details"]
mock_get_publisher_client.assert_called_once()
mock_publisher_client.publish.assert_called_once()
@mock.patch.dict(os.environ, {}, clear=True)
@mock.patch.object(pubsub_client_lib, "get_subscriber_client", autospec=True)
def test_pull_messages(mock_get_subscriber_client):
"""Test pull_messages tool invocation."""
subscription_name = "projects/my_project_id/subscriptions/my_sub"
mock_credentials = mock.create_autospec(Credentials, instance=True)
tool_settings = PubSubToolConfig(project_id="my_project_id")
mock_subscriber_client = mock.create_autospec(
pubsub_v1.SubscriberClient, instance=True
)
mock_get_subscriber_client.return_value = mock_subscriber_client
mock_response = mock.create_autospec(types.PullResponse, instance=True)
mock_message = mock.MagicMock()
mock_message.message.message_id = "123"
mock_message.message.data = b"Hello"
mock_message.message.attributes = {"key": "value"}
mock_message.message.ordering_key = "ABC"
mock_publish_time = mock.MagicMock()
mock_publish_time.rfc3339.return_value = "2023-01-01T00:00:00Z"
mock_message.message.publish_time = mock_publish_time
mock_message.ack_id = "ack_123"
mock_response.received_messages = [mock_message]
mock_subscriber_client.pull.return_value = mock_response
result = message_tool.pull_messages(
subscription_name, mock_credentials, tool_settings
)
expected_message = {
"message_id": "123",
"data": "Hello",
"attributes": {"key": "value"},
"ordering_key": "ABC",
"publish_time": "2023-01-01T00:00:00Z",
"ack_id": "ack_123",
}
assert result["messages"] == [expected_message]
mock_get_subscriber_client.assert_called_once()
mock_subscriber_client.pull.assert_called_once_with(
subscription=subscription_name, max_messages=1
)
mock_subscriber_client.acknowledge.assert_not_called()
@mock.patch.dict(os.environ, {}, clear=True)
@mock.patch.object(pubsub_client_lib, "get_subscriber_client", autospec=True)
def test_pull_messages_auto_ack(mock_get_subscriber_client):
"""Test pull_messages tool invocation with auto_ack."""
subscription_name = "projects/my_project_id/subscriptions/my_sub"
mock_credentials = mock.create_autospec(Credentials, instance=True)
tool_settings = PubSubToolConfig(project_id="my_project_id")
mock_subscriber_client = mock.create_autospec(
pubsub_v1.SubscriberClient, instance=True
)
mock_get_subscriber_client.return_value = mock_subscriber_client
mock_response = mock.create_autospec(types.PullResponse, instance=True)
mock_message = mock.MagicMock()
mock_message.message.message_id = "123"
mock_message.message.data = b"Hello"
mock_message.message.attributes = {}
mock_publish_time = mock.MagicMock()
mock_publish_time.rfc3339.return_value = "2023-01-01T00:00:00Z"
mock_message.message.publish_time = mock_publish_time
mock_message.ack_id = "ack_123"
mock_response.received_messages = [mock_message]
mock_subscriber_client.pull.return_value = mock_response
result = message_tool.pull_messages(
subscription_name,
mock_credentials,
tool_settings,
max_messages=5,
auto_ack=True,
)
assert len(result["messages"]) == 1
mock_get_subscriber_client.assert_called_once()
mock_subscriber_client.pull.assert_called_once_with(
subscription=subscription_name, max_messages=5
)
mock_subscriber_client.acknowledge.assert_called_once_with(
subscription=subscription_name, ack_ids=["ack_123"]
)
@mock.patch.dict(os.environ, {}, clear=True)
@mock.patch.object(pubsub_client_lib, "get_subscriber_client", autospec=True)
def test_pull_messages_exception(mock_get_subscriber_client):
"""Test pull_messages tool invocation when exception occurs."""
subscription_name = "projects/my_project_id/subscriptions/my_sub"
mock_credentials = mock.create_autospec(Credentials, instance=True)
tool_settings = PubSubToolConfig(project_id="my_project_id")
mock_subscriber_client = mock.create_autospec(
pubsub_v1.SubscriberClient, instance=True
)
mock_get_subscriber_client.return_value = mock_subscriber_client
mock_subscriber_client.pull.side_effect = Exception("Pull failed")
result = message_tool.pull_messages(
subscription_name, mock_credentials, tool_settings
)
assert result["status"] == "ERROR"
assert "Pull failed" in result["error_details"]
@mock.patch.dict(os.environ, {}, clear=True)
@mock.patch.object(pubsub_client_lib, "get_subscriber_client", autospec=True)
def test_acknowledge_messages(mock_get_subscriber_client):
"""Test acknowledge_messages tool invocation."""
subscription_name = "projects/my_project_id/subscriptions/my_sub"
ack_ids = ["ack1", "ack2"]
mock_credentials = mock.create_autospec(Credentials, instance=True)
tool_settings = PubSubToolConfig(project_id="my_project_id")
mock_subscriber_client = mock.create_autospec(
pubsub_v1.SubscriberClient, instance=True
)
mock_get_subscriber_client.return_value = mock_subscriber_client
result = message_tool.acknowledge_messages(
subscription_name, ack_ids, mock_credentials, tool_settings
)
assert result["status"] == "SUCCESS"
mock_get_subscriber_client.assert_called_once()
mock_subscriber_client.acknowledge.assert_called_once_with(
subscription=subscription_name, ack_ids=ack_ids
)
@mock.patch.dict(os.environ, {}, clear=True)
@mock.patch.object(pubsub_client_lib, "get_subscriber_client", autospec=True)
def test_acknowledge_messages_exception(mock_get_subscriber_client):
"""Test acknowledge_messages tool invocation when exception occurs."""
subscription_name = "projects/my_project_id/subscriptions/my_sub"
ack_ids = ["ack1"]
mock_credentials = mock.create_autospec(Credentials, instance=True)
tool_settings = PubSubToolConfig(project_id="my_project_id")
mock_subscriber_client = mock.create_autospec(
pubsub_v1.SubscriberClient, instance=True
)
mock_get_subscriber_client.return_value = mock_subscriber_client
mock_subscriber_client.acknowledge.side_effect = Exception("Ack failed")
result = message_tool.acknowledge_messages(
subscription_name, ack_ids, mock_credentials, tool_settings
)
assert result["status"] == "ERROR"
assert "Ack failed" in result["error_details"]
@@ -0,0 +1,131 @@
# Copyright 2026 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.pubsub import PubSubCredentialsConfig
from google.adk.tools.pubsub import PubSubToolset
from google.adk.tools.pubsub.config import PubSubToolConfig
import pytest
@pytest.mark.asyncio
async def test_pubsub_toolset_tools_default():
"""Test default PubSub toolset.
This test verifies the behavior of the PubSub toolset when no filter is
specified.
"""
credentials_config = PubSubCredentialsConfig(
client_id="abc", client_secret="def"
)
toolset = PubSubToolset(
credentials_config=credentials_config, pubsub_tool_config=None
)
# Verify that the tool config is initialized to default values.
assert isinstance(toolset._tool_settings, PubSubToolConfig) # pylint: disable=protected-access
assert toolset._tool_settings.__dict__ == PubSubToolConfig().__dict__ # pylint: disable=protected-access
tools = await toolset.get_tools()
assert tools is not None
assert len(tools) == 3
assert all(isinstance(tool, GoogleTool) for tool in tools)
expected_tool_names = set([
"publish_message",
"pull_messages",
"acknowledge_messages",
])
actual_tool_names = {tool.name for tool in tools}
assert actual_tool_names == expected_tool_names
@pytest.mark.parametrize(
"selected_tools",
[
pytest.param([], id="None"),
pytest.param(["publish_message"], id="publish"),
pytest.param(["pull_messages"], id="pull"),
pytest.param(["acknowledge_messages"], id="ack"),
],
)
@pytest.mark.asyncio
async def test_pubsub_toolset_tools_selective(selected_tools):
"""Test PubSub toolset with filter.
This test verifies the behavior of the PubSub toolset when filter is
specified. A use case for this would be when the agent builder wants to
use only a subset of the tools provided by the toolset.
Args:
selected_tools: The list of tools to select from the toolset.
"""
credentials_config = PubSubCredentialsConfig(
client_id="abc", client_secret="def"
)
toolset = PubSubToolset(
credentials_config=credentials_config, tool_filter=selected_tools
)
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 = {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", "publish_message"],
["publish_message"],
id="mixed-known-unknown",
),
],
)
@pytest.mark.asyncio
async def test_pubsub_toolset_unknown_tool(selected_tools, returned_tools):
"""Test PubSub toolset with filter.
This test verifies the behavior of the PubSub toolset when filter is
specified with an unknown tool.
Args:
selected_tools: The list of tools to select from the toolset.
returned_tools: The list of tools that are expected to be returned.
"""
credentials_config = PubSubCredentialsConfig(
client_id="abc", client_secret="def"
)
toolset = PubSubToolset(
credentials_config=credentials_config, tool_filter=selected_tools
)
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 = {tool.name for tool in tools}
assert actual_tool_names == expected_tool_names